<?php
namespace Moto\Application\Themes; use Moto\Json\Response; use Moto\Json\Server; use Moto; class Service extends Moto\Service\AbstractStaticService { protected static $_resourceName = 'themes'; protected static $_resourcePrivilegesMap = array( 'getList' => 'get', ); protected static $_previewImageFile = 'preview.png'; protected static $_themeSettingsFile = 'theme.json'; protected static $_themeLessFile = 'less/styles.less'; public static function getList() { $themesPath = Moto\System::getAbsolutePath('@themes'); if (!is_dir($themesPath) || !is_readable($themesPath)) { throw new Server\Exception(Moto\System\Exception::ERROR_NOT_FOUND_MESSAGE, Moto\System\Exception::ERROR_NOT_FOUND_CODE); } $themes = array(); $activeTheme = Moto\Website\Settings::get('theme'); foreach (scandir($themesPath) as $theme) { $themePath = $themesPath . '/' . $theme . '/'; if ($theme === '.' || $theme === '..' || is_file($themePath)) { continue; } if (!file_exists($themePath . static::$_previewImageFile) || !file_exists($themePath . static::$_themeSettingsFile)) { continue; } if (!is_readable($themePath . static::$_previewImageFile) || !is_readable($themePath . static::$_themeSettingsFile)) { continue; } $info = \Zend\Json\Json::decode(file_get_contents($themePath . static::$_themeSettingsFile), 1); $themes[] = array( 'info' => $info, 'name' => $theme, 'active' => $theme == $activeTheme ); } return new Response\Collection(array( 'meta' => array( 'total' => count($themes), 'page' => 1, ), 'records' => $themes )); } public static function activate($name) { $name = trim((string)$name); if (!preg_match('/^[a-z0-9\_\-]+$/i', $name)) { throw new Server\Exception(Moto\System\Exception::ERROR_BAD_REQUEST_MESSAGE, Moto\System\Exception::ERROR_BAD_REQUEST_CODE, array('name' => 'notValid')); } $themePath = Moto\System::getAbsolutePath('@themes/' . $name); if (!static::_isValidTheme($themePath)) { throw new Server\Exception(Moto\System\Exception::ERROR_NOT_FOUND_MESSAGE, Moto\System\Exception::ERROR_NOT_FOUND_CODE); } try{ Moto\Website\Theme::activate($name, 'activate'); } catch(\Exception $e) { $errors = array(); if ($e instanceof Moto\Exception) { $errors = $e->getErrors(); } if (Moto\System::isDevelopmentStage()) { Moto\System\Log::error('Exception:THEME_ACTIVATION_FAILED', [ 'code' => $e->getCode(), 'message' => $e->getMessage(), 'class' => get_class($e), ]); } throw new Server\Exception('COMMON.ERROR.THEME_ACTIVATION_FAILED', 500, $errors); } return true; } public static function _isValidTheme($path) { $result = true; $result &= is_dir($path); $result &= is_file($path . '/' . static::$_previewImageFile); $result &= is_file($path . '/' . static::$_themeSettingsFile); $result &= is_readable($path . '/' . static::$_themeSettingsFile); $result &= is_file($path . '/' . static::$_themeLessFile); $result &= is_readable($path . '/' . static::$_themeLessFile); return $result; } }