/** * Test get tax rate for class id. */ public function testGetRateForClassId() { $taxService = $this->get('taxService'); $taxRate = $taxService->getTaxRateForClassId(1, 223, 18); $this->assertNotNull($taxRate); $this->assertTrue($taxRate instanceof \ZenMagick\StoreBundle\Entity\TaxRate); if ($taxRate) { $this->assertEquals('1_223_18', $taxRate->getId()); $this->assertEquals(1, $taxRate->getClassId()); $this->assertEquals(223, $taxRate->getCountryId()); $this->assertEquals(18, $taxRate->getZoneId()); // check for 7 decimal digits $this->assertEquals(7.0, $taxRate->getRate()); } // test non existing $taxRate = $taxService->getTaxRateForClassId(2, 223, 18); $this->assertNotNull($taxRate); $this->assertTrue($taxRate instanceof \ZenMagick\StoreBundle\Entity\TaxRate); if ($taxRate) { $this->assertEquals(2, $taxRate->getClassId()); $this->assertEquals(Runtime::getSettings()->get('storeCountry'), $taxRate->getCountryId()); $this->assertEquals(Runtime::getSettings()->get('storeZone'), $taxRate->getZoneId()); // check for 6 decimal digits $this->assertEquals(0, $taxRate->getRate()); } else { $this->fail('no default tax rate not found'); } }
/** * Create new image info. * * @param string image The image name; default is <code>null</code>. * @param string alt The alt text; default is an empty string. */ public function __construct($image = null, $alt = '') { parent::__construct($image, $alt); $this->image = $image; $this->formattedParameter = ''; $plugin = Runtime::getContainer()->get('pluginService')->getPluginForId('imageHandler2'); }
/** * Encode a given string to valid HTML. * * @param string s The string to encode. * @return string The encoded HTML. */ public static function encode($s) { $charset = Runtime::getSettings()->get('zenmagick.http.html.charset'); $s = html_entity_decode($s, ENT_QUOTES, $charset); $s = htmlentities($s, ENT_QUOTES, $charset); return $s; }
/** * Start mocking around. * * @param ShoppingCart shoppingCart The current shopping cart. * @param ZenMagick\StoreBundle\Entity\Address shippingAddress Optional shipping address; default is <code>null</code>. */ public static function startMock(ShoppingCart $shoppingCart, $shippingAddress = null) { global $order, $shipping_weight, $shipping_quoted, $shipping_num_boxes, $total_count, $order_total_modules; global $_order, $_shipping_weight, $_shipping_quoted, $_shipping_num_boxes, $_total_count, $_order_total_modules; if (self::$mock++) { // already mocking return; } // save originals $_order = $order; $_shipping_weight = $shipping_weight; $_shipping_quoted = $shipping_quoted; $_shipping_num_boxes = $shipping_num_boxes; $_total_count = $total_count; $_order_total_modules = $order_total_modules; if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = new \ZenMagick\ZenCartBundle\Compat\ShoppingCart(); } // get total number of products, not line items... $total_count = 0; foreach ($shoppingCart->getItems() as $item) { $total_count += $item->getQuantity(); } //$order_total_modules = new ZenCartOrderTotal(); if (null == $order || !$order instanceof ZenCartCheckoutOrder) { $mockOrder = new ZenCartCheckoutOrder(); $mockOrder->setContainer(Runtime::getContainer()); $mockOrder->setShoppingCart($shoppingCart); if (null != $shippingAddress) { $mockOrder->setShippingAddress($shippingAddress); } $order = $mockOrder; } // START: adjust boxes, weight and tare $shipping_quoted = ''; $shipping_num_boxes = 1; $shipping_weight = $shoppingCart->getWeight(); $za_tare_array = preg_split("/[:,]/", SHIPPING_BOX_WEIGHT); $zc_tare_percent = $za_tare_array[0]; $zc_tare_weight = $za_tare_array[1]; $za_large_array = preg_split("/[:,]/", SHIPPING_BOX_PADDING); $zc_large_percent = $za_large_array[0]; $zc_large_weight = $za_large_array[1]; switch (true) { // large box add padding case SHIPPING_MAX_WEIGHT <= $shipping_weight: $shipping_weight = $shipping_weight + $shipping_weight * ($zc_large_percent / 100) + $zc_large_weight; break; default: // add tare weight < large $shipping_weight = $shipping_weight + $shipping_weight * ($zc_tare_percent / 100) + $zc_tare_weight; break; } if ($shipping_weight > SHIPPING_MAX_WEIGHT) { // Split into many boxes $shipping_num_boxes = ceil($shipping_weight / SHIPPING_MAX_WEIGHT); $shipping_weight = $shipping_weight / $shipping_num_boxes; } // END: adjust boxes, weight and tare }
/** * Validate the given request data. * * @param ZenMagick\Http\Request request The current request. * @param array data The data. * @return boolean <code>true</code> if the value for <code>$name</code> is valid, <code>false</code> if not. */ public function validate($request, $data) { if (!Runtime::getSettings()->get('isAccountState')) { return true; } //todo: this should not be here, but in the corresponding controller classes - BEFORE the validation is done $state = isset($data['state']) ? $data['state'] : null; $zoneId = isset($data['zoneId']) ? $data['zoneId'] : null; $zones = $this->container->get('countryService')->getZonesForCountryId($data['countryId']); $valid = false; if (0 < count($zones)) { // need $state to match either an id or name foreach ($zones as $zone) { if ($zone->getName() == $state || $zone->getId() == $state || $zone->getId() == $zoneId || $zone->getCode() == $state) { $zoneId = $zone->getId(); $state = ''; $valid = true; break; } } } else { if (!empty($state)) { $valid = true; $zoneId = 0; } } // check for form bean if (array_key_exists('__obj', $data)) { $data['__obj'] = Beans::setAll($data['__obj'], array('state' => $state, 'zoneId' => $zoneId)); } return $valid; }
/** * Create new patch. * * @param string id Id of the patch. */ public function __construct($id) { parent::__construct(); $this->container = \ZenMagick\Base\Runtime::getContainer(); $this->id = $id; $this->label = $id . ' Patch'; $this->messages = array(); }
/** * Create new application * * @param string environment The environment * @param boolean debug Whether to enable debugging or not * @param array config Optional config settings. */ public function __construct($environment = 'prod', $debug = false, $context = null) { $this->context = $context; // @todo FIXME: Only save it the first time. this gets called again via ConfigCache if (null === Runtime::getContext()) { Runtime::setContext($context); } parent::__construct($environment, $debug); }
/** * Get a database connection by name. * * @param string name get default connection if null. * @return ZenMagick\Base\Database\Connection */ public static function getDatabase($conf = 'default') { if (null !== Runtime::getContainer()) { return Runtime::getContainer()->get('doctrine.dbal.' . $conf . '_connection'); } if (is_array(self::$databaseMap[$conf])) { self::$databaseMap[$conf] = Doctrine\DBAL\DriverManager::getConnection(self::$databaseMap[$conf]); } return self::$databaseMap[$conf]; }
/** * Create new instance. */ public function __construct() { parent::__construct(); $settingsService = Runtime::getContainer()->get('settingsService'); $this->set('includeTax', $settingsService->get('showPricesTaxIncluded')); $this->set('countryId', $settingsService->get('storeCountry')); $this->set('zoneId', $settingsService->get('storeCountry')); $this->set('languageId', $settingsService->get('storeDefaultLanguageId')); $this->set('searchAll', false); }
/** * Create new result list. */ public function __construct() { parent::__construct(); $this->resultSource = null; $this->filters = array(); $this->sorters = array(); $this->page = 1; $this->pagination = Runtime::getSettings()->get('zenmagick.mvc.resultlist.defaultPagination'); $this->allResults = null; $this->results = null; }
/** * {@inheritDoc} */ public function getOptions($request) { $options = parent::getOptions($request); // try to find a useful countryId, defaulting to store country Id $countryId = Runtime::getSettings()->get('storeCountry'); //XXX: where else to look ?? foreach ($this->container->get('countryService')->getZonesForCountryId($countryId) as $zone) { $options[$zone->getId()] = $zone->getName(); } return $options; }
/** * zen_build_html_email_from_template wrapper that delegates to either the Zenmagick implementation or the renamed original * version of it. */ function zen_build_html_email_from_template($template, $args = array()) { $container = Runtime::getContainer(); if ($container->hasParameter('zencart.use_native_email') && $container->getParameter('zencart.use_native_email')) { return zen_build_html_email_from_template_org($template, $args); } $messageBuilder = $container->get('messageBuilder'); $request = $container->get('request'); $emailContext = $GLOBALS['ZM_EMAIL_CONTEXT']; unset($GLOBALS['ZM_EMAIL_CONTEXT']); return $messageBuilder->createContents($template, true, $request, $emailContext); }
/** * Create a new instance. * */ public function __construct() { parent::__construct(); $this->tableMap = array(); $this->tablePrefix = ''; // load from file $mappings = array(); eval('$mappings = ' . file_get_contents(Runtime::getInstallationPath() . '/src/ZenMagick/StoreBundle/config/db_mappings.txt')); foreach ($mappings as $table => $mapping) { $this->setMappingForTable($table, $mapping); } }
/** * Create new instance. */ public function __construct() { parent::__construct(); $this->setFirstName('foo'); $this->setLastName('bar'); $this->setCompany('Doo Ltd.'); $this->setAddressLine1('1 Street'); $this->setSuburb('Suburb'); $this->setPostcode('1234'); $this->setCity('The City'); $this->setState('Some State'); $this->setCountry(Runtime::getContainer()->get('countryService')->getCountryForId('NZ')); }
/** * Create new instance. */ public function __construct(ContainerInterface $container) { $this->container = $container; parent::__construct(); $this->sets = array(); $this->alias = array(); $this->messages = array(); if (Runtime::isContextMatch('storefront')) { // yucky, but easier now than later $rootDir = $container->getParameter('zenmagick.root_dir'); $this->load($rootDir . '/src/ZenMagick/StorefrontBundle/config/validation.php'); } }
/** * Create new instance. */ public function __construct() { parent::__construct('prfilter', Runtime::getContainer()->get('translator')->trans('Price Range')); $this->ranges = array(); if (!empty($this->filterValues) && is_array($this->filterValues)) { // values are in the form of from-to foreach ($this->filterValues as $value) { $range = explode('-', $value); if (!empty($value)) { $this->ranges[$value] = $range; } } } }
/** * @todo Move this init back into ZenCartAutoLoader or an event * when we can lazy load the shopping cart class. */ public function initClassLoader() { $isAdmin = Runtime::isContextMatch('admin'); !defined('IS_ADMIN_FLAG') && define('IS_ADMIN_FLAG', $isAdmin); $classLoader = new \Composer\AutoLoad\ClassLoader(); $classLoader->register(); $container = $this->container; $zcRoot = $this->container->getParameter('zencart.root_dir'); $zc = $zcRoot . '/includes/classes/'; $zca = $this->container->getParameter('zencart.admin_dir') . '/includes/classes/'; $b = __DIR__ . '/bridge/includes/classes/'; $ba = __DIR__ . '/bridge/admin/includes/classes/'; $map = array('httpClient' => $zc . 'http_client.php', 'category_tree' => $zc . 'category_tree.php', 'language' => ($isAdmin ? $ba : $b) . 'language.php', 'products' => $zc . 'products.php', 'splitPageResults' => ($isAdmin ? $zca : $zc) . 'split_page_results.php', 'template_func' => $zc . 'template_func.php', 'PHPMailer' => $zc . 'class.phpmailer.php', 'SMTP' => $zc . 'class.smtp.php', 'payment' => $zc . 'payment.php', 'order_total' => $zc . 'order_total.php', 'shipping' => $zc . 'shipping.php', 'order' => ($isAdmin ? $zca : $zc) . 'order.php', 'box' => $zca . 'box.php', 'objectInfo' => $zca . 'object_info.php', 'tableBlock' => $zca . 'table_block.php', 'upload' => $zca . 'upload.php'); $classLoader->addClassMap($map); }
/** * {@inheritDoc} */ public function getStatusMessages() { $messages = array(); $settingsService = $this->container->get('settingsService'); $warnBeforeMaintenance = $settingsService->get('apps.store.warnBeforeMaintenance'); $downForMaintenance = $settingsService->get('apps.store.downForMaintenance'); $translator = $this->container->get('translator'); if ($warnBeforeMaintenance && !$downForMaintenance) { $configService = $this->container->get('configService'); $downForMaintenanceDateTime = $configService->getConfigValue('PERIOD_BEFORE_DOWN_FOR_MAINTENANCE'); $messages[] = array(StatusCheck::STATUS_NOTICE, $translator->trans('This website is scheduled to be "<em>Down For Maintenance</em>" on: %s.', array('%time_date%' => $downForMaintenanceDateTime->getValue()))); } if ($downForMaintenance && !Runtime::isContextMatch('storefront')) { $messages[] = array(StatusCheck::STATUS_WARN, $translator->trans('The website is currently "<em>Down For Maintenance</em>" to the public.')); } return $messages; }
/** * zen_href_link wrapper that delegates to the Zenmagick implementation (for storefront). */ function zen_href_link($page = '', $params = '', $transport = 'NONSSL', $addSessionId = true, $seo = true, $isStatic = false, $useContext = true) { $router = Runtime::getContainer()->get('router'); $page = str_replace('.php', '', $page); if (false !== strpos($page, '?')) { list($page, $pageParams) = explode('?', $page); $params .= $pageParams; } parse_str($params, $tmp); $params = $tmp; try { return $router->generate('zc_admin_' . $page, $params); } catch (\Symfony\Component\Routing\Exception\RouteNotFoundException $e) { } // try without return $router->generate($page, $params); }
/** * Reset all internal data structures. */ public function reset() { $this->mappings = array('default' => array(), 'mappings' => array()); $this->handlers = array(); $this->permissionProviders = array(); $context = Runtime::getContext(); if ('admin' == $context) { $def = 'ZenMagick\\Http\\Sacs\\Handler\\UserRoleSacsHandler'; } if (empty($def) || !class_exists($def)) { return; } if (null != ($handler = new $def())) { $handler->setContainer($this->container); $this->handlers[$handler->getName()] = $handler; } }
/** * Redirect to a url (safely) * * This function safely shuts down Symfony by making sure the * response and terminate kernel events are called. * * @param string $url The url to redirect to * @param int $response_code http response code (defaults to 302) */ function zen_redirect($url, $responseCode = 302) { // fix accidental ampersands $url = str_replace(array('&', '&&'), '&', $url); $container = Runtime::getContainer(); $request = $container->get('request'); if (ENABLE_SSL == 'true' && $request->isSecure()) { $url = str_replace('http://', 'https://', $url); } $response = new RedirectResponse($url, $responseCode); $httpKernel = $container->get('http_kernel'); $event = new FilterResponseEvent($httpKernel, $request, HttpKernelInterface::MASTER_REQUEST, $response); $dispatcher = $container->get('event_dispatcher'); $dispatcher->dispatch(KernelEvents::RESPONSE, $event); $response->send(); $httpKernel->terminate($request, $response); exit; }
/** * Get a list of all available editors. * * @return array A class/name map of editors. */ public static function getEditorMap() { $container = Runtime::getContainer(); $editorMap = array(); foreach ($container->get('containerTagService')->findTaggedServiceIds('zenmagick.apps.store.editor') as $id => $args) { $label = $id; foreach ($args as $elem) { foreach ($elem as $key => $value) { if ('label' == $key) { $label = $value; break; } } } $editorMap[$id] = $label; } return $editorMap; }
/** * Validate the given request data. * * @param ZenMagick\Http\Request request The current request. * @param array data The data. * @return boolean <code>true</code> if the value for <code>$name</code> is valid, <code>false</code> if not. */ public function validate($request, $data) { if (empty($data[$this->getName()])) { return true; } $amount = $data[$this->getName()]; $account = $this->container->get('security.context')->getToken()->getUser(); $balance = $account->getVoucherBalance(); $currentCurrencyCode = $request->getSession()->get('currency'); if (Runtime::getSettings()->get('defaultCurrency') != $currentCurrencyCode) { // need to convert amount to default currency as GV values are in default currency $currency = $this->container->get('currencyService')->getCurrencyForCode($currentCurrencyCode); $amount = $currency->convertFrom($amount); } if (0 == $amount || $amount > $balance) { return false; } return true; }
/** * Execute this patch. * * @param boolean force If set to <code>true</code> it will force patching even if * disabled as per settings. * @return boolean <code>true</code> if patching was successful, <code>false</code> if not. */ public function patch($force = false) { $configService = Runtime::getContainer()->get('configService'); // Create configuration groups $group = $configService->getConfigGroupForName('ZenMagick Configuration'); if (null == $group) { $group = $configService->createConfigGroup('ZenMagick Configuration', 'ZenMagick Configuration', false); } $pluginGroup = $configService->getConfigGroupForName('ZenMagick Plugins'); if (null == $pluginGroup) { $pluginGroup = $configService->createConfigGroup('ZenMagick Plugins', 'ZenMagick Plugins', false); } $groupId = $group->getId(); $pluginGroupId = $pluginGroup->getId(); // create configuration values if (null == $configService->getConfigValue('ZENMAGICK_CONFIG_GROUP_ID')) { $configService->createConfigValue('ZenMagick Configuration Group Id', 'ZENMAGICK_CONFIG_GROUP_ID', $groupId, $groupId); } if (null == $configService->getConfigValue('ZENMAGICK_PLUGIN_STATUS')) { $configService->createConfigValue('ZenMagick Plugin Status', 'ZENMAGICK_PLUGIN_STATUS', '', $groupId); } if (null == $configService->getConfigValue('ZENMAGICK_PLUGIN_GROUP_ID')) { $configService->createConfigValue('ZenMagick Plugins Group Id', 'ZENMAGICK_PLUGIN_GROUP_ID', $pluginGroupId, $groupId); } $modulesGroup = $configService->getConfigGroupForName('Module Options')->getId(); if (null == $configService->getConfigValue('PRODUCTS_OPTIONS_TYPE_SELECT')) { $title = 'Product option type Select'; $description = 'Numeric value of the text product option type.'; $configService->createConfigValue($title, 'PRODUCTS_OPTIONS_TYPE_SELECT', 0, $modulesGroup, $description); } if (null == $configService->getConfigValue('TEXT_PREFIX')) { $title = 'Text Prefix'; $description = 'Prefix used to differentiate between text option values and other option values'; $configService->createConfigValue($title, 'TEXT_PREFIX', 'txt_', $modulesGroup, $description); } if (null == $configService->getConfigValue('UPLOAD_PREFIX')) { $title = 'Upload Prefix'; $description = 'Prefix used to differentiate between upload option values and other option values'; $configService->createConfigValue($title, 'UPLOAD_PREFIX', 'upload_', $modulesGroup, $description); } return true; }
/** * ZenMagick implementation of zen-cart's zen_href_link function. * * @todo improve this entirely! */ public static function zenHrefLink($page, $params = '', $transport = 'NONSSL', $addSessionId = true, $seo = true, $isStatic = false, $useContext = true) { $container = Runtime::getContainer(); $request = $container->get('request'); $page = trim($page, '&?'); $page = str_replace('&', '&', $page); $params = trim(trim($params), '&?'); $params = str_replace('&', '&', $params); if ('index.php' == $page) { $page = 'index'; } if ('ipn_main_handler.php' == $page) { $page = 'ipn_main_handler'; } $requestId = $page; parse_str($params, $parameters); if (0 === strpos($page, 'index.php?')) { // EZPage altUrl $page = str_replace('index.php?', '', $page); parse_str($page, $extra); if (array_key_exists('main_page', $extra)) { $requestId = $extra['main_page']; unset($extra['main_page']); } $parameters = array_merge($extra, $parameters); } // @todo if we still keep someting like this.. wrong place! if (array_key_exists('products_id', $parameters)) { $parameters['productId'] = $parameters['products_id']; unset($parameters['products_id']); } if ('login' == $requestId) { if (array_key_exists('action', $parameters) && 'process' == $parameters['action']) { unset($parameters['action']); $requestId = 'login_check'; } } return $container->get('router')->generate($requestId, $parameters); }
/** * Load attributes for the given product. * * @param ZenMagick\StoreBundle\Entity\Product product The product. * @return boolean <code>true</code> if attributes eixst, <code>false</code> if not. */ public function getAttributesForProduct($product) { // set up sort order SQL $attributesOrderBy = ''; if (Runtime::getSettings()->get('isSortAttributesByName')) { $attributesOrderBy = ' ORDER BY po.products_options_name'; } else { $attributesOrderBy = ' ORDER BY LPAD(po.products_options_sort_order, 11, "0")'; } $sql = "SELECT distinct po.products_options_id, po.products_options_name, po.products_options_sort_order,\n po.products_options_type, po.products_options_length, po.products_options_comment, po.products_options_size,\n po.products_options_images_per_row, po.products_options_images_style, pa.products_id\n FROM %table.products_options% po, %table.products_attributes% pa\n WHERE pa.products_id = :productId\n AND pa.options_id = po.products_options_id\n AND po.language_id = :languageId" . $attributesOrderBy; $args = array('productId' => $product->getId(), 'languageId' => $product->getLanguageId()); $attributes = \ZMRuntime::getDatabase()->fetchAll($sql, $args, array('products_options', 'products_attributes'), 'ZenMagick\\StoreBundle\\Entity\\Catalog\\Attribute'); if (0 == count($attributes)) { return $attributes; } // put in map for easy lookup $attributeMap = array(); foreach ($attributes as $attribute) { $attributeMap[$attribute->getId()] = $attribute; } $sql = "SELECT pov.products_options_values_id, pov.products_options_values_name, pa.*\n FROM %table.products_attributes% pa, %table.products_options_values% pov\n WHERE pa.products_id = :productId\n AND pa.options_id IN (:attributeId)\n AND pa.options_values_id = pov.products_options_values_id\n AND pov.language_id = :languageId "; // set up sort order SQL if (Runtime::getSettings()->get('isSortAttributeValuesByPrice')) { $sql .= ' ORDER BY pa.options_id, LPAD(pa.products_options_sort_order, 11, "0"), pa.options_values_price'; } else { $sql .= ' ORDER BY pa.options_id, LPAD(pa.products_options_sort_order, 11, "0"), pov.products_options_values_name'; } // read all in one go $args = array('attributeId' => array_keys($attributeMap), 'productId' => $product->getId(), 'languageId' => $product->getLanguageId()); $mapping = array('products_options_values', 'products_attributes'); foreach (\ZMRuntime::getDatabase()->fetchAll($sql, $args, $mapping, 'ZMAttributeValue') as $value) { $attribute = $attributeMap[$value->getAttributeId()]; $value->setAttribute($attribute); $value->setTaxRate($product->getTaxRate()); $attribute->addValue($value); } return $attributes; }
/** * {@inheritDoc} */ public function populate($raw) { $recommendations = new ZMLiftSuggestRecommendations(); $recommended = $this->getFromSession('reco_prods', array()); // process product infos $products = array(); foreach ($raw['products'] as $details) { if (array_key_exists('sku', $details)) { $product = $this->container->get('productService')->getProductForId($details['sku'], Runtime::getSettings()->get('storeDefaultLanguageId')); if (null != $product && $product->getStatus()) { $info = array('product' => null, 'info' => array()); foreach ($details as $key => $value) { if ('sku' == $key) { $info['product'] = $product; $recommended[] = $product->getId(); } else { // other details $info['info'][$key] = $value; } } $products[] = $info; } } } $recommendations->set('productDetails', $products); // keep other foreach ($raw as $key => $details) { if ('products' != $key) { $recommendations->set($key, $details); if ('popular_perc' == $key) { $recommendations->set('popularity', $details); } } } $this->storeInSession('reco_prods', $recommended); return $recommendations; }
/** * Check stock. * * @param boolean messages Optional flag to enable/hide messages related to stock checking; default is <code>true</code>. * @return boolean <code>true</code> if the stock check was sucessful (or disabled). */ public function checkStock($messages = true) { if (Runtime::getSettings()->get('isEnableStock') && $this->shoppingCart->hasOutOfStockItems()) { $flashBag = $this->container->get('session')->getFlashBag(); if (Runtime::getSettings()->get('isAllowLowStockCheckout')) { if ($messages) { $flashBag->warn('Products marked as "Out Of Stock" will be placed on backorder.'); } return true; } else { if ($messages) { $flashBag->error('The shopping cart contains products currently out of stock. To checkout you may either lower the quantity or remove those products from the cart.'); } return false; } } return true; }
/** * Set up. */ public function setUp() { parent::setUp(); // all tests assume this Runtime::getSettings()->set('zenmagick.mvc.resultlist.defaultPagination', 10); }
/** * Apply user/group settings to file(s) that should allow ftp users to modify/delete them. * * <p>The file group attribute is only going to be changed if the <code>$perms</code> parameter is not empty.</p> * * <p>This method may be disabled by setting <em>zenmagick.core.fs.permissions.fix</em> to <code>false</code>.</p> * * @param mixed files Either a single filename or list of files. * @param boolean recursive Optional flag to recursively process all files/folders in a given directory; default is <code>false</code>. * @param array perms Optional file permissions; defaults are taken from the settings <em>fs.permissions.defaults.folder</em> for folder, * <em>fs.permissions.defaults.file</em> for files. * * @todo rewrite to use Symfony\Component\Filesystem methods. */ public function setFilePerms($files, $recursive = false, $perms = array()) { $settingsService = Runtime::getSettings(); if (!$settingsService->get('zenmagick.core.fs.permissions.fix')) { return; } if (null == $this->fileOwner || null == $this->fileGroup) { clearstatcache(); $this->fileOwner = fileowner(__FILE__); $this->fileGroup = filegroup(__FILE__); if (0 == $this->fileOwner && 0 == $this->fileGroup) { return; } } if (!is_array($files)) { $files = array($files); } $filePerms = array_merge(array('file' => $settingsService->get('zenmagick.core.fs.permissions.defaults.file', '0644'), 'folder' => $settingsService->get('zenmagick.core.fs.permissions.defaults.folder', '0755')), $perms); foreach ($filePerms as $type => $perms) { if (is_string($perms)) { $filePerms[$type] = intval($perms, 8); } } foreach ($files as $file) { if (0 < count($perms)) { @chgrp($file, $this->fileGroup); } @chown($file, $this->fileOwner); $mod = $filePerms[is_dir($file) ? 'folder' : 'file']; @chmod($file, $mod); if (is_dir($file) && $recursive) { $dir = $file; $dir = rtrim($dir, '/') . '/'; $subfiles = array(); $handle = @opendir($dir); while (false !== ($file = readdir($handle))) { if ("." == $file || ".." == $file) { continue; } $subfiles[] = $dir . $file; } @closedir($handle); $this->setFilePerms($subfiles, $recursive, $perms); } } }