Esempio n. 1
0
 /**
  * Determines whether there exist at least one instance of a certain object type in the database.
  *
  * @param string $objectType Name of treated entity type.
  *
  * @return boolean Whether at least one instance exists or not.
  */
 protected function hasExistingInstances($objectType)
 {
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     if (!in_array($objectType, $controllerHelper->getObjectTypes('util', array('util' => 'model', 'action' => 'hasExistingInstances')))) {
         throw new \Exception('Error! Invalid object type received.');
     }
     $entityClass = 'Reviews_Entity_' . ucwords($objectType);
     $repository = $this->entityManager->getRepository($entityClass);
     return $repository->selectCount() > 0;
 }
Esempio n. 2
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;
 }
Esempio n. 3
0
 /**
  * Clear cache for given item. Can be called from other modules to clear an item cache.
  *
  * @param $args['ot']   the treated object type
  * @param $args['item'] the actual object
  */
 public function clearItemCache(array $args = array())
 {
     if (!isset($args['ot']) || !isset($args['item'])) {
         return;
     }
     $objectType = $args['ot'];
     $item = $args['item'];
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     $utilArgs = array('api' => 'cache', 'action' => 'clearItemCache');
     if (!in_array($objectType, $controllerHelper->getObjectTypes('controllerAction', $utilArgs))) {
         return;
     }
     if ($item && !is_array($item) && !is_object($item)) {
         $item = ModUtil::apiFunc($this->name, 'selection', 'getEntity', array('ot' => $objectType, 'id' => $item, 'useJoins' => false, 'slimMode' => true));
     }
     if (!$item) {
         return;
     }
     // create full identifier (considering composite keys)
     $idFields = ModUtil::apiFunc($this->name, 'selection', 'getIdFields', array('ot' => $objectType));
     $instanceId = '';
     foreach ($idFields as $idField) {
         if (!empty($instanceId)) {
             $instanceId .= '_';
         }
         $instanceId .= $item[$idField];
     }
     // Clear View_cache
     $cacheIds = array();
     $cacheIds[] = 'main';
     $cacheIds[] = 'view';
     $cacheIds[] = $instanceId;
     $view = Zikula_View::getInstance('Reviews');
     foreach ($cacheIds as $cacheId) {
         $view->clear_cache(null, $cacheId);
     }
     // Clear Theme_cache
     $cacheIds = array();
     $cacheIds[] = 'homepage';
     // for homepage (can be assigned in the Settings module)
     $cacheIds[] = 'Reviews/user/main';
     // main function
     $cacheIds[] = 'Reviews/user/view/' . $objectType;
     // view function (list views)
     $cacheIds[] = 'Reviews/user/display/' . $objectType . '|' . $instanceId;
     // display function (detail views)
     $theme = Zikula_View_Theme::getInstance();
     $theme->clear_cacheid_allthemes($cacheIds);
 }
Esempio n. 4
0
 /**
  * Returns available admin panel links.
  *
  * @return array Array of admin links.
  */
 public function getLinks()
 {
     $links = array();
     if (SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_READ)) {
         $links[] = array('url' => ModUtil::url($this->name, 'user', 'main'), 'text' => $this->__('Frontend'), 'title' => $this->__('Switch to user area.'), 'class' => 'z-icon-es-home');
     }
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     $utilArgs = array('api' => 'admin', 'action' => 'getLinks');
     $allowedObjectTypes = $controllerHelper->getObjectTypes('api', $utilArgs);
     if (in_array('review', $allowedObjectTypes) && SecurityUtil::checkPermission($this->name . ':Review:', '::', ACCESS_ADMIN)) {
         $links[] = array('url' => ModUtil::url($this->name, 'admin', 'view', array('ot' => 'review')), 'text' => $this->__('Reviews'), 'title' => $this->__('Review list'));
     }
     if (SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_ADMIN)) {
         $links[] = array('url' => ModUtil::url($this->name, 'admin', 'config'), 'text' => $this->__('Configuration'), 'title' => $this->__('Manage settings for this application'));
     }
     return $links;
 }
Esempio n. 5
0
 /**
  * Loads the data.
  *
  * @param array $data Data array with parameters.
  */
 public function loadData(&$data)
 {
     $serviceManager = ServiceUtil::getManager();
     $controllerHelper = new Reviews_Util_Controller($serviceManager);
     $utilArgs = array('name' => 'detail');
     if (!isset($data['objectType']) || !in_array($data['objectType'], $controllerHelper->getObjectTypes('contentType', $utilArgs))) {
         $data['objectType'] = $controllerHelper->getDefaultObjectType('contentType', $utilArgs);
     }
     $this->objectType = $data['objectType'];
     if (!isset($data['id'])) {
         $data['id'] = null;
     }
     if (!isset($data['displayMode'])) {
         $data['displayMode'] = 'embed';
     }
     $this->id = $data['id'];
     $this->displayMode = $data['displayMode'];
 }
Esempio n. 6
0
 /**
  * This method provides a generic item detail view.
  *
  * @param string  $ot           Treated object type.
  * @param string  $tpl          Name of alternative template (for alternative display options, feeds and xml output)
  * @param boolean $raw          Optional way to display a template instead of fetching it (needed for standalone output)
  *
  * @return mixed Output.
  */
 public function display()
 {
     $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' => 'display');
     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());
     $idFields = ModUtil::apiFunc($this->name, 'selection', 'getIdFields', array('ot' => $objectType));
     // retrieve identifier of the object we wish to view
     $idValues = $controllerHelper->retrieveIdentifier($this->request, array(), $objectType, $idFields);
     $hasIdentifier = $controllerHelper->isValidIdentifier($idValues);
     // check for unique permalinks (without id)
     $hasSlug = false;
     $slug = '';
     if ($hasIdentifier === false) {
         $entityClass = $this->name . '_Entity_' . ucwords($objectType);
         $meta = $this->entityManager->getClassMetadata($entityClass);
         $hasSlug = $meta->hasField('slug') && $meta->isUniqueField('slug');
         if ($hasSlug) {
             $slug = $this->request->query->filter('slug', '', FILTER_SANITIZE_STRING);
             $hasSlug = !empty($slug);
         }
     }
     $hasIdentifier |= $hasSlug;
     $this->throwNotFoundUnless($hasIdentifier, $this->__('Error! Invalid identifier received.'));
     $entity = ModUtil::apiFunc($this->name, 'selection', 'getEntity', array('ot' => $objectType, 'id' => $idValues, 'slug' => $slug));
     $this->throwNotFoundUnless($entity != null, $this->__('No such item.'));
     unset($idValues);
     $entity->initWorkflow();
     // build ModUrl instance for display hooks; also create identifier for permission check
     $currentUrlArgs = array('ot' => $objectType);
     $instanceId = '';
     foreach ($idFields as $idField) {
         $currentUrlArgs[$idField] = $entity[$idField];
         if (!empty($instanceId)) {
             $instanceId .= '_';
         }
         $instanceId .= $entity[$idField];
     }
     $currentUrlArgs['id'] = $instanceId;
     if (isset($entity['slug'])) {
         $currentUrlArgs['slug'] = $entity['slug'];
     }
     $currentUrlObject = new Zikula_ModUrl($this->name, 'user', 'display', ZLanguage::getLanguageCode(), $currentUrlArgs);
     $this->throwForbiddenUnless(SecurityUtil::checkPermission($this->name . ':' . ucwords($objectType) . ':', $instanceId . '::', ACCESS_READ), LogUtil::getErrorMsgPermission());
     $viewHelper = new Reviews_Util_View($this->serviceManager);
     $templateFile = $viewHelper->getViewTemplate($this->view, 'user', $objectType, 'display', array());
     // set cache id
     $component = $this->name . ':' . ucwords($objectType) . ':';
     $instance = $instanceId . '::';
     $accessLevel = ACCESS_READ;
     if (SecurityUtil::checkPermission($component, $instance, ACCESS_COMMENT)) {
         $accessLevel = ACCESS_COMMENT;
     }
     if (SecurityUtil::checkPermission($component, $instance, ACCESS_EDIT)) {
         $accessLevel = ACCESS_EDIT;
     }
     $this->view->setCacheId($objectType . '|' . $instanceId . '|a' . $accessLevel);
     // assign output data to view object.
     $this->view->assign($objectType, $entity)->assign('currentUrlObject', $currentUrlObject)->assign($repository->getAdditionalTemplateParameters('controllerAction', $utilArgs));
     //$controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     $controllerHelper->addView($entity['id']);
     // fetch and return the appropriate template
     return $viewHelper->processTemplate($this->view, 'user', $objectType, 'display', array(), $templateFile);
 }
Esempio n. 7
0
 /**
  * Popup selector for Scribite plugins.
  * Finds items of a certain object type.
  *
  * @param string $objectType The object type.
  * @param string $editor     Name of used Scribite editor.
  * @param string $sort       Sorting field.
  * @param string $sortdir    Sorting direction.
  * @param int    $pos        Current pager position.
  * @param int    $num        Amount of entries to display.
  *
  * @return output The external item finder page
  */
 public function finder()
 {
     PageUtil::addVar('stylesheet', ThemeUtil::getModuleStylesheet('Reviews'));
     $getData = $this->request->query;
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     $objectType = $getData->filter('objectType', 'review', FILTER_SANITIZE_STRING);
     $utilArgs = array('controller' => 'external', 'action' => 'finder');
     if (!in_array($objectType, $controllerHelper->getObjectTypes('controller', $utilArgs))) {
         $objectType = $controllerHelper->getDefaultObjectType('controllerType', $utilArgs);
     }
     $this->throwForbiddenUnless(SecurityUtil::checkPermission('Reviews:' . ucwords($objectType) . ':', '::', ACCESS_COMMENT), LogUtil::getErrorMsgPermission());
     $entityClass = 'Reviews_Entity_' . ucwords($objectType);
     $repository = $this->entityManager->getRepository($entityClass);
     $repository->setControllerArguments(array());
     $editor = $getData->filter('editor', '', FILTER_SANITIZE_STRING);
     if (empty($editor) || !in_array($editor, array('xinha', 'tinymce'))) {
         return $this->__('Error: Invalid editor context given for external controller action.');
     }
     // fetch selected categories to reselect them in the output
     // the actual filtering is done inside the repository class
     $categoryIds = ModUtil::apiFunc('Reviews', 'category', 'retrieveCategoriesFromRequest', array('ot' => $objectType, 'source' => 'GET'));
     $sort = $getData->filter('sort', '', FILTER_SANITIZE_STRING);
     if (empty($sort) || !in_array($sort, $repository->getAllowedSortingFields())) {
         $sort = $repository->getDefaultSortingField();
     }
     $sortdir = $getData->filter('sortdir', '', FILTER_SANITIZE_STRING);
     $sdir = strtolower($sortdir);
     if ($sdir != 'asc' && $sdir != 'desc') {
         $sdir = 'asc';
     }
     $sortParam = $sort . ' ' . $sdir;
     // the current offset which is used to calculate the pagination
     $currentPage = (int) $getData->filter('pos', 1, FILTER_VALIDATE_INT);
     // the number of items displayed on a page for pagination
     $resultsPerPage = (int) $getData->filter('num', 0, FILTER_VALIDATE_INT);
     if ($resultsPerPage == 0) {
         $resultsPerPage = $this->getVar('pageSize', 20);
     }
     $where = '';
     list($entities, $objectCount) = $repository->selectWherePaginated($where, $sortParam, $currentPage, $resultsPerPage);
     foreach ($entities as $k => $entity) {
         $entity->initWorkflow();
     }
     $view = Zikula_View::getInstance('Reviews', false);
     $view->assign('editorName', $editor)->assign('objectType', $objectType)->assign('items', $entities)->assign('sort', $sort)->assign('sortdir', $sdir)->assign('currentPage', $currentPage)->assign('pager', array('numitems' => $objectCount, 'itemsperpage' => $resultsPerPage));
     // assign category properties
     $properties = null;
     if (in_array($objectType, $this->categorisableObjectTypes)) {
         $properties = ModUtil::apiFunc('Reviews', 'category', 'getAllProperties', array('ot' => $objectType));
     }
     $view->assign('properties', $properties)->assign('catIds', $categoryIds);
     return $view->display('external/' . $objectType . '/find.tpl');
 }
Esempio n. 8
0
 /**
  * form custom url string
  *
  * @author Mark West
  * @return string custom url string
  */
 public function encodeurl($args)
 {
     // check if we have the required input
     if (!isset($args['modname']) || !isset($args['func'])) {
         throw new \InvalidArgumentException(__('Invalid arguments array received.'));
     }
     // set default values
     if (!isset($args['type'])) {
         $args['type'] = 'user';
     }
     if (!isset($args['args'])) {
         $args['args'] = array();
     }
     // return if function url scheme is not being customised
     $customFuncs = array('view', 'display');
     if (!in_array($args['func'], $customFuncs)) {
         return false;
     }
     // initialise url routing rules
     $routerFacade = new Reviews_RouterFacade();
     // get router itself for convenience
     $router = $routerFacade->getRouter();
     // initialise object type
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     $utilArgs = array('controller' => 'user', 'action' => 'encodeurl');
     $allowedObjectTypes = $controllerHelper->getObjectTypes('api', $utilArgs);
     $objectType = isset($args['args']['ot']) && in_array($args['args']['ot'], $allowedObjectTypes) ? $args['args']['ot'] : $controllerHelper->getDefaultObjectType('api', $utilArgs);
     // initialise group folder
     $groupFolder = $routerFacade->getGroupingFolderFromObjectType($objectType, $args['func'], $args['args']);
     // start pre processing
     // convert object type to group folder
     $args['args']['ot'] = $groupFolder;
     // handle special templates
     $displayDefaultEnding = System::getVar('shorturlsext', '');
     $endingPrefix = $args['func'] == 'view' ? '.' : '';
     foreach (array('csv', 'rss', 'atom', 'xml', 'pdf', 'json', 'kml') as $ending) {
         if (!isset($args['args']['use' . $ending . 'ext'])) {
             continue;
         }
         if ($args['args']['use' . $ending . 'ext'] == '1') {
             $args['args'][$args['func'] . 'ending'] = $endingPrefix . $ending;
         }
         unset($args['args']['use' . $ending . 'ext']);
     }
     // fallback to default templates
     if (!isset($args['args'][$args['func'] . 'ending'])) {
         if ($args['func'] == 'view') {
             // category list
             /* if (isset($args['args']['prop'])) {
                 $vars = $args['args']['prop'];
                if (isset($args['args']['cat'])) {
                $vars .= '/'.$args['args']['cat'];
                }
                // letter list
                } elseif (isset($args['args']['letter'])) {
                $vars = 'letter/'.$args['args']['letter'];
                }
                if (isset($args['args']['page']) && $args['args']['page'] != 1) {
                $vars .= (empty($vars) ? '' : '/').'page/'.$args['args']['page'];
                }*/
             $args['args'][$args['func'] . 'ending'] = '';
             //'/';
         } else {
             if ($args['func'] == 'display') {
                 $args['args'][$args['func'] . 'ending'] = $displayDefaultEnding;
             }
         }
     }
     if ($args['func'] == 'view') {
         // TODO filter views (e.g. /orders/customer/mr-smith.csv)
         /**
         $filterEntities = array('customer', 'region', 'federalstate', 'country');
         foreach ($filterEntities as $filterEntity) {
         $filterField = $filterEntity . 'id';
         if (!isset($args['args'][$filterField]) || !$args['args'][$filterField]) {
         continue;
         }
         $filterId = $args['args'][$filterField];
         unset($args['args'][$filterField]);
         
         $filterGroupFolder = $routerFacade->getGroupingFolderFromObjectType($filterEntity, 'display', $args['args']);
         $filterSlug = $routerFacade->getFormattedSlug($filterEntity, 'display', $args['args'], $filterId);
         $result .= $filterGroupFolder . '/' . $filterSlug .'/';
         break;
         }
         */
     } elseif ($args['func'] == 'display') {
         // determine given id
         $id = 0;
         foreach (array('id', strtolower($objectType) . 'id', 'objectid') as $idFieldName) {
             if (isset($args['args'][$idFieldName])) {
                 $id = $args['args'][$idFieldName];
                 unset($args['args'][$idFieldName]);
             }
         }
         if (ModUtil::getVar('Reviews', 'addcategorytitletopermalink') == 1 && ModUtil::getVar('Reviews', 'enablecategorization') == 1) {
             if ($id > 0) {
                 $modelHelper = new Reviews_Util_Model($this->serviceManager);
                 $repository = $modelHelper->getReviewRepository();
                 $thisreview = $repository->selectById($id);
                 $categories = $thisreview->getCategories();
                 $name = $categories[0]->getCategory()->getName();
                 $displayname = $categories[0]->getCategory()->getDisplayName();
             }
             $lang = ZLanguage::getLanguageCode();
             $cat = '';
             if ($name != '') {
                 $cat = $name;
             }
             if ($displayname != '') {
                 $cat = $displayname[$lang];
             }
             $args['args']['cat'] = $cat;
         }
         // check if we have a valid slug given
         if (isset($args['args']['slug']) && (!$args['args']['slug'] || $args['args']['slug'] == $id)) {
             unset($args['args']['slug']);
         }
         // try to determine missing slug
         if (!isset($args['args']['slug'])) {
             $slug = '';
             if ($id > 0) {
                 $slug = $routerFacade->getFormattedSlug($objectType, $args['func'], $args['args'], $id);
             }
             if (!empty($slug) && $slug != $id) {
                 // add slug expression
                 $args['args']['slug'] = $slug;
             }
         }
         // check if we have one now
         if (!isset($args['args']['slug'])) {
             // readd id as fallback
             $args['args']['id'] = $id;
         }
     }
     // add func as first argument
     $routerArgs = array_merge(array('func' => $args['func']), $args['args']);
     // now create url based on params
     $result = $router->generate(null, $routerArgs);
     // post processing
     if ($args['func'] == 'view' && !empty($args['args']['viewending']) || $args['func'] == 'display') {
         // check if url ends with a trailing slash
         if (substr($result, -1) == '/') {
             // remove the trailing slash
             $result = substr($result, 0, strlen($result) - 1);
         }
     }
     // enforce url name of the module, but do only 1 replacement to avoid changing other params
     $modInfo = ModUtil::getInfoFromName('Reviews');
     $result = preg_replace('/' . $modInfo['name'] . '/', $modInfo['url'], $result, 1);
     $result = preg_replace('#' . 'review/' . '#', '', $result, 1);
     $result = preg_replace('=' . '\\+' . '=', ' ', $result);
     return $result;
 }
Esempio n. 9
0
 /**
  * This method provides a generic handling of all edit requests.
  *
  * @param string  $ot           Treated object type.
  * @param string  $tpl          Name of alternative template (for alternative display options, feeds and xml output)
  * @param boolean $raw          Optional way to display a template instead of fetching it (needed for standalone output)
  *
  * @return mixed Output.
  */
 public function edit()
 {
     $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' => 'edit');
     if (!in_array($objectType, $controllerHelper->getObjectTypes('controllerAction', $utilArgs))) {
         $objectType = $controllerHelper->getDefaultObjectType('controllerAction', $utilArgs);
     }
     $this->throwForbiddenUnless(SecurityUtil::checkPermission($this->name . ':' . ucwords($objectType) . ':', '::', ACCESS_EDIT), LogUtil::getErrorMsgPermission());
     // create new Form reference
     $view = FormUtil::newForm($this->name, $this);
     // build form handler class name
     $handlerClass = $this->name . '_Form_Handler_User_' . ucfirst($objectType) . '_Edit';
     // determine the output template
     $viewHelper = new Reviews_Util_View($this->serviceManager);
     $template = $viewHelper->getViewTemplate($this->view, 'user', $objectType, 'edit', array());
     // execute form using supplied template and page event handler
     return $view->execute($template, new $handlerClass());
 }
Esempio n. 10
0
 /**
  * Initialize form handler.
  *
  * This method takes care of all necessary initialisation of our data and form states.
  *
  * @param Zikula_Form_View $view The form view instance.
  *
  * @return boolean False in case of initialization errors, otherwise true.
  */
 public function initialize(Zikula_Form_View $view)
 {
     $this->inlineUsage = UserUtil::getTheme() == 'Printer' ? true : false;
     $this->idPrefix = $this->request->query->filter('idp', '', FILTER_SANITIZE_STRING);
     // initialise redirect goal
     $this->returnTo = $this->request->query->filter('returnTo', null, FILTER_SANITIZE_STRING);
     // store current uri for repeated creations
     $this->repeatReturnUrl = System::getCurrentURI();
     $this->permissionComponent = $this->name . ':' . $this->objectTypeCapital . ':';
     $entityClass = $this->name . '_Entity_' . ucfirst($this->objectType);
     $this->idFields = ModUtil::apiFunc($this->name, 'selection', 'getIdFields', array('ot' => $this->objectType));
     // retrieve identifier of the object we wish to view
     $controllerHelper = new Reviews_Util_Controller($this->view->getServiceManager());
     $this->idValues = $controllerHelper->retrieveIdentifier($this->request, array(), $this->objectType, $this->idFields);
     $hasIdentifier = $controllerHelper->isValidIdentifier($this->idValues);
     $entity = null;
     $this->mode = $hasIdentifier ? 'edit' : 'create';
     if ($this->mode == 'edit') {
         if (!SecurityUtil::checkPermission($this->permissionComponent, $this->createCompositeIdentifier() . '::', ACCESS_EDIT)) {
             return LogUtil::registerPermissionError();
         }
         $entity = $this->initEntityForEdit();
         if (!is_object($entity)) {
             return LogUtil::registerError($this->__('No such item.'));
         }
         if ($this->hasPageLockSupport === true && ModUtil::available('PageLock')) {
             // try to guarantee that only one person at a time can be editing this entity
             ModUtil::apiFunc('PageLock', 'user', 'pageLock', array('lockName' => $this->name . $this->objectTypeCapital . $this->createCompositeIdentifier(), 'returnUrl' => $this->getRedirectUrl(null)));
         }
     } else {
         if (!SecurityUtil::checkPermission($this->permissionComponent, '::', ACCESS_EDIT)) {
             return LogUtil::registerPermissionError();
         }
         $entity = $this->initEntityForCreation();
     }
     $this->view->assign('mode', $this->mode)->assign('inlineUsage', $this->inlineUsage);
     // save entity reference for later reuse
     $this->entityRef = $entity;
     if ($this->hasCategories === true) {
         $this->initCategoriesForEdit();
     }
     $workflowHelper = new Reviews_Util_Workflow($this->view->getServiceManager());
     $actions = $workflowHelper->getActionsForObject($entity);
     if ($actions === false || !is_array($actions)) {
         return LogUtil::registerError($this->__('Error! Could not determine workflow actions.'));
     }
     // assign list of allowed actions to the view for further processing
     $this->view->assign('actions', $actions);
     // everything okay, no initialization errors occured
     return true;
 }
Esempio n. 11
0
 /**
  * Executes the actual search process.
  *
  * @param array $args List of arguments.
  *
  * @return boolean
  *
  * @throws RuntimeException Thrown if search results can not be saved
  */
 public function search(array $args = array())
 {
     if (!SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_READ)) {
         return '';
     }
     // ensure that database information of Search module is loaded
     ModUtil::dbInfoLoad('Search');
     // save session id as it is used when inserting search results below
     $sessionId = session_id();
     // retrieve list of activated object types
     $searchTypes = isset($args['objectTypes']) ? (array) $args['objectTypes'] : (array) FormUtil::getPassedValue('reviewsSearchTypes', array(), 'GETPOST');
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     $utilArgs = array('api' => 'search', 'action' => 'search');
     $allowedTypes = $controllerHelper->getObjectTypes('api', $utilArgs);
     $entityManager = ServiceUtil::getService('doctrine.entitymanager');
     $currentPage = 1;
     $resultsPerPage = 50;
     foreach ($searchTypes as $objectType) {
         if (!in_array($objectType, $allowedTypes)) {
             continue;
         }
         $whereArray = array();
         $languageField = null;
         switch ($objectType) {
             case 'review':
                 $whereArray[] = 'tbl.workflowState';
                 $whereArray[] = 'tbl.title';
                 $whereArray[] = 'tbl.text';
                 $whereArray[] = 'tbl.zlanguage';
                 $whereArray[] = 'tbl.reviewer';
                 $whereArray[] = 'tbl.email';
                 $whereArray[] = 'tbl.score';
                 $whereArray[] = 'tbl.url';
                 $whereArray[] = 'tbl.url_title';
                 $whereArray[] = 'tbl.cover';
                 $whereArray[] = 'tbl.coverUpload';
                 $languageField = 'zlanguage';
                 break;
         }
         $where = Search_Api_User::construct_where($args, $whereArray);
         $entityClass = $this->name . '_Entity_' . ucwords($objectType);
         $repository = $entityManager->getRepository($entityClass);
         // get objects from database
         list($entities, $objectCount) = $repository->selectWherePaginated($where, '', $currentPage, $resultsPerPage, false);
         if ($objectCount == 0) {
             continue;
         }
         $idFields = ModUtil::apiFunc($this->name, 'selection', 'getIdFields', array('ot' => $objectType));
         $descriptionField = $repository->getDescriptionFieldName();
         foreach ($entities as $entity) {
             $urlArgs = array('ot' => $objectType);
             // create identifier for permission check
             $instanceId = '';
             foreach ($idFields as $idField) {
                 $urlArgs[$idField] = $entity[$idField];
                 if (!empty($instanceId)) {
                     $instanceId .= '_';
                 }
                 $instanceId .= $entity[$idField];
             }
             $urlArgs['id'] = $instanceId;
             /* commented out as it could exceed the maximum length of the 'extra' field
                if (isset($entity['slug'])) {
                    $urlArgs['slug'] = $entity['slug'];
                }*/
             // perform permission check
             if (!SecurityUtil::checkPermission($this->name . ':' . ucfirst($objectType) . ':', $instanceId . '::', ACCESS_OVERVIEW)) {
                 continue;
             }
             $title = $entity->getTitleFromDisplayPattern();
             $description = !empty($descriptionField) ? $entity[$descriptionField] : '';
             $created = isset($entity['createdDate']) ? $entity['createdDate']->format('Y-m-d H:i:s') : '';
             $searchItemData = array('title' => $title, 'text' => $description, 'extra' => serialize($urlArgs), 'created' => $created, 'module' => $this->name, 'session' => $sessionId);
             if (!DBUtil::insertObject($searchItemData, 'search_result')) {
                 return LogUtil::registerError($this->__('Error! Could not save the search results.'));
             }
         }
     }
     return true;
 }
Esempio n. 12
0
 /**
  * Post-Process the data after the entity has been constructed by the entity manager.
  * The event happens after the entity has been loaded from database or after a refresh call.
  *
  * Restrictions:
  *     - no access to entity manager or unit of work apis
  *     - no access to associations (not initialised yet)
  *
  * @see Reviews_Entity_Review::postLoadCallback()
  * @return boolean true if completed successfully else false.
  */
 protected function performPostLoadCallback()
 {
     // echo 'loaded a record ...';
     $currentFunc = FormUtil::getPassedValue('func', 'main', 'GETPOST', FILTER_SANITIZE_STRING);
     $usesCsvOutput = FormUtil::getPassedValue('usecsvext', false, 'GETPOST', FILTER_SANITIZE_STRING);
     // initialise the upload handler
     $uploadManager = new Reviews_UploadHandler();
     $serviceManager = ServiceUtil::getManager();
     $controllerHelper = new Reviews_Util_Controller($serviceManager);
     $this['id'] = (int) (isset($this['id']) && !empty($this['id']) ? DataUtil::formatForDisplay($this['id']) : 0);
     $this->formatTextualField('workflowState', $currentFunc, $usesCsvOutput, true);
     $this->formatTextualField('title', $currentFunc, $usesCsvOutput);
     $this->formatTextualField('text', $currentFunc, $usesCsvOutput);
     $this->formatTextualField('zlanguage', $currentFunc, $usesCsvOutput);
     $this->formatTextualField('reviewer', $currentFunc, $usesCsvOutput);
     $this->formatTextualField('email', $currentFunc, $usesCsvOutput);
     $this->formatTextualField('score', $currentFunc, $usesCsvOutput, true);
     $this['url'] = isset($this['url']) && !empty($this['url']) ? DataUtil::formatForDisplay($this['url']) : '';
     $this->formatTextualField('url_title', $currentFunc, $usesCsvOutput);
     $this['hits'] = (int) (isset($this['hits']) && !empty($this['hits']) ? DataUtil::formatForDisplay($this['hits']) : 0);
     $this->formatTextualField('cover', $currentFunc, $usesCsvOutput);
     if (!empty($this['coverUpload'])) {
         try {
             $basePath = $controllerHelper->getFileBaseFolder('review', 'coverUpload');
         } catch (\Exception $e) {
             return LogUtil::registerError($e->getMessage());
         }
         $fullPath = $basePath . $this['coverUpload'];
         $this['coverUploadFullPath'] = $fullPath;
         $this['coverUploadFullPathURL'] = System::getBaseUrl() . $fullPath;
         // just some backwards compatibility stuff
         /*if (!isset($this['coverUploadMeta']) || !is_array($this['coverUploadMeta']) || !count($this['coverUploadMeta'])) {
               // assign new meta data
               $this['coverUploadMeta'] = $uploadManager->readMetaDataForFile($this['coverUpload'], $fullPath);
           }*/
     }
     $this->prepareItemActions();
     return true;
 }
Esempio n. 13
0
 /**
  * This method provides a generic handling of simple delete requests.
  *
  * @param string  $ot           Treated object type.
  * @param int     $id           Identifier of entity to be deleted.
  * @param boolean $confirmation Confirm the deletion, else a confirmation page is displayed.
  * @param string  $tpl          Name of alternative template (for alternative display options, feeds and xml output)
  * @param boolean $raw          Optional way to display a template instead of fetching it (needed for standalone output)
  *
  * @return mixed Output.
  */
 public function delete()
 {
     $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' => 'admin', 'action' => 'delete');
     if (!in_array($objectType, $controllerHelper->getObjectTypes('controllerAction', $utilArgs))) {
         $objectType = $controllerHelper->getDefaultObjectType('controllerAction', $utilArgs);
     }
     $this->throwForbiddenUnless(SecurityUtil::checkPermission($this->name . ':' . ucwords($objectType) . ':', '::', ACCESS_ADMIN), LogUtil::getErrorMsgPermission());
     $idFields = ModUtil::apiFunc($this->name, 'selection', 'getIdFields', array('ot' => $objectType));
     // retrieve identifier of the object we wish to delete
     $idValues = $controllerHelper->retrieveIdentifier($this->request, array(), $objectType, $idFields);
     $hasIdentifier = $controllerHelper->isValidIdentifier($idValues);
     $this->throwNotFoundUnless($hasIdentifier, $this->__('Error! Invalid identifier received.'));
     $entity = ModUtil::apiFunc($this->name, 'selection', 'getEntity', array('ot' => $objectType, 'id' => $idValues));
     $this->throwNotFoundUnless($entity != null, $this->__('No such item.'));
     $entity->initWorkflow();
     $workflowHelper = new Reviews_Util_Workflow($this->serviceManager);
     $deleteActionId = 'delete';
     $deleteAllowed = false;
     $actions = $workflowHelper->getActionsForObject($entity);
     if ($actions === false || !is_array($actions)) {
         return LogUtil::registerError($this->__('Error! Could not determine workflow actions.'));
     }
     foreach ($actions as $actionId => $action) {
         if ($actionId != $deleteActionId) {
             continue;
         }
         $deleteAllowed = true;
         break;
     }
     if (!$deleteAllowed) {
         return LogUtil::registerError($this->__('Error! It is not allowed to delete this entity.'));
     }
     $confirmation = (bool) $this->request->request->filter('confirmation', false, FILTER_VALIDATE_BOOLEAN);
     if ($confirmation) {
         $this->checkCsrfToken();
         $hookAreaPrefix = $entity->getHookAreaPrefix();
         $hookType = 'validate_delete';
         // Let any hooks perform additional validation actions
         $hook = new Zikula_ValidationHook($hookAreaPrefix . '.' . $hookType, new Zikula_Hook_ValidationProviders());
         $validators = $this->notifyHooks($hook)->getValidators();
         if (!$validators->hasErrors()) {
             // execute the workflow action
             $success = $workflowHelper->executeAction($entity, $deleteActionId);
             if ($success) {
                 $this->registerStatus($this->__('Done! Item deleted.'));
             }
             // Let any hooks know that we have created, updated or deleted an item
             $hookType = 'process_delete';
             $hook = new Zikula_ProcessHook($hookAreaPrefix . '.' . $hookType, $entity->createCompositeIdentifier());
             $this->notifyHooks($hook);
             // An item was deleted, so we clear all cached pages this item.
             $cacheArgs = array('ot' => $objectType, 'item' => $entity);
             ModUtil::apiFunc($this->name, 'cache', 'clearItemCache', $cacheArgs);
             // redirect to the list of the current object type
             return $this->redirect(ModUtil::url($this->name, 'admin', 'view', array('ot' => $objectType)));
         }
     }
     $entityClass = $this->name . '_Entity_' . ucwords($objectType);
     $repository = $this->entityManager->getRepository($entityClass);
     // set caching id
     $this->view->setCaching(Zikula_View::CACHE_DISABLED);
     // assign the object we loaded above
     $this->view->assign($objectType, $entity)->assign($repository->getAdditionalTemplateParameters('controllerAction', $utilArgs));
     // fetch and return the appropriate template
     $viewHelper = new Reviews_Util_View($this->serviceManager);
     return $viewHelper->processTemplate($this->view, 'admin', $objectType, 'delete', array());
 }
Esempio n. 14
0
 /**
  * Loads the data.
  *
  * @param array $data Data array with parameters.
  */
 public function loadData(&$data)
 {
     $serviceManager = ServiceUtil::getManager();
     $controllerHelper = new Reviews_Util_Controller($serviceManager);
     $utilArgs = array('name' => 'list');
     if (!isset($data['objectType']) || !in_array($data['objectType'], $controllerHelper->getObjectTypes('contentType', $utilArgs))) {
         $data['objectType'] = $controllerHelper->getDefaultObjectType('contentType', $utilArgs);
     }
     $this->objectType = $data['objectType'];
     if (!isset($data['sorting'])) {
         $data['sorting'] = 'default';
     }
     if (!isset($data['amount'])) {
         $data['amount'] = 1;
     }
     if (!isset($data['template'])) {
         $data['template'] = 'itemlist_' . $this->objectType . '_display.tpl';
     }
     if (!isset($data['customTemplate'])) {
         $data['customTemplate'] = '';
     }
     if (!isset($data['filter'])) {
         $data['filter'] = '';
     }
     $this->sorting = $data['sorting'];
     $this->amount = $data['amount'];
     $this->template = $data['template'];
     $this->customTemplate = $data['customTemplate'];
     $this->filter = $data['filter'];
     $this->categorisableObjectTypes = array('review');
     // fetch category properties
     $this->catRegistries = array();
     $this->catProperties = array();
     if (in_array($this->objectType, $this->categorisableObjectTypes)) {
         $idFields = ModUtil::apiFunc('Reviews', 'selection', 'getIdFields', array('ot' => $this->objectType));
         $this->catRegistries = ModUtil::apiFunc('Reviews', 'category', 'getAllPropertiesWithMainCat', array('ot' => $this->objectType, 'arraykey' => $idFields[0]));
         $this->catProperties = ModUtil::apiFunc('Reviews', 'category', 'getAllProperties', array('ot' => $this->objectType));
     }
     if (!isset($data['catIds'])) {
         $primaryRegistry = ModUtil::apiFunc('Reviews', 'category', 'getPrimaryProperty', array('ot' => $this->objectType));
         $data['catIds'] = array($primaryRegistry => array());
         // backwards compatibility
         if (isset($data['catId'])) {
             $data['catIds'][$primaryRegistry][] = $data['catId'];
             unset($data['catId']);
         }
     } elseif (!is_array($data['catIds'])) {
         $data['catIds'] = explode(',', $data['catIds']);
     }
     foreach ($this->catRegistries as $registryId => $registryCid) {
         $propName = '';
         foreach ($this->catProperties as $propertyName => $propertyId) {
             if ($propertyId == $registryId) {
                 $propName = $propertyName;
                 break;
             }
         }
         if (isset($data['catids' . $propName])) {
             $data['catIds'][$propName] = $data['catids' . $propName];
         }
         if (!is_array($data['catIds'][$propName])) {
             if ($data['catIds'][$propName]) {
                 $data['catIds'][$propName] = array($data['catIds'][$propName]);
             } else {
                 $data['catIds'][$propName] = array();
             }
         }
     }
     $this->catIds = $data['catIds'];
 }
Esempio n. 15
0
 /**
  * Determines object type using controller util methods.
  *
  * @param string $args['ot'] The object type to retrieve (optional).
  * @param string $methodName Name of calling method.
  *
  * @return string the object type.
  */
 protected function determineObjectType(array $args = array(), $methodName = '')
 {
     $objectType = isset($args['ot']) ? $args['ot'] : '';
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     $utilArgs = array('api' => 'selection', 'action' => $methodName);
     if (!in_array($objectType, $controllerHelper->getObjectTypes('api', $utilArgs))) {
         $objectType = $controllerHelper->getDefaultObjectType('api', $utilArgs);
     }
     return $objectType;
 }
Esempio n. 16
0
 /**
  * Deletes an existing upload file.
  * For images the thumbnails are removed, too.
  *
  * @param string  $objectType Currently treated entity type.
  * @param string  $objectData Object data array.
  * @param string  $fieldName  Name of upload field.
  * @param integer $objectId   Primary identifier of the given object.
  *
  * @return mixed Array with updated object data on success, else false.
  */
 public function deleteUploadFile($objectType, $objectData, $fieldName, $objectId)
 {
     if (!in_array($objectType, $this->allowedObjectTypes)) {
         return false;
     }
     if (empty($objectData[$fieldName])) {
         return $objectData;
     }
     $serviceManager = ServiceUtil::getManager();
     $controllerHelper = new Reviews_Util_Controller($serviceManager);
     // determine file system information
     try {
         $basePath = $controllerHelper->getFileBaseFolder($objectType, $fieldName);
     } catch (\Exception $e) {
         LogUtil::registerError($e->getMessage());
         return $objectData;
     }
     $fileName = $objectData[$fieldName];
     // path to original file
     $filePath = $basePath . $fileName;
     // check whether we have to consider thumbnails, too
     $fileExtension = FileUtil::getExtension($fileName, false);
     if (in_array($fileExtension, $this->imageFileTypes) && $fileExtension != 'swf') {
         // remove thumbnail images as well
         $manager = ServiceUtil::getManager()->getService('systemplugin.imagine.manager');
         $manager->setModule('Reviews');
         $fullObjectId = $objectType . '-' . $objectId;
         $manager->removeImageThumbs($filePath, $fullObjectId);
     }
     // remove original file
     if (!unlink($filePath)) {
         return false;
     }
     $objectData[$fieldName] = '';
     $objectData[$fieldName . 'Meta'] = array();
     return $objectData;
 }
Esempio n. 17
0
 /**
  * Processes a template file using dompdf (LGPL).
  *
  * @param Zikula_View $view     Reference to view object.
  * @param string      $template Name of template to use.
  *
  * @return mixed Output.
  */
 protected function processPdf(Zikula_View $view, $template)
 {
     // first the content, to set page vars
     $output = $view->fetch($template);
     // make local images absolute
     $output = str_replace('img src="/', 'img src="' . System::serverGetVar('DOCUMENT_ROOT') . '/', $output);
     // see http://codeigniter.com/forums/viewthread/69388/P15/#561214
     //$output = utf8_decode($output);
     // then the surrounding
     $output = $view->fetch('include_pdfheader.tpl') . $output . '</body></html>';
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     // create name of the pdf output file
     $fileTitle = $controllerHelper->formatPermalink(System::getVar('sitename')) . '-' . $controllerHelper->formatPermalink(PageUtil::getVar('title')) . '-' . date('Ymd') . '.pdf';
     // if ($_GET['dbg'] == 1) die($output);
     // instantiate pdf object
     $pdf = new \DOMPDF();
     // define page properties
     $pdf->set_paper('A4');
     // load html input data
     $pdf->load_html($output);
     // create the actual pdf file
     $pdf->render();
     // stream output to browser
     $pdf->stream($fileTitle);
     // prevent additional output by shutting down the system
     System::shutDown();
     return true;
 }
Esempio n. 18
0
 /**
  * Checks whether a field value is a duplicate or not.
  *
  * @param string $ot Treated object type.
  * @param string $fn Name of field to be checked.
  * @param string $v  The value to be checked for uniqueness.
  * @param string $ex Optional identifier to be excluded from search.
  *
  * @return Zikula_Response_Ajax
  */
 public function checkForDuplicate()
 {
     $this->checkAjaxToken();
     $this->throwForbiddenUnless(SecurityUtil::checkPermission($this->name . '::Ajax', '::', ACCESS_EDIT));
     $postData = $this->request->request;
     $objectType = $postData->filter('ot', 'review', FILTER_SANITIZE_STRING);
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     $utilArgs = array('controller' => 'ajax', 'action' => 'checkForDuplicate');
     if (!in_array($objectType, $controllerHelper->getObjectTypes('controllerAction', $utilArgs))) {
         $objectType = $controllerHelper->getDefaultObjectType('controllerAction', $utilArgs);
     }
     $fieldName = $postData->filter('fn', '', FILTER_SANITIZE_STRING);
     $value = $postData->get('v', '');
     if (empty($fieldName) || empty($value)) {
         return new Zikula_Response_Ajax_BadData($this->__('Error: invalid input.'));
     }
     // check if the given field is existing and unique
     $uniqueFields = array();
     switch ($objectType) {
         case 'review':
             $uniqueFields = array('slug');
             break;
     }
     if (!count($uniqueFields) || !in_array($fieldName, $uniqueFields)) {
         return new Zikula_Response_Ajax_BadData($this->__('Error: invalid input.'));
     }
     $exclude = $postData->get('ex', '');
     $entityClass = 'Reviews_Entity_' . ucfirst($objectType);
     $object = new $entityClass();
     $result = false;
     switch ($objectType) {
         case 'review':
             $repository = $this->entityManager->getRepository($entityClass);
             switch ($fieldName) {
                 case 'slug':
                     $entity = $repository->selectBySlug($value, false, $exclude);
                     $result = $entity != null && isset($entity['slug']);
                     break;
             }
             break;
     }
     // return response
     $result = array('isDuplicate' => $result);
     return new Zikula_Response_Ajax($result);
 }