public function getCDNWriter()
 {
     $stores = $this->contentService->getStoreTypes();
     if ($stores && isset($stores[$this->getCDNStore()])) {
         return $this->contentService->getWriter($this->getCDNStore());
     }
 }
 /**
  * Store the contents of a folder on a CDN. 
  * 
  * If processReferences is set, relative URL references are attempted to be 
  * detected and stored remotely as well, with the file to be stored rewritten 
  * to refer to the CDN value. This really is only useful for CSS 
  *
  * @param string $folder
  * @param boolean $processReferences 
  */
 public function storeThemeFile($toCdn, $file, $forceUpdate = false, $processReferences = false)
 {
     $mtime = @filemtime($file);
     $relativeName = self::CDN_THEME_PREFIX . '/' . $mtime . '/' . trim(str_replace(Director::baseFolder(), '', $file), '/');
     if (!$forceUpdate) {
         // see if the file already exists, if not we do NOT do an update
         $reader = $this->contentService->findReaderFor($toCdn, $relativeName);
         if ($reader && $reader->exists()) {
             return $reader->getURL();
         }
     }
     $clear = false;
     if ($processReferences) {
         $clear = true;
         $file = $this->processFileReferences($toCdn, $file, $forceUpdate);
     }
     // otherwise, lets get a content writer
     $writer = $this->contentService->getWriter($toCdn);
     try {
         $writer->write($file, $relativeName);
     } catch (Exception $e) {
         SS_Log::log($e, SS_Log::WARN);
     }
     if ($clear && strpos($file, '.cdn') > 0) {
         @unlink($file);
     }
     $id = $writer->getContentId();
     return $writer->getReader()->getURL();
 }
 public function homeAction()
 {
     if ($this->hasParam('pos')) {
         $pos = $this->getParam('pos');
     } else {
         $pos = 0;
     }
     $this->setTitleCurrentPage(array());
     $this->saveLastPage();
     if ($this->userService->checkRight('CONTENT_EDIT')) {
         $state = \org\equinox\modules\content\dao\ContentDto::STATE_ALL;
     } else {
         $state = \org\equinox\modules\content\dao\ContentDto::STATE_ONLINE;
     }
     $list = $this->contentService->listByIdCategory(0, $state, $pos, self::PAGE_STEP + 1, true);
     if (sizeof($list) == self::PAGE_STEP + 1) {
         $this->assign('posNext', $pos + self::PAGE_STEP);
         array_pop($list);
     } else {
         $this->assign('posNext', -1);
     }
     $this->assign('pos', $pos);
     $this->assign('posPrec', $pos - self::PAGE_STEP);
     $this->assign('edito', $this->contentService->getEdito());
     $this->assign('listeContent', $list);
 }
 /**
  * Return the CDN store that this file should be stored into, based on its
  * parent setting, if no parent is found the ContentService default is returned
  */
 public function targetStore()
 {
     if ($this->owner->ParentID) {
         $store = $this->owner->Parent()->getCDNStore();
         return $store;
     }
     return $this->contentService->getDefaultStore();
 }
 /**
  * @return ContentWriter
  */
 protected function getWriter()
 {
     $current = $this->currentThemeCdn();
     $writer = $this->contentService->getWriter($current->StoreIn);
     if (!$writer) {
         throw new Exception("Invalid writer type " . $current->StoreIn);
     }
     return $writer;
 }
 /**
  * Get the CDN store that this item should be stored in
  */
 public function getCDNStore()
 {
     if ($this->owner->StoreInCDN) {
         return $this->owner->StoreInCDN;
     }
     if (!$this->owner->ID || $this->owner->ID === "root" || !$this->owner->ParentID) {
         return $this->contentService->getDefaultStore();
     }
     if ($this->owner->ParentID) {
         return $this->owner->Parent()->getCDNStore();
     }
 }
 public function testListFolder()
 {
     if (file_exists($this->testDir)) {
         Filesystem::removeFolder($this->testDir);
     }
     mkdir($this->testDir);
     file_put_contents($this->testDir . '/testfile.txt', 'dummy_data');
     $reader = $this->contentService->getReader('File:||' . $this->testDir);
     $list = $reader->getList();
     $this->assertEquals(1, count($list));
     $file = $list[0];
     $writer = $file->getWriter();
     $writer->write('new contents');
     $this->assertEquals('new contents', file_get_contents($this->testDir . '/testfile.txt'));
 }
 /**
  * Lists entries based on passed parameters
  *
  * @return array|string
  */
 public function getContent($variable)
 {
     $urls = array_get($this->context, $variable);
     if (!$urls) {
         return null;
     }
     // grab common parameters
     $settings = $this->parseCommonParameters();
     // grab content set based on the common parameters
     // $content_set = $this->getContentSet($settings);
     $content_set = ContentService::getContentByURL($urls);
     $content_set->filter(array('show_hidden' => $this->fetchParam('show_hidden', false, null, true, false), 'show_drafts' => $this->fetchParam('show_drafts', false, null, true, false), 'show_past' => $this->fetchParam('show_past', true, null, true), 'show_future' => $this->fetchParam('show_future', false, null, true), 'type' => 'all', 'conditions' => trim($this->fetchParam('conditions', null, false, false, false))));
     // limit
     $limit = $this->fetchParam('limit', null, 'is_numeric');
     $offset = $this->fetchParam('offset', 0, 'is_numeric');
     if ($limit || $offset) {
         $content_set->limit($limit, $offset);
     }
     // sort
     $sort_by = $this->fetchParam('sort_by');
     $sort_dir = $this->fetchParam('sort_dir');
     if ($sort_by || $sort_dir) {
         $content_set->sort($sort_by, $sort_dir);
     }
     // check for results
     if (!$content_set->count()) {
         return Parse::template($this->content, array('no_results' => true));
     }
     return Parse::tagLoop($this->content, $content_set->get(), false, $this->context);
 }
 /**
  * Is the $url in our cache and still valid?
  * 
  * @param string  $url  URL to check for cache
  * @return bool
  */
 public function isPageCached($url)
 {
     $cache_length = trim($this->fetchConfig('cache_length', false));
     // if no cache-length is set, this feature is off
     if (!(bool) $cache_length) {
         return false;
     }
     if ($this->fetchConfig('ignore_query_strings', false, null, true)) {
         $url = $this->removeQueryString($url);
     }
     // create the hash now so we don't have to do it many times below
     $url_hash = Helper::makeHash($url);
     // we're no longer allowing `on cache update` here, as its a flawed concept:
     // it only appeared to work because new pages were being hit, however, once
     // every page is hit and then HTML-cached, the cache will no longer update
     // because procedurally, that happens *after* we look for and load a version
     // that has been cached
     if ($cache_length == 'on cache update' || $cache_length == 'on last modified') {
         // ignore the cached version if the last modified time of this URL's
         // content file is newer than when the cached version was made
         // check that the URL being requested is a content file
         $bare_url = strpos($url, '?') !== false ? substr($url, 0, strpos($url, '?')) : $url;
         $data = ContentService::getContent($bare_url);
         $age = time() - File::getLastModified($data['_file']);
         // return if the cache file exists and if it's new enough
         return $this->cache->exists($url_hash) && $this->cache->getAge($url_hash) <= $age;
     } else {
         // purge any cache files older than the cache length
         $this->cache->purgeFromBefore('-' . $cache_length);
         // return if the file still exists
         return $this->cache->exists($url_hash);
     }
 }
 public function control_panel__add_to_head()
 {
     if (URL::getCurrent(false) == '/publish') {
         $file = 'defined-links.json';
         $current_content_list = file_get_contents($file, true);
         $current_content_list = json_decode($current_content_list);
         $content_set = ContentService::getContentByFolders(array("/*"));
         $content_set->multisort('url');
         $content_set = $content_set->get();
         $content_list = [];
         $content_list[] = ['name' => 'Select...', 'url' => false];
         foreach ($content_set as $content) {
             if (isset($content['url']) && isset($content['title'])) {
                 $name = '[' . $content['url'] . '] ' . $content['title'];
                 $url = $content['url'];
                 $content_list[] = ['name' => $name, 'url' => $url];
             }
         }
         if ($current_content_list !== $content_list) {
             $json = json_encode($content_list);
             file_put_contents($file, $json, FILE_USE_INCLUDE_PATH);
         }
         return $this->js->link('definedlinks.js');
     }
 }
 public function index()
 {
     $from = $this->fetchParam('from', false);
     if (!$from) {
         return null;
     }
     // account for subfolder
     if (strpos($from, Config::getSiteRoot()) !== 0) {
         $from = Path::tidy(Config::getSiteRoot() . $from);
     }
     $from = Path::addStartingSlash($from);
     $content_set = ContentService::getContentByURL($from);
     // filter
     $content_set->filter(array('show_hidden' => $this->fetchParam('show_hidden', false, null, true, false), 'show_drafts' => $this->fetchParam('show_drafts', false, null, true, false), 'show_past' => $this->fetchParam('show_past', true, null, true), 'show_future' => $this->fetchParam('show_future', false, null, true), 'type' => 'all', 'conditions' => trim($this->fetchParam('conditions', null, false, false, false))));
     // limit
     $limit = $this->fetchParam('limit', 1, 'is_numeric');
     $offset = $this->fetchParam('offset', 0, 'is_numeric');
     $content_set->limit($limit, $offset);
     // check for results
     if (!$content_set->count()) {
         return Parse::tagLoop($this->content, array(array('no_results' => true)));
     }
     // if content is used in this entries loop, parse it
     $parse_content = (bool) preg_match(Pattern::USING_CONTENT, $this->content);
     return Parse::tagLoop($this->content, $content_set->get($parse_content), false, $this->context);
 }
 public function __call($method, $arguments)
 {
     // Get all the parameter/filters
     $filters = $this->attributes;
     // Default content to context
     $content = $this->context;
     // Override content by a specific page if needed
     if ($from = $this->fetchParam('from')) {
         $content = current(ContentService::getContentByURL($from)->get());
         unset($filters['from']);
     }
     // Grab the field data
     $field_data = array_get($content, $method);
     // Filter down to what we're looking for
     $values = array_values(array_filter($field_data, function ($i) use($filters) {
         foreach ($filters as $key => $val) {
             $match = array_get($i, $key) == $val;
             if (!$match) {
                 break;
             }
         }
         return $match;
     }));
     // No results?
     if (empty($values)) {
         return array('no_results' => true);
     }
     // Got something. Yay. Return it.
     return Parse::tagLoop($this->content, $values, true);
 }
Пример #13
0
 public function getContent()
 {
     $url = URL::assemble(Config::getSiteRoot(), $this->fetchConfig('globals_url', null, null, false, false));
     $content = ContentService::getContentByUrl($url);
     $content = current($content->extract());
     return $content;
 }
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->replaceField('LastSync', new ReadonlyField('LastSync', _t('ThemeCdn.LAST_SYNC', 'Last Sync')));
     $config = SiteConfig::current_site_config();
     $themes = $config->getAvailableThemes();
     $themes = array_merge(array('' => ''), $themes);
     $fields->replaceField('Theme', new DropdownField('Theme', _t('ThemeCdn.THEME', 'Theme'), $themes));
     if ($this->Theme) {
         // $fields->addFieldToTab('Root.Main', new MultiValue
         $fields->replaceField('Files', MultiValueCheckboxField::create('Files', _t('ThemeCdn.FILES', 'Files'), $this->getThemeFiles()));
     }
     $stores = $this->contentService->getStoreTypes();
     if (count($stores)) {
         $default = array('' => 'No CDN');
         $stores = array_merge($default, array_combine(array_keys($stores), array_keys($stores)));
         $fields->replaceField('StoreIn', DropdownField::create('StoreIn', 'CDN', $stores));
     }
     return $fields;
 }
 public function control_panel__post_publish($publish_data)
 {
     // check that caching is turned on
     if (!$this->core->isEnabled()) {
         return;
     }
     // we only need one key from the hook's value
     $file = $publish_data['file'];
     // update the cache
     _Cache::update();
     ContentService::loadCache(true);
     // grab data
     $triggers = $this->fetchConfig('publish_invalidation', array(), 'is_array', false, false);
     $content = Content::find(Path::tidy(str_replace(Config::getContentRoot(), '/', $file)));
     if ($triggers && $content) {
         foreach ($triggers as $trigger) {
             $folders = Parse::pipeList(array_get($trigger, 'folder', null));
             $key = array_get($trigger, 'key', null);
             if (!$folders || !$key) {
                 // not checking this
                 continue;
             }
             // check
             $invalidate = false;
             foreach ($folders as $folder) {
                 if ($folder === "*" || $folder === "/*") {
                     // include all
                     $invalidate = true;
                     break;
                 } elseif (substr($folder, -1) === "*") {
                     // wildcard check
                     if (strpos($content['_folder'], substr($folder, 0, -1)) === 0) {
                         $invalidate = true;
                         break;
                     }
                 } else {
                     // plain check
                     if ($folder == $content['_folder']) {
                         $invalidate = true;
                         break;
                     }
                 }
             }
             // invalidate if needed
             if ($invalidate) {
                 $this->core->deleteByKey(Parse::pipeList($key));
             }
         }
     }
 }
 /**
    Show the content of a category
 */
 public function indexAction()
 {
     $this->formStorage->clearDefinition();
     if ($this->hasParam('pos')) {
         $pos = $this->getParam('pos');
     } else {
         $pos = 0;
     }
     $id = $this->getParam('idCat', 0);
     $cat = $this->categoryService->get($id);
     if ($cat == null) {
         $this->goHome();
         return;
     }
     $this->assign('category', $cat);
     // recuperer la liste de toutes les categories filles
     $idCatz = $this->categoryService->listIdCategoriesForParent($id);
     $idCatz[] = $id;
     $this->assign('idz', $idCatz);
     $this->setTitleCurrentPage($this->getTitlesForIdCategory($id));
     $this->saveLastPage();
     if ($this->userService->checkRight('CONTENT_EDIT')) {
         $state = \org\equinox\modules\content\dao\ContentDto::STATE_ALL;
     } else {
         $state = \org\equinox\modules\content\dao\ContentDto::STATE_ONLINE;
     }
     $list = $this->contentService->listByIdCategories($idCatz, $state, $pos, self::PAGE_STEP + 1);
     if (sizeof($list) == self::PAGE_STEP + 1) {
         $this->assign('posNext', $pos + self::PAGE_STEP);
         array_pop($list);
     } else {
         $this->assign('posNext', -1);
     }
     $this->assign('pos', $pos);
     $this->assign('posPrec', $pos - self::PAGE_STEP);
     $this->assign('listeContent', $list);
 }
Пример #17
0
 /**
  * @Route("/upload_content_image/{contentId}")
  * @Method({"FILES|POST"})
  */
 public function uploadContentImage(Request $request, $contentId)
 {
     $fileSource = [];
     /** @var UploadedFile[] $files */
     $files = $request->files->get('files');
     $absolutePath = $request->server->get('DOCUMENT_ROOT') . "/upload/content";
     $file = $files[0];
     $imageSize = getimagesize($file);
     $fileInfo = $file->move($absolutePath, $file->getClientOriginalName());
     $resultImage = $this->imageService->resizeImage($fileInfo, $absolutePath . '/', $imageSize[0], $imageSize[1]);
     $savedUrl = $this->service->editTextById($contentId, '/content/' . $resultImage);
     unlink($absolutePath . '/' . $fileInfo->getFilename());
     $fileSource['file_name'] = $savedUrl['text'];
     $fileSource['contentId'] = $contentId;
     return new Response(json_encode($fileSource));
 }
Пример #18
0
 /**
  * Lists entries based on passed parameters
  *
  * @return array|string
  */
 public function listing()
 {
     $folders = $this->fetchParam('folder', $this->fetchParam('folders', ltrim($this->fetchParam('from', URL::getCurrent()), "/")));
     $folders = $folders === "/" ? "" : $folders;
     if ($this->fetchParam('taxonomy', false, null, true, null)) {
         $taxonomy_parts = Taxonomy::getCriteria(URL::getCurrent());
         $taxonomy_type = $taxonomy_parts[0];
         $taxonomy_slug = Config::get('_taxonomy_slugify') ? Slug::humanize($taxonomy_parts[1]) : urldecode($taxonomy_parts[1]);
         $content_set = ContentService::getContentByTaxonomyValue($taxonomy_type, $taxonomy_slug, $folders);
     } else {
         $content_set = ContentService::getContentByFolders($folders);
     }
     // filter
     $content_set->filter(array('show_all' => $this->fetchParam('show_hidden', false, null, true, false), 'since' => $this->fetchParam('since'), 'until' => $this->fetchParam('until'), 'show_past' => $this->fetchParam('show_past', TRUE, NULL, TRUE), 'show_future' => $this->fetchParam('show_future', FALSE, NULL, TRUE), 'type' => 'pages', 'conditions' => trim($this->fetchParam('conditions', ""))));
     // sort
     $content_set->sort($this->fetchParam('sort_by', 'order_key'), $this->fetchParam('sort_dir'));
     // grab total entries for setting later
     $total_entries = $content_set->count();
     // limit
     $limit = $this->fetchParam('limit', null, 'is_numeric');
     $offset = $this->fetchParam('offset', 0, 'is_numeric');
     $paginate = $this->fetchParam('paginate', true, null, true, false);
     if ($limit || $offset) {
         if ($limit && $paginate && !$offset) {
             // pagination requested, isolate the appropriate page
             $content_set->isolatePage($limit, URL::getCurrentPaginationPage());
         } else {
             // just limit
             $content_set->limit($limit, $offset);
         }
     }
     // manually supplement
     $content_set->supplement(array('total_found' => $total_entries));
     // check for results
     if (!$content_set->count()) {
         return array('no_results' => true);
     }
     // if content is used in this entries loop, parse it
     $parse_content = (bool) preg_match(Pattern::USING_CONTENT, $this->content);
     return Parse::tagLoop($this->content, $content_set->get($parse_content));
 }
 public function listing()
 {
     // grab a taxonomy set from the content service
     $taxonomy_set = ContentService::getTaxonomiesByType($this->fetchParam('type', null));
     // folders
     $folders = $this->fetchParam('folder', $this->fetchParam('folders', ltrim($this->fetchParam('from', URL::getCurrent()), "/")));
     // now filter that down to just what we want
     $taxonomy_set->filter(array('folders' => $folders, 'show_hidden' => $this->fetchParam('show_hidden', false, null, true, false), 'show_drafts' => $this->fetchParam('show_drafts', false, null, true, false), 'since' => $this->fetchParam('since', null), 'until' => $this->fetchParam('until', null), 'min_count' => $this->fetchParam('min_count', 1, 'is_numeric'), 'show_future' => $this->fetchParam('show_future', false, null, true, false), 'show_past' => $this->fetchParam('show_past', true, null, true, false), 'conditions' => trim($this->fetchParam('conditions', null, false, false, false)), 'where' => trim($this->fetchParam('where', null, false, false, false))));
     // sort as needed
     $taxonomy_set->sort($this->fetchParam('sort_by', 'name'), $this->fetchParam('sort_dir', 'asc'));
     // trim to limit the number of results
     $taxonomy_set->limit($this->fetchParam('limit', null, 'is_numeric'));
     // contextualize the urls to the given folder
     $taxonomy_set->contextualize($this->fetchParam('folder', null));
     $output = $taxonomy_set->get();
     // no results found, return so
     if (!count($output)) {
         return array('no_results' => true);
     }
     // results found, parse the tag loop with our content
     return Parse::tagLoop($this->content, $output, true, $this->context);
 }
Пример #20
0
 public function index()
 {
     $from = $this->fetchParam('from', false);
     // defaults to null
     if (!$from) {
         return null;
     }
     $from = Path::addStartingSlash($from);
     $from = strlen($from) > 1 ? rtrim($from, "/") : $from;
     $content_set = ContentService::getContentByURL($from);
     // filter
     $content_set->filter(array('show_all' => $this->fetchParam('show_hidden', false, null, true, false), 'show_past' => $this->fetchParam('show_past', true, null, true), 'show_future' => $this->fetchParam('show_future', false, null, true), 'type' => 'all', 'conditions' => trim($this->fetchParam('conditions', null, false, false, false))));
     // limit
     $limit = $this->fetchParam('limit', 1, 'is_numeric');
     $offset = $this->fetchParam('offset', 0, 'is_numeric');
     $content_set->limit($limit, $offset);
     // check for results
     if (!$content_set->count()) {
         return Parse::tagLoop($this->content, array(array('no_results' => true)));
     }
     // if content is used in this entries loop, parse it
     $parse_content = (bool) preg_match(Pattern::USING_CONTENT, $this->content);
     return Parse::tagLoop($this->content, $content_set->get($parse_content));
 }
Пример #21
0
    /**
     * Returns a ContentSet object with the appropriate content
     *
     * @param array  $settings  Settings for filtering content and such
     * @return ContentSet
     */
    private function getContentSet($settings)
    {
        // create a unique hash for these settings
        $content_hash = Helper::makeHash($settings);

        if ($this->blink->exists($content_hash)) {
            // blink content exists, use that
            $content_set = new ContentSet($this->blink->get($content_hash));
        } else {
            // no blink content exists, get data the hard way
            if ($settings['taxonomy']) {
                $taxonomy_parts  = Taxonomy::getCriteria(URL::getCurrent());
                $taxonomy_type   = $taxonomy_parts[0];
                $taxonomy_slug   = Config::get('_taxonomy_slugify') ? Slug::humanize($taxonomy_parts[1]) : urldecode($taxonomy_parts[1]);

                $content_set = ContentService::getContentByTaxonomyValue($taxonomy_type, $taxonomy_slug, $settings['folders']);
            } else {
                $content_set = ContentService::getContentByFolders($settings['folders']);
            }

            // filter
            $content_set->filter($settings);

            // grab total entries for setting later
            $total_entries = $content_set->count();

            // pre-sort supplement
            $content_set->supplement(array('total_found' => $total_entries) + $settings);

            // sort
            $content_set->multisort($settings['sort']);            
            
            // post-sort supplement
            $content_set->supplement(array(
                'group_by_date' => trim($this->fetchParam("group_by_date", null, null, false, false))
            ), true);

            // store content as blink content for future use
            $this->blink->set($content_hash, $content_set->extract());
        }

        return $content_set;
    }
Пример #22
0
 public function count()
 {
     // grab parameters
     $from = $this->fetchParam('from', URL::getCurrent());
     $exclude = $this->fetchParam('exclude', false);
     $max_depth = $this->fetchParam('max_depth', 1, 'is_numeric');
     $include_entries = $this->fetchParam('include_entries', false, false, true);
     $folders_only = $this->fetchParam('folders_only', true, false, true);
     $include_content = $this->fetchParam('include_content', false, false, true);
     $show_hidden = $this->fetchParam('show_hidden', false, null, true);
     // add in left-/ if not present
     if (substr($from, 0, 1) !== '/') {
         $from = '/' . $from;
     }
     // if this doesn't start with the site root, add the site root
     if (!Pattern::startsWith($from, Config::getSiteRoot())) {
         $from = Path::tidy(Config::getSiteRoot() . '/' . $from);
     }
     // standardize excludes
     if ($exclude && !is_array($exclude)) {
         $exclude = Helper::explodeOptions($exclude, array());
         foreach ($exclude as $key => $value) {
             $exclude[$key] = Path::tidy(Config::getSiteRoot() . '/' . $value);
         }
     }
     // option hash
     $hash = Helper::makeHash($from, $exclude, $max_depth, $include_entries, $folders_only, $include_content, $show_hidden);
     // load the content tree from cache
     if ($this->blink->exists($hash)) {
         $tree = $this->blink->get($hash);
     } else {
         $tree = ContentService::getContentTree($from, $max_depth, $folders_only, $include_entries, $show_hidden, $include_content, $exclude);
         $this->blink->set($hash, $tree);
     }
     if ($this->content) {
         return Parse::template($this->content, array('count' => count($tree)));
     } elseif (count($tree)) {
         return count($tree);
     }
     return '';
 }
Пример #23
0
 /**
  * Returns a ContentSet object with the appropriate content
  *
  * @param array  $settings  Settings for filtering content and such
  * @return ContentSet
  */
 private function getContentSet($settings)
 {
     // create a unique hash for these settings
     $content_hash = Helper::makeHash($settings);
     if ($this->blink->exists($content_hash)) {
         // blink content exists, use that
         $content_set = new ContentSet($this->blink->get($content_hash));
     } else {
         // no blink content exists, get data the hard way
         if ($settings['taxonomy']) {
             $taxonomy_parts = Taxonomy::getCriteria(URL::getCurrent());
             $taxonomy_type = $taxonomy_parts[0];
             $taxonomy_slug = Config::get('_taxonomy_slugify') ? Slug::humanize($taxonomy_parts[1]) : urldecode($taxonomy_parts[1]);
             $content_set = ContentService::getContentByTaxonomyValue($taxonomy_type, $taxonomy_slug, $settings['folders']);
         } else {
             $content_set = ContentService::getContentByFolders($settings['folders']);
         }
         // filter
         $content_set->filter($settings);
         // sort
         $content_set->sort($settings['sort_by'], $settings['sort_dir']);
         // store content as blink content for future use
         $this->blink->set($content_hash, $content_set->extract());
     }
     return $content_set;
 }
 /**
  * Gets cached content for pages for a certain taxonomy type and value
  *
  * @param string  $taxonomy  Taxonomy to use
  * @param string  $values  Values to match (single or array)
  * @param mixed  $folders  Optionally, folders to filter down by
  * @return ContentSet
  */
 public static function getContentByTaxonomyValue($taxonomy, $values, $folders = null)
 {
     self::loadCache();
     $case_sensitive = Config::getTaxonomyCaseSensitive();
     if ($folders) {
         $folders = Parse::pipeList($folders);
     }
     // if an array was sent
     if (is_array($values)) {
         $files = array();
         if (!$case_sensitive) {
             $values = array_map('strtolower', $values);
         }
         // loop through each of the values looking for files
         foreach ($values as $value) {
             if (!isset(self::$cache["taxonomies"][$taxonomy][$value])) {
                 continue;
             }
             // add these file names to the big file list
             $files = array_merge($files, self::$cache["taxonomies"][$taxonomy][$value]['files']);
         }
         // get unique list of files
         $files = array_unique($files);
         // if a single value was sent
     } else {
         if (!$case_sensitive) {
             $values = strtolower($values);
         }
         if (!isset(self::$cache["taxonomies"][$taxonomy][$values])) {
             $files = array();
         } else {
             $files = self::$cache["taxonomies"][$taxonomy][$values]['files'];
         }
     }
     // if no files, abort
     if (!count($files)) {
         return new ContentSet(array());
     }
     // still here? grab data from cache
     $data = array();
     foreach ($files as $file) {
         $data[] = ContentService::getContent($file);
     }
     // build a new ContentSet with the data we have
     $content_set = new ContentSet($data);
     // if there are folders to filter on, filter
     if ($folders) {
         $content_set->filter(array("folders" => $folders));
     }
     return $content_set;
 }
Пример #25
0
            $app->pass();
        }

    });

}


/////////////////////////////////////////////////////////////////////////////////////////////////
// Bundle Asset Pipeline
/////////////////////////////////////////////////////////////////////////////////////////////////

$app->get('/_add-ons/(:segments+)', function($segments = array()) use ($app) {

    // reset any content service caching that's been done
    ContentService::resetCaches();

    // clean segments
    $segments = URL::sanitize($segments);
    $file_requested = implode($segments, '/');
    
    $bundle_folder  = APP_PATH . "/core/bundles/" . $segments[0];
    $file = APP_PATH . "/core/bundles/" . $file_requested;

    $file = realpath($file);
    
    // prevent bad access of files
    if (strpos($file_requested, '../') !== false || File::getExtension($file) === 'php') {
        $app->pass();
        return;
    }
Пример #26
0
 private function completeEdit($submission, $config, $entry)
 {
     $content_set = ContentService::getContentByURL(Helper::decrypt($entry))->extract();
     // Bail if the content doesn't exist. Someone tweaked it. Tsk tsk.
     if (!count($content_set)) {
         return;
     }
     // Get front-matter from existing submission
     $content = current($content_set);
     $yaml = YAML::parseFile($content['_file']);
     // MERGE!@#!
     $submission = array_merge($yaml, $submission);
     // Update the entry
     $file_content = File::buildContent($submission, '');
     File::put($content['_file'], $file_content);
     // Shall we send?
     if (array_get($config, 'send_notification_email', false) === true) {
         $this->sendEmails($submission, $config, 'update');
     }
     // Save data to flash for use in raven:submission
     $this->flash->set('submission', $submission);
 }
Пример #27
0
 /**
  * Gets the target data from the cache
  *
  * @param array  $config  Configuration array
  * @return array
  */
 public function getData($config)
 {
     // load data
     if ($config['taxonomy']) {
         $taxonomy_parts = Taxonomy::getCriteria(URL::getCurrent());
         $taxonomy_type = $taxonomy_parts[0];
         $taxonomy_slug = Config::get('_taxonomy_slugify') ? Slug::humanize($taxonomy_parts[1]) : urldecode($taxonomy_parts[1]);
         $content_set = ContentService::getContentByTaxonomyValue($taxonomy_type, $taxonomy_slug, $config['folders']);
     } else {
         $content_set = ContentService::getContentByFolders($config['folders']);
     }
     // filters
     $content_set->filter($config);
     // custom filter, remove the 404 page if needed
     if (!$config['include_404']) {
         $content_set->customFilter(function ($item) {
             return $item['url'] !== '/404';
         });
     }
     // custom filter, remove any excluded folders
     if ($config['exclude']) {
         $excluded = Parse::pipeList($config['exclude']);
         $content_set->customFilter(function ($item) use($excluded) {
             foreach ($excluded as $exclude) {
                 if ($exclude === "*" || $exclude === "/*") {
                     // exclude all
                     return false;
                 } elseif (substr($exclude, -1) === "*") {
                     // wildcard check
                     if (strpos($item['_folder'], substr($exclude, 0, -1)) === 0) {
                         return false;
                     }
                 } else {
                     // plain check
                     if ($exclude == $item['_folder']) {
                         return false;
                     }
                 }
             }
             return true;
         });
     }
     $content_set->supplement(array('merge_with_data' => false));
     $content_set->prepare($config['include_content']);
     $data = $content_set->get();
     return $data;
 }
Пример #28
0
 /**
  * Finds content by path
  * 
  * @param string  $path  Path to use to look for content
  * @return array|false
  */
 public static function find($path)
 {
     $hash = Debug::markStart('content', 'finding');
     // ensure it starts with /
     $path = Path::tidy('/' . $path);
     ContentService::loadCache();
     $urls = ContentService::$cache['urls'];
     foreach ($urls as $url => $data) {
         if ($data['path'] === $path) {
             return Content::get($url, false, false);
         }
     }
     Debug::markEnd($hash);
     return false;
 }
Пример #29
0
    public function render()
    {
        $field_data = $this->field_data;

        /*
        |--------------------------------------------------------------------------
        | Multi-select
        |--------------------------------------------------------------------------
        |
        | We need to set an empty array brace [] and add the "multiple" attribute
        | in the event we want to allow multi-selects. We also change the
        | plurality of the placeholder content.
        |
        */

        $max_items = array_get($this->field_config, 'max_items', 'null');
        $force_list = array_get($this->field_config, 'force_list', false);
        $multiple = array_get($this->field_config, 'multiple', true);
        $allow_blank = array_get($this->field_config, 'allow_blank', false);
        $placeholder = array_get($this->field_config, 'placeholder', false);

        if ($max_items === 1 && !$force_list) {
            $multiple = false;
        }

        $multiple_array_holder = $multiple ? '[]' : '';
        $multiple_string = $multiple ? "multiple='multiple'" : '';
        $placeholder_string = $placeholder ? "placeholder='$placeholder'" : '';

        $suggestions = array();

        /*
        |--------------------------------------------------------------------------
        | Hardcoded list of options
        |--------------------------------------------------------------------------
        |
        | Any list can contain a preset list of options available for suggestion,
        | exactly like how the Select fieldtype works.
        |
        */

        if (isset($this->field_config['options'])) {
            $options = $this->field_config['options'];
            $suggestions = array_merge($suggestions, $options);
        }

        /*
        |--------------------------------------------------------------------------
        | Entries & Pages
        |--------------------------------------------------------------------------
        |
        | Fetch a list of pages and/or entries, using any existing fields as
        | labels and values
        |
        */

        if (isset($this->field_config['content'])) {

            $config = $this->field_config['content'];

            $value   = array_get($config, 'value', 'url');
            $label   = array_get($config, 'label', 'title');
            $folder  = array_get($config, 'folder');


            $content_set = ContentService::getContentByFolders(array($folder));

            $content_set->filter(array(
                    'show_hidden' => array_get($config, array('show_hidden', 'show_all'), false),  // show_all is legacy
                    'show_drafts' => array_get($config, 'show_drafts', false),
                    'since'       => array_get($config, 'since'),
                    'until'       => array_get($config, 'until'),
                    'show_past'   => array_get($config, 'show_past', true),
                    'show_future' => array_get($config, 'show_future', true),
                    'type'        => array_get($config, 'type', 'entries'),
                    'conditions'  => trim(array_get($config, 'conditions'))
                )
            );
            $entries = $content_set->get();

            foreach ($entries as $entry) {
                $pieces = array();
                foreach (Helper::ensureArray($label) as $label_part) {
                    if (isset($entry[$label_part]) && isset($entry[$value])) {
                        $pieces[] = $entry[$label_part];
                    }
                }

                $suggestions[$entry[$value]] = join(' – ', $pieces);
            }
        }

        /*
        |--------------------------------------------------------------------------
        | Taxonomies
        |--------------------------------------------------------------------------
        |
        | Single taxonomy types can be fetched from any folder. The taxonomy label
        | and value will be identical to ensure consistency with template logic
        |
        */

        if (isset($this->field_config['taxonomy'])) {

            $taxonomy_type = array_get($this->field_config, 'taxonomy:type');
            $folder        = array_get($this->field_config, 'taxonomy:folder');
            $taxonomy_set  = ContentService::getTaxonomiesByType($taxonomy_type);

            // now filter that down to just what we want
            $taxonomy_set->filter(array(
                "min_count" => 1,
                "folders"   => array($folder)
            ));

            $taxonomy_set->contextualize($folder);
            $taxonomies = $taxonomy_set->get();


            foreach ($taxonomies as $key => $value) {
                $taxonomies[$key] = $value['name'];
            }

            $suggestions = array_merge($suggestions, $taxonomies);
        }

        /*
        |--------------------------------------------------------------------------
        | Members
        |--------------------------------------------------------------------------
        |
        | Fetch a list of members, using any existing fields as labels and values
        |
        */

        if (isset($this->field_config['members'])) {

            $config = $this->field_config['members'];

            $value   = array_get($config, 'value', '_uid');
            $label   = array_get($config, 'label', 'username');

            $member_set = MemberService::getMembers();
            $member_set->filter(array(
                'role'   => array_get($config, 'role')
            ));
            $members = $member_set->get();

            foreach ($members as $key => $member) {
                if (isset($member[$label]) && isset($member[$value])) {
                    $suggestions[$member[$value]] = $member[$label];
                }
            }
        }

        /*
        |--------------------------------------------------------------------------
        | Input HTML
        |--------------------------------------------------------------------------
        |
        | Generate the HTML for the select field. A single, blank option is
        | needed if allow blank is true.
        |
        */
       
        if ($max_items === null && $multiple === false) {
            $max_items = 1;
        }

        $options = json_encode(array(
            'sortField'      => 'text',
            'maxItems'      => $max_items,
            'delimiter'      => ',',
            'create'         => array_get($this->field_config, 'create', false),
            'persist'        => array_get($this->field_config, 'persist', true),
            'hideSelected'   => array_get($this->field_config, 'hide_selected', true),
            'sortDirection'  => array_get($this->field_config, 'sort_dir', 'asc'),
            'plugins'        => array('drag_drop'),
            'dropdownParent' => 'body'
        ));

        $html = "<div id='$this->field_id' class='suggest-field-container' data-config='$options'>";
        $html .= "<select name='{$this->fieldname}{$multiple_array_holder}' tabindex='{$this->tabindex}' $multiple_string $placeholder_string class='suggest'>\n";

        $is_indexed = (array_values($suggestions) === $suggestions);

        // Preserve existing data's order
        if (is_array($field_data)) {
            $field_data = array_combine($field_data, $field_data);
            $suggestions = array_merge($field_data, $suggestions);
        }

        if ($allow_blank) {
            $html .= "<option value=''></option>\n";
        }

        foreach ($suggestions as $value => $label) {

            $value = $is_indexed ? $label : $value; #allows setting custom values and labels

            if ($multiple && is_array($field_data) ) {
                $selected = in_array($value, $field_data) ? " selected " : '';
            } else {
                $selected = $field_data == $value ? " selected " : '';
            }

            $html .= '<option value="'. $value .'" ' . $selected .'>' . $label .'</option>';
        }

        $html .= "</select>";
        $html .= "<div class='count-placeholder'></div></div>";

        $html .= "<script>$('#{$this->field_id}').statamicSuggest();</script>";

        return $html;
    }
Пример #30
0
 public static function find_relative($current, $folder = null, $future = false, $past = true, $show_hidden = false)
 {
     $content_set = ContentService::getContentByFolders($folder);
     $content_set->filter(array('show_hidden' => $show_hidden, 'show_drafts' => false, 'show_future' => $future, 'show_past' => $past, 'type' => 'entries'));
     $content_set->sort();
     $content = $content_set->get(false, false);
     $relative = array('prev' => null, 'next' => null);
     $use_next = false;
     $prev = false;
     foreach ($content as $data) {
         // find previous
         if (!$prev && $current != $data['url']) {
             $relative['prev'] = $data['url'];
             continue;
         }
         // we have found the current url
         // set the currently-set previous url to be `prev`
         // and mark the next iteration to use its value as `next`
         if ($current == $data['url']) {
             $prev = true;
             $use_next = true;
             continue;
         }
         // we should use this url as `next`
         if ($use_next) {
             $relative['next'] = $data['url'];
             break;
         }
     }
     return $relative;
 }