createMock(AppConfig::class); $config->expects($this->any()) ->method('getValue') ->willReturnCallback(function ($app, $key, $default) use (&$appConfig) { return (isset($appConfig[$app]) and isset($appConfig[$app][$key])) ? $appConfig[$app][$key] : $default; }); $config->expects($this->any()) ->method('setValue') ->willReturnCallback(function ($app, $key, $value) use (&$appConfig) { if (!isset($appConfig[$app])) { $appConfig[$app] = []; } $appConfig[$app][$key] = $value; }); $config->expects($this->any()) ->method('getValues') ->willReturnCallback(function ($app, $key) use (&$appConfig) { if ($app) { return $appConfig[$app]; } else { $values = []; foreach ($appConfig as $appid => $appData) { if (isset($appData[$key])) { $values[$appid] = $appData[$key]; } } return $values; } }); return $config; } /** @var IUserSession|MockObject */ protected $userSession; /** @var IConfig|MockObject */ private $config; /** @var IGroupManager|MockObject */ protected $groupManager; /** @var AppConfig|MockObject */ protected $appConfig; /** @var ICache|MockObject */ protected $cache; /** @var ICacheFactory|MockObject */ protected $cacheFactory; /** @var IEventDispatcher|MockObject */ protected $eventDispatcher; /** @var LoggerInterface|MockObject */ protected $logger; protected IURLGenerator&MockObject $urlGenerator; /** @var IAppManager */ protected $manager; protected function setUp(): void { parent::setUp(); $this->userSession = $this->createMock(IUserSession::class); $this->groupManager = $this->createMock(IGroupManager::class); $this->config = $this->createMock(IConfig::class); $this->appConfig = $this->getAppConfig(); $this->cacheFactory = $this->createMock(ICacheFactory::class); $this->cache = $this->createMock(ICache::class); $this->eventDispatcher = $this->createMock(IEventDispatcher::class); $this->logger = $this->createMock(LoggerInterface::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->overwriteService(AppConfig::class, $this->appConfig); $this->overwriteService(IURLGenerator::class, $this->urlGenerator); $this->cacheFactory->expects($this->any()) ->method('createDistributed') ->with('settings') ->willReturn($this->cache); $this->config ->method('getSystemValueBool') ->with('installed', false) ->willReturn(true); $this->manager = new AppManager( $this->userSession, $this->config, $this->groupManager, $this->cacheFactory, $this->eventDispatcher, $this->logger, ); } /** * @dataProvider dataGetAppIcon */ public function testGetAppIcon($callback, ?bool $dark, ?string $expected): void { $this->urlGenerator->expects($this->atLeastOnce()) ->method('imagePath') ->willReturnCallback($callback); if ($dark !== null) { $this->assertEquals($expected, $this->manager->getAppIcon('test', $dark)); } else { $this->assertEquals($expected, $this->manager->getAppIcon('test')); } } public function dataGetAppIcon(): array { $nothing = function ($appId) { $this->assertEquals('test', $appId); throw new \RuntimeException(); }; $createCallback = function ($workingIcons) { return function ($appId, $icon) use ($workingIcons) { $this->assertEquals('test', $appId); if (in_array($icon, $workingIcons)) { return '/path/' . $icon; } throw new \RuntimeException(); }; }; return [ 'does not find anything' => [ $nothing, false, null, ], 'nothing if request dark but only bright available' => [ $createCallback(['app.svg']), true, null, ], 'nothing if request bright but only dark available' => [ $createCallback(['app-dark.svg']), false, null, ], 'bright and only app.svg' => [ $createCallback(['app.svg']), false, '/path/app.svg', ], 'dark and only app-dark.svg' => [ $createCallback(['app-dark.svg']), true, '/path/app-dark.svg', ], 'dark only appname -dark.svg' => [ $createCallback(['test-dark.svg']), true, '/path/test-dark.svg', ], 'bright and only appname.svg' => [ $createCallback(['test.svg']), false, '/path/test.svg', ], 'priotize custom over default' => [ $createCallback(['app.svg', 'test.svg']), false, '/path/test.svg', ], 'defaults to bright' => [ $createCallback(['test-dark.svg', 'test.svg']), null, '/path/test.svg', ], 'no dark icon on default' => [ $createCallback(['test-dark.svg', 'test.svg', 'app-dark.svg', 'app.svg']), false, '/path/test.svg', ], 'no bright icon on dark' => [ $createCallback(['test-dark.svg', 'test.svg', 'app-dark.svg', 'app.svg']), true, '/path/test-dark.svg', ], ]; } public function testEnableApp(): void { // making sure "files_trashbin" is disabled if ($this->manager->isEnabledForUser('files_trashbin')) { $this->manager->disableApp('files_trashbin'); } $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new AppEnableEvent('files_trashbin')); $this->manager->enableApp('files_trashbin'); $this->assertEquals('yes', $this->appConfig->getValue('files_trashbin', 'enabled', 'no')); } public function testDisableApp(): void { $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new AppDisableEvent('files_trashbin')); $this->manager->disableApp('files_trashbin'); $this->assertEquals('no', $this->appConfig->getValue('files_trashbin', 'enabled', 'no')); } public function testNotEnableIfNotInstalled(): void { try { $this->manager->enableApp('some_random_name_which_i_hope_is_not_an_app'); $this->assertFalse(true, 'If this line is reached the expected exception is not thrown.'); } catch (AppPathNotFoundException $e) { // Exception is expected $this->assertEquals('Could not find path for some_random_name_which_i_hope_is_not_an_app', $e->getMessage()); } $this->assertEquals('no', $this->appConfig->getValue( 'some_random_name_which_i_hope_is_not_an_app', 'enabled', 'no' )); } public function testEnableAppForGroups(): void { $group1 = $this->createMock(IGroup::class); $group1->method('getGID') ->willReturn('group1'); $group2 = $this->createMock(IGroup::class); $group2->method('getGID') ->willReturn('group2'); $groups = [$group1, $group2]; /** @var AppManager|MockObject $manager */ $manager = $this->getMockBuilder(AppManager::class) ->setConstructorArgs([ $this->userSession, $this->config, $this->groupManager, $this->cacheFactory, $this->eventDispatcher, $this->logger, ]) ->onlyMethods([ 'getAppPath', ]) ->getMock(); $manager->expects($this->exactly(2)) ->method('getAppPath') ->with('test') ->willReturn('apps/test'); $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new AppEnableEvent('test', ['group1', 'group2'])); $manager->enableAppForGroups('test', $groups); $this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no')); } public function dataEnableAppForGroupsAllowedTypes() { return [ [[]], [[ 'types' => [], ]], [[ 'types' => ['nickvergessen'], ]], ]; } /** * @dataProvider dataEnableAppForGroupsAllowedTypes * * @param array $appInfo */ public function testEnableAppForGroupsAllowedTypes(array
# redMine - project management software
# Copyright (C) 2006-2007  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

module Redmine
  module WikiFormatting
    module Macros
      module Definitions
        def exec_macro(name, obj, args)
          method_name = "macro_#{name}"
          send(method_name, obj, args) if respond_to?(method_name)
        end
        
        def extract_macro_options(args, *keys)
          options = {}
          while args.last.to_s.strip =~ %r{^(.+)\=(.+)$} && keys.include?($1.downcase.to_sym)
            options[$1.downcase.to_sym] = $2
            args.pop
          end
          return [args, options]
        end
      end
      
      @@available_macros = {}
      
      class << self
        # Called with a block to define additional macros.
        # Macro blocks accept 2 arguments:
        # * obj: the object that is rendered
        # * args: macro arguments
        # 
        # Plugins can use this method to define new macros:
        # 
        #   Redmine::WikiFormatting::Macros.register do
        #     desc "This is my macro"
        #     macro :my_macro do |obj, args|
        #       "My macro output"
        #     end
        #   end
        def register(&block)
          class_eval(&block) if block_given?
        end
              
      private
        # Defines a new macro with the given name and block.
        def macro(name, &block)
          name = name.to_sym if name.is_a?(String)
          @@available_macros[name] = @@desc || ''
          @@desc = nil
          raise "Can not create a macro without a block!" unless block_given?
          Definitions.send :define_method, "macro_#{name}".downcase, &block
        end
    
        # Sets description for the next macro to be defined
        def desc(txt)
          @@desc = txt
        end
      end
          
      # Builtin macros
      desc "Sample macro."
      macro :hello_world do |obj, args|
        "Hello world! Object: #{obj.class.name}, " + (args.empty? ? "Called with no argument." : "Arguments: #{args.join(', ')}")
      end
    
      desc "Displays a list of all available macros, including description if available."
      macro :macro_list do
        out = ''
        @@available_macros.keys.collect(&:to_s).sort.each do |macro|
          out << content_tag('dt', content_tag('code', macro))
          out << content_tag('dd', textilizable(@@available_macros[macro.to_sym]))
        end
        content_tag('dl', out)
      end
      
      desc "Displays a list of child pages. With no argument, it displays the child pages of the current wiki page. Examples:\n\n" +
             "  !{{child_pages}} -- can be used from a wiki page only\n" +
             "  !{{child_pages(Foo)}} -- lists all children of page Foo\n" +
             "  !{{child_pages(Foo, parent=1)}} -- same as above with a link to page Foo"
      macro :child_pages do |obj, args|
        args, options = extract_macro_options(args, :parent)
        page = nil
        if args.size > 0
          page = Wiki.find_page(args.first.to_s, :project => @project)
        elsif obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version)
          page = obj.page
        else
          raise 'With no argument, this macro can be called from wiki pages only.'
        end
        raise 'Page not found' if page.nil? || !User.current.allowed_to?(:view_wiki_pages, page.wiki.project)
        pages = ([page] + page.descendants).group_by(&:parent_id)
        render_page_hierarchy(pages, options[:parent] ? page.parent_id : page.id)
      end
      
      desc "Include a wiki page. Example:\n\n  !{{include(Foo)}}\n\nor to include a page of a specific project wiki:\n\n  !{{include(projectname:Foo)}}"
      macro :include do |obj, args|
        page = Wiki.find_page(args.first.to_s, :project => @project)
        raise 'Page not found' if page.nil? || !User.current.allowed_to?(:view_wiki_pages, page.wiki.project)
        @included_wiki_pages ||= []
        raise 'Circular inclusion detected' if @included_wiki_pages.include?(page.title)
        @included_wiki_pages << page.title
        out = textilizable(page.content, :text, :attachments => page.attachments)
        @included_wiki_pages.pop
        out
      end
    end
  end
end