/** * Get device features * * @return Application_Model_Device */ public function getDevice() { if ($this->device == null) { $this->device = false; $devices = Application_Model_DevicesMapper::i()->fetchAll(); /* @var Application_Model_Device $device */ foreach ($devices as $device) { // if exact do an == comparison if ($device->isExact() && $device->getPattern() == $_SERVER['HTTP_USER_AGENT'] || !$device->isExact() && preg_match($device->getPattern(), $_SERVER['HTTP_USER_AGENT']) > 0) { // valid $device found; $this->device = $device; break; } } if ($this->device == false) { // load things from default $this->device = new Application_Model_Device(); if (X_VlcShares_Plugins::broker()->isRegistered('wiimc')) { $this->device->setGuiClass($this->options->get('gui', 'X_VlcShares_Plugins_WiimcPlxRenderer')); } else { $this->device->setGuiClass($this->options->get('gui', 'X_VlcShares_Plugins_WebkitRenderer')); } $this->device->setIdProfile($this->options->get('profile', 1))->setLabel("Unknown device"); } } return $this->device; }
/** * @return bool|\Dingo\Api\Models\ApiKey */ protected function pullApiKey() { $headers = ['ID', 'Service', 'Name', 'Token']; $this->table($headers, $this->user->apiKeys()->get(['id', 'service', 'name', 'token'])); $key_id = $this->ask('What key are we using?'); if ($key_id === 'exit') { exit; } if ($key = $this->user->apiKeys()->where('id', $key_id)->first()) { return $key; } $this->error('ApiKey ' . $key_id . ' not found!'); return false; }
/** * Migrate constructor * * @param string $dirname module directory name that defines the tables to be migrated * * @throws \InvalidArgumentException * @throws \RuntimeException */ public function __construct($dirname) { $this->helper = Helper::getHelper($dirname); if (false === $this->helper) { throw new \InvalidArgumentException("Invalid module {$dirname} specified"); } $module = $this->helper->getModule(); $this->moduleTables = $module->getInfo('tables'); if (empty($this->moduleTables)) { throw new \RuntimeException("No tables established in module"); } $version = $module->getInfo('version'); $this->tableDefinitionFile = $this->helper->path("sql/{$dirname}_{$version}_migrate.yml"); $this->tableHandler = new Tables(); }
/** * Save image information to DB. * * @param \Magento\Catalog\Model\Product $product * @param array $images * @return void */ protected function storeImage($product, $images) { $baseImage = ''; $i = 1; $mediaAttribute = $this->eavConfig->getAttribute('catalog_product', 'media_gallery'); foreach ($images as $image) { if (empty($image)) { $this->errors[] = $product->getSku(); continue; } if (strpos($image, '_main') !== false) { $baseImage = $image; } $id = $this->galleryResource->insertGallery(['attribute_id' => $mediaAttribute->getAttributeId(), 'entity_id' => $product->getId(), 'value' => $image]); $this->galleryResource->insertGalleryValueInStore(['value_id' => $id, 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID, 'entity_id' => $product->getId(), 'label' => 'Image', 'position' => $i, 'disables' => 0]); $this->galleryResource->bindValueToEntity($id, $product->getId()); $i++; } if (empty($baseImage)) { $baseImage = $images[0]; } if ($baseImage) { $imageAttribute = $product->getResource()->getAttribute('image'); $smallImageAttribute = $product->getResource()->getAttribute('small_image'); $thumbnailAttribute = $product->getResource()->getAttribute('thumbnail'); $adapter = $product->getResource()->getConnection(); foreach ([$imageAttribute, $smallImageAttribute, $thumbnailAttribute] as $attribute) { $table = $imageAttribute->getBackend()->getTable(); /** @var \Magento\Framework\DB\Adapter\AdapterInterface $adapter*/ $data = [$attribute->getBackend()->getEntityIdField() => $product->getId(), 'attribute_id' => $attribute->getId(), 'value' => $baseImage]; $adapter->insertOnDuplicate($table, $data, ['value']); } } }
/** * Returns the site with provided global id, or false if there is no such site. * * @since 1.21 * * @param string $globalId * @param string $source * * @return Site|false */ public function getSite($globalId, $source = 'cache') { if ($source === 'cache' && $this->sites !== false) { return $this->sites->hasSite($globalId) ? $this->sites->getSite($globalId) : false; } return SitesTable::singleton()->selectRow(null, array('global_key' => $globalId)); }
protected function getPrimaryValue() { if (!$this->primaryValue && $this->value && $this->value->isPersisted()) { $this->primaryValue = $this->value->getValue('id'); } return $this->primaryValue; }
/** * Send a mail using this transport * * @param \Zend\Mail\Mail $mail * @access public * @return void * @throws \Zend\Mail\Transport\Exception if mail is empty */ public function send(\Zend\Mail\Mail $mail) { $this->_isMultipart = false; $this->_mail = $mail; $this->_parts = $mail->getParts(); $mime = $mail->getMime(); // Build body content $this->_buildBody(); // Determine number of parts and boundary $count = count($this->_parts); $boundary = null; if ($count < 1) { throw new Exception('Empty mail cannot be sent'); } if ($count > 1) { // Multipart message; create new MIME object and boundary $mime = new Mime\Mime($this->_mail->getMimeBoundary()); $boundary = $mime->boundary(); } elseif ($this->_isMultipart) { // multipart/alternative -- grab boundary $boundary = $this->_parts[0]->boundary; } // Determine recipients, and prepare headers $this->recipients = implode(',', $mail->getRecipients()); $this->_prepareHeaders($this->_getHeaders($boundary)); // Create message body // This is done so that the same \Zend\Mail\Mail object can be used in // multiple transports $message = new Mime\Message(); $message->setParts($this->_parts); $message->setMime($mime); $this->body = $message->generateMessage($this->EOL); // Send to transport! $this->_sendMail(); }
private static function log($level, $string, $statsLog = false) { if (php_sapi_name() === 'cli' || defined('STDIN')) { // we are being executed from the CLI, nowhere to log return; } if (self::$loggingHandler === null) { // Initialize logging self::createLoggingHandler(); if (!empty(self::$earlyLog)) { error_log('----------------------------------------------------------------------'); // output messages which were logged before we properly initialized logging foreach (self::$earlyLog as $msg) { self::log($msg['level'], $msg['string'], $msg['statsLog']); } } } elseif (self::$loggingHandler === false) { // some error occurred while initializing logging if (empty(self::$earlyLog)) { // this is the first message error_log('--- Log message(s) while initializing logging ------------------------'); } error_log($string); self::defer($level, $string, $statsLog); return; } if (self::$captureLog) { $ts = microtime(true); $msecs = (int) (($ts - (int) $ts) * 1000); $ts = GMdate('H:i:s', $ts) . sprintf('.%03d', $msecs) . 'Z'; self::$capturedLog[] = $ts . ' ' . $string; } if (self::$logLevel >= $level || $statsLog) { if (is_array($string)) { $string = implode(",", $string); } $formats = array('%trackid', '%msg', '%srcip', '%stat'); $replacements = array(self::$trackid, $string, $_SERVER['REMOTE_ADDR']); $stat = ''; if ($statsLog) { $stat = 'STAT '; } array_push($replacements, $stat); if (self::$trackid === self::NO_TRACKID && !self::$shuttingDown) { // we have a log without track ID and we are not still shutting down, so defer logging self::defer($level, $string, $statsLog); return; } elseif (self::$trackid === self::NO_TRACKID) { // shutting down without a track ID, prettify it array_shift($replacements); array_unshift($replacements, 'N/A'); } // we either have a track ID or we are shutting down, so just log the message $string = str_replace($formats, $replacements, self::$format); self::$loggingHandler->log($level, $string); } }
/** * Get the lowest and highest timestamp for a category. * * @param Title $category * @return array The lowest and highest timestamp * @throws MWException If category has no entries. */ protected function getMinAndMaxForCat(Title $category) { $dbr = wfGetDB(DB_REPLICA); $res = $dbr->selectRow('categorylinks', ['low' => 'MIN( cl_timestamp )', 'high' => 'MAX( cl_timestamp )'], ['cl_to' => $this->category->getDBkey()], __METHOD__, ['LIMIT' => 1]); if (!$res) { throw new MWException('No entries in category'); } return [wfTimestamp(TS_UNIX, $res->low), wfTimestamp(TS_UNIX, $res->high)]; }
/** * Checks if current position is valid. * * @return bool Returns true on success, false otherwise */ public function valid() { if (is_null($this->current)) { return !empty($this->branch); } if ($this->current instanceof RecursiveLeafInterface) { return $this->current->valid(); } return false; }
/** * Show the template to the user. */ public function show() { if ($this->twig !== false) { $this->twigDefaultContext(); echo $this->twig->render($this->twig_template, $this->data); } else { $filename = $this->findTemplatePath($this->template); require $filename; } }
/** * Returns cache * * @return AppCache The update cache * @since 2.0 */ protected function getCache() { if (empty($this->_cache)) { $this->_cache = $this->app->cache->create($this->app->path->path('cache:') . '/zoo_update_cache'); if (!$this->_cache->check()) { $this->app->system->application->enqueueMessage('Cache not writeable please update the file permissions!', 'warning'); } } return $this->_cache; }
/** * Purges the cache store, and loader if there is one. * * @return bool True on success, false otherwise */ public function purge() { // 1. Purge the persist cache. $this->persistcache = array(); // 2. Purge the store. $this->store->purge(); // 3. Optionally pruge any stacked loaders. if ($this->loader) { $this->loader->purge(); } return true; }
/** * Purges the cache store, and loader if there is one. * * @return bool True on success, false otherwise */ public function purge() { // 1. Purge the static acceleration array. $this->static_acceleration_purge(); // 2. Purge the store. $this->store->purge(); // 3. Optionally pruge any stacked loaders. if ($this->loader) { $this->loader->purge(); } return true; }
/** * Send a mail using this transport * * @param OpenPGP_Zend_Mail $mail * @access public * @return void * @throws Zend_Mail_Transport_Exception if mail is empty */ public function send(OpenPGP_Zend_Mail $mail) { $this->_isMultipart = false; $this->_mail = $mail; $this->_parts = $mail->getParts(); $mime = $mail->getMime(); // Build body content $this->_buildBody(); // Determine number of parts and boundary $count = count($this->_parts); $boundary = null; if ($count < 1) { throw new Zend_Mail_Transport_Exception('Empty mail cannot be sent'); } if ($count > 1) { // Multipart message; create new MIME object and boundary $mime = new Zend_Mime($this->_mail->getMimeBoundary()); $boundary = $mime->boundary(); } elseif ($this->_isMultipart) { // multipart/alternative -- grab boundary $boundary = $this->_parts[0]->boundary; } // Determine recipients, and prepare headers $this->recipients = implode(',', $mail->getRecipients()); $this->_prepareHeaders($this->_getHeaders($boundary)); // Create message body // This is done so that the same OpenPGP_Zend_Mail object can be used in // multiple transports $message = new Zend_Mime_Message(); $message->setParts($this->_parts); $message->setMime($mime); $this->body = $message->generateMessage($this->EOL); //////////////////////////////////////////////////////// // // // ALPHAFIELDS 2012-11-03: ADDED PGP/MIME ENCRYPTION // // USING lib/openpgp/opepgplib.php // // // //////////////////////////////////////////////////////// // get from globals (set in tiki-setup.php) global $openpgplib; $pgpmime_msg = $openpgplib->prepareEncryptWithZendMail($this->header, $this->body, $mail->getRecipients()); $this->header = $pgpmime_msg[0]; // set pgp/mime headers from result array $this->body = $pgpmime_msg[1]; // set pgp/mime encrypted message body from result array //////////////////////////////////////////////////////// // // // ALPHAFIELDS 2012-11-03: ..END PGP/MIME ENCRYPTION // // // //////////////////////////////////////////////////////// // Send to transport! $this->_sendMail(); }
/** * Handle exception (uncatched). * * @param \Throwable $exception */ public function handleException($exception) { if (!$exception instanceof \Exception) { $exception = new \Exception("Can't handle exception thrown!"); } // Log \Logger::error((string) $exception); // Whoops if ($this->whoops !== false) { $this->whoops->handleException($exception); } }
/** * @param string $keyword * @param int $keywordAdditionalWeight */ public function run($keyword, $keywordAdditionalWeight = 0) { if ($this->_databaseConnection) { $prefix = config('coaster::blog.prefix'); $blogPosts = $this->_databaseConnection->query("\n SELECT wp.*, weights.search_weight FROM wp_posts wp RIGHT JOIN\n (\n SELECT ID, sum(search_weight) as search_weight\n FROM (\n SELECT ID, 4 AS search_weight FROM {$prefix}posts WHERE post_type = 'post' AND post_status = 'publish' AND post_title like '%" . $keyword . "%'\n UNION\n SELECT ID, 2 AS search_weight FROM {$prefix}posts WHERE post_type = 'post' AND post_status = 'publish' AND post_content like '%" . $keyword . "%'\n ) results\n GROUP BY ID\n ) weights\n ON weights.ID = wp.ID;\n "); if ($blogPosts) { $defaultSeparator = new Path(false); foreach ($blogPosts as $blogPost) { $postData = new \stdClass(); $postData->id = 'WP' . $blogPost['ID']; unset($blogPost['ID']); foreach ($blogPost as $field => $value) { $postData->{$field} = $value; } $postData->content = $blogPost['post_content']; $postData->fullName = ucwords(str_replace('/', ' ', config('coaster::blog.url'))) . $defaultSeparator->separator . $blogPost['post_title']; $postData->fullUrl = config('coaster::blog.url') . $blogPost['post_name']; self::_addWeight($postData, $blogPost['search_weight'] + $keywordAdditionalWeight); } } } }
/** * Checks if login is required on this site. is_required for public access * * @since 0.1.0 * * @return boolean Enabled or disabled */ protected function get_required_option_bool() { $setting = $this->get_option('require'); if ('enabled' === $setting) { return true; } if ('disabled' === $setting) { return false; } if ($this->network_admin) { return (bool) $this->network_admin->get_option('enable_network_wide'); } return false; }
/** * Returns array('success'=>true) or array('error'=>'error message') */ public function handleUpload() { if (!$this->file) { return array('error' => Tools::displayError('No files were uploaded.')); } $size = $this->file->getSize(); if ($size == 0) { return array('error' => Tools::displayError('File is empty')); } if ($size > $this->sizeLimit) { return array('error' => Tools::displayError('File is too large')); } $pathinfo = pathinfo($this->file->getName()); $these = implode(', ', $this->allowedExtensions); if (!isset($pathinfo['extension'])) { return array('error' => sprintf(Tools::displayError('File has an invalid extension, it should be one of these: %s.'), $these)); } $ext = $pathinfo['extension']; if ($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) { return array('error' => sprintf(Tools::displayError('File has an invalid extension, it should be one of these: %s.'), $these)); } return $this->file->save(); }
/** * Log an action. * * @since 0.1 * * @param string $subType */ protected function log($subType) { if ($this->log) { $info = $this->getLogInfo($subType); if ($info !== false) { if ($this->revAction !== false) { $info['user'] = $this->revAction->getUser(); $info['comment'] = $this->revAction->getComment(); } $info['subtype'] = $subType; EPUtils::log($info); } } }
/** * @param UnicatConfigurationManager $ucm * @param TaxonModel|false $lastTaxon * * @throws \Exception */ protected function buildFrontControlForTaxon(UnicatConfigurationManager $ucm, $lastTaxon = false) { $this->node->addFrontControl('create_item')->setTitle('Добавить запись')->setUri($this->generateUrl('unicat_admin.item_create_in_taxon', ['configuration' => $ucm->getConfiguration()->getName(), 'default_taxon_id' => empty($lastTaxon) ? 0 : $lastTaxon->getId()])); if (!empty($lastTaxon)) { $this->node->addFrontControl('create_taxon')->setIsDefault(false)->setTitle('Создать Taxon')->setUri($this->generateUrl('unicat_admin.structure_with_parent_id', ['configuration' => $ucm->getConfiguration()->getName(), 'parent_id' => empty($lastTaxon) ? 0 : $lastTaxon->getId(), 'id' => $lastTaxon->getStructure()->getId()])); $this->node->addFrontControl('edit_taxon')->setIsDefault(false)->setTitle('Редактировать Taxon')->setUri($this->generateUrl('unicat_admin.taxon', ['configuration' => $ucm->getConfiguration()->getName(), 'id' => $lastTaxon->getId(), 'structure_id' => $lastTaxon->getStructure()->getId()])); } $this->node->addFrontControl('manage_configuration')->setIsDefault(false)->setTitle('Управление каталогом')->setUri($this->generateUrl('unicat_admin.configuration', ['configuration' => $ucm->getConfiguration()->getName()])); }
/** * Purges the cache store, and loader if there is one. * * @return bool True on success, false otherwise */ public function purge() { // 1. Purge the static acceleration array. $this->staticaccelerationarray = array(); if ($this->staticaccelerationsize !== false) { $this->staticaccelerationkeys = array(); $this->staticaccelerationcount = 0; } // 2. Purge the store. $this->store->purge(); // 3. Optionally pruge any stacked loaders. if ($this->loader) { $this->loader->purge(); } return true; }
/** * Resolve a class name from self/parent. * * @param string $class The class name. * * @return string The resolved class name. */ protected function _resolveName($class) { if (!$this->called_in_class) { return $class; } switch ($class) { case '$this': case 'self': $class = $this->called_in_class->getShortName(); break; case 'parent': $class = $this->called_in_class->getNode()->extends->toString(); break; } return $class; }
private static function log($level, $string, $statsLog = false) { if (php_sapi_name() === 'cli' || defined('STDIN')) { // we are being executed from the CLI, nowhere to log return; } if (self::$loggingHandler === null) { /* Initialize logging. */ self::createLoggingHandler(); if (!empty(self::$earlyLog)) { error_log('----------------------------------------------------------------------'); // output messages which were logged before we properly initialized logging foreach (self::$earlyLog as $msg) { self::log($msg['level'], $msg['string'], $msg['statsLog']); } } } elseif (self::$loggingHandler === false) { // some error occurred while initializing logging if (empty(self::$earlyLog)) { // this is the first message error_log('--- Log message(s) while initializing logging ------------------------'); } error_log($string); self::$earlyLog[] = array('level' => $level, 'string' => $string, 'statsLog' => $statsLog); return; } if (self::$captureLog) { $ts = microtime(true); $msecs = (int) (($ts - (int) $ts) * 1000); $ts = GMdate('H:i:s', $ts) . sprintf('.%03d', $msecs) . 'Z'; self::$capturedLog[] = $ts . ' ' . $string; } if (self::$logLevel >= $level || $statsLog) { if (is_array($string)) { $string = implode(",", $string); } $formats = array('%trackid', '%msg', '%srcip', '%stat'); $replacements = array(self::getTrackId(), $string, $_SERVER['REMOTE_ADDR']); $stat = ''; if ($statsLog) { $stat = 'STAT '; } array_push($replacements, $stat); $string = str_replace($formats, $replacements, self::$format); self::$loggingHandler->log($level, $string); } }
/** * Checks if REST API bypass is allowed on this site. * * @since 0.1.0 * @return boolean Enabled or disabled */ public function is_required_for_rest($is_required) { $setting = $this->get_option('allow_rest_api'); if ('bypass' === $setting) { return false; } if ('require' === $setting) { return true; } if ('use_require_login_setting' === $setting) { return $is_required; } if ($this->network_admin) { return (bool) $this->network_admin->is_required_for_rest(); } return $is_required; }
/** * Returns the title to return to after the form has been submitted, * or when form use is aborted for some other reason. * * @since 0.1 * * @param boolean $addedItem * * @return Title */ protected function getReturnToTitle($addedItem = false) { if ($this->getRequest()->getCheck('wpreturnto')) { return Title::newFromText($this->getRequest()->getText('wpreturnto')); } elseif (!$addedItem && $this->isNew()) { $c = $this->getItemClass(); // Yeah, this is needed in PHP 5.3 >_> return SpecialPage::getTitleFor($c::getListPage()); } elseif ($this->item !== false) { return $this->item->getTitle(); } else { $c = $this->getItemClass(); // Yeah, this is needed in PHP 5.3 >_> $fieldName = 'wpitem-' . $c::getIdentifierField(); if ($this->getRequest()->getCheck($fieldName)) { return $c::getTitleFor($this->getRequest()->getText($fieldName)); } else { return $this->getTitle(); } } }
/** * Transfoms the response body (json) into an array we can more easily * work with. * * @param \GuzzleHttp\Message\Response|false $response * * @return array */ public function getResponseArray($response) { $return = []; if (!$response instanceof \GuzzleHttp\Message\Response) { $this->errors[] = ['source' => 'client', 'attribute' => null, 'kind' => 'networking', 'message' => 'no response']; return $return; } /** * add error for bad status codes */ $code = $response->getStatusCode(); $errorCodes = [404, 401, 500]; if (in_array($code, $errorCodes)) { $this->errors[] = ['source' => 'client', 'attribute' => null, 'kind' => 'status_code', 'message' => 'Bad status code: ' . $code]; } $body = $response->getBody(); $body = trim((string) $body); /** * Return early if we have an empty body, which we can't turn into an array * anyway. This happens in cases where the API returns a 404, and possibly * other status codes. */ if (empty($body)) { return $return; } $return = json_decode($body, true); // set errors, if any if (!empty($return['result']['errors'])) { foreach ($return['result']['errors'] as $error) { $this->errors[] = $error; } } /** * NOTE: There is also, maybe, an errors array nested in $return['meta']['errors'] * Why is this API so inconsistent???!!!!! */ return $return; }
/** * Fetch the data via SimplePie_File * * If the data is already cached, attempt to fetch it from there instead * @param SimplePie_Cache|false $cache Cache handler, or false to not load from the cache * @return array|true Returns true if the data was loaded from the cache, or an array of HTTP headers and sniffed type */ protected function fetch_data(&$cache) { // If it's enabled, use the cache if ($cache) { // Load the Cache $this->data = $cache->load(); if (!empty($this->data)) { // If the cache is for an outdated build of SimplePie if (!isset($this->data['build']) || $this->data['build'] !== SIMPLEPIE_BUILD) { $cache->unlink(); $this->data = array(); } elseif (isset($this->data['url']) && $this->data['url'] !== $this->feed_url) { $cache = false; $this->data = array(); } elseif (isset($this->data['feed_url'])) { // If the autodiscovery cache is still valid use it. if ($cache->mtime() + $this->autodiscovery_cache_duration > time()) { // Do not need to do feed autodiscovery yet. if ($this->data['feed_url'] !== $this->data['url']) { $this->set_feed_url($this->data['feed_url']); return $this->init(); } $cache->unlink(); $this->data = array(); } } elseif ($cache->mtime() + $this->cache_duration < time()) { // If we have last-modified and/or etag set if (isset($this->data['headers']['last-modified']) || isset($this->data['headers']['etag'])) { $headers = array('Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1'); if (isset($this->data['headers']['last-modified'])) { $headers['if-modified-since'] = $this->data['headers']['last-modified']; } if (isset($this->data['headers']['etag'])) { $headers['if-none-match'] = $this->data['headers']['etag']; } $file = $this->registry->create('File', array($this->feed_url, $this->timeout / 10, 5, $headers, $this->useragent, $this->force_fsockopen)); if ($file->success) { if ($file->status_code === 304) { $cache->touch(); return true; } } else { unset($file); } } } else { $this->raw_data = false; return true; } } else { $cache->unlink(); $this->data = array(); } } // If we don't already have the file (it'll only exist if we've opened it to check if the cache has been modified), open it. if (!isset($file)) { if ($this->file instanceof SimplePie_File && $this->file->url === $this->feed_url) { $file =& $this->file; } else { $headers = array('Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1'); $file = $this->registry->create('File', array($this->feed_url, $this->timeout, 5, $headers, $this->useragent, $this->force_fsockopen)); } } // If the file connection has an error, set SimplePie::error to that and quit if (!$file->success && !($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300))) { $this->error = $file->error; return !empty($this->data); } if (!$this->force_feed) { // Check if the supplied URL is a feed, if it isn't, look for it. $locate = $this->registry->create('Locator', array(&$file, $this->timeout, $this->useragent, $this->max_checked_feeds)); if (!$locate->is_feed($file)) { // We need to unset this so that if SimplePie::set_file() has been called that object is untouched unset($file); try { if (!($file = $locate->find($this->autodiscovery, $this->all_discovered_feeds))) { $this->error = "A feed could not be found at {$this->feed_url}. A feed with an invalid mime type may fall victim to this error, or " . SIMPLEPIE_NAME . " was unable to auto-discover it.. Use force_feed() if you are certain this URL is a real feed."; $this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, __FILE__, __LINE__)); return false; } } catch (SimplePie_Exception $e) { // This is usually because DOMDocument doesn't exist $this->error = $e->getMessage(); $this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, $e->getFile(), $e->getLine())); return false; } if ($cache) { $this->data = array('url' => $this->feed_url, 'feed_url' => $file->url, 'build' => SIMPLEPIE_BUILD); if (!$cache->save($this)) { trigger_error("{$this->cache_location} is not writeable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING); } $cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, call_user_func($this->cache_name_function, $file->url), 'spc')); } $this->feed_url = $file->url; } $locate = null; } $this->raw_data = $file->body; $headers = $file->headers; $sniffer = $this->registry->create('Content_Type_Sniffer', array(&$file)); $sniffed = $sniffer->get_type(); return array($headers, $sniffed); }
/** * @param Product $product * @param null|false|\Magento\Quote\Model\Quote\Address $shipping * @param null|false|\Magento\Quote\Model\Quote\Address $billing * @param Website $website * @param bool $calculateTax * @param bool $round * @return \Magento\Framework\DataObject[] * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function getProductWeeeAttributes($product, $shipping = null, $billing = null, $website = null, $calculateTax = null, $round = true) { $result = []; $websiteId = $this->_storeManager->getWebsite($website)->getId(); /** @var \Magento\Store\Model\Store $store */ $store = $this->_storeManager->getWebsite($website)->getDefaultGroup()->getDefaultStore(); $allWeee = $this->getWeeeTaxAttributeCodes($store); if (!$allWeee) { return $result; } /** @var \Magento\Tax\Model\Calculation $calculator */ $calculator = $this->_calculationFactory->create(); $customerId = $this->_customerSession->getCustomerId(); if ($shipping && $shipping->getCountryId()) { $customerTaxClass = $shipping->getQuote()->getCustomerTaxClassId(); } else { // if customer logged use it default shipping and billing address if ($customerId) { $shipping = $this->accountManagement->getDefaultShippingAddress($customerId); $billing = $this->accountManagement->getDefaultBillingAddress($customerId); $customerTaxClass = null; } else { $shippingAddressArray = $this->_customerSession->getDefaultTaxShippingAddress(); $billingAddressArray = $this->_customerSession->getDefaultTaxBillingAddress(); if (!empty($billingAddressArray)) { $billing = new \Magento\Framework\DataObject($billingAddressArray); } if (!empty($shippingAddressArray)) { $shipping = new \Magento\Framework\DataObject($shippingAddressArray); } $customerTaxClass = $this->_customerSession->getCustomerTaxClassId(); } } $rateRequest = $calculator->getRateRequest($shipping, $billing, $customerTaxClass, $store, $customerId); $defaultRateRequest = $calculator->getDefaultRateRequest($store); $productAttributes = $this->getResource()->fetchWeeeTaxCalculationsByEntity($rateRequest->getCountryId(), $rateRequest->getRegionId(), $websiteId, $store->getId(), $product->getId()); foreach ($productAttributes as $attribute) { $value = $attribute['weee_value']; if ($value) { $taxAmount = $amount = 0; $amount = $value; $amountExclTax = $value; if ($calculateTax && $this->weeeConfig->isTaxable($store)) { /** @var \Magento\Tax\Model\Calculation $calculator */ $defaultPercent = $calculator->getRate($defaultRateRequest->setProductClassId($product->getTaxClassId())); $currentPercent = $calculator->getRate($rateRequest->setProductClassId($product->getTaxClassId())); if ($this->_taxData->priceIncludesTax($store)) { $amountInclTax = $value / (100 + $defaultPercent) * (100 + $currentPercent); if ($round) { $amountInclTax = $this->priceCurrency->round($amountInclTax); } $taxAmount = $amountInclTax - $amountInclTax / (100 + $currentPercent) * 100; if ($round) { $taxAmount = $this->priceCurrency->round($taxAmount); } $amountExclTax = $amountInclTax - $taxAmount; } else { $appliedRates = $this->_calculationFactory->create()->getAppliedRates($rateRequest); if (count($appliedRates) > 1) { $taxAmount = 0; foreach ($appliedRates as $appliedRate) { $taxRate = $appliedRate['percent']; if ($round) { $taxAmount += $this->priceCurrency->round($value * $taxRate / 100); } else { $taxAmount += $value * $taxRate / 100; } } } else { if ($round) { $taxAmount = $this->priceCurrency->round($value * $currentPercent / 100); } else { $taxAmount = $value * $currentPercent / 100; } } } } $one = new \Magento\Framework\DataObject(); $one->setName($attribute['label_value'] ? __($attribute['label_value']) : __($attribute['frontend_label']))->setAmount($amount)->setTaxAmount($taxAmount)->setAmountExclTax($amountExclTax)->setCode($attribute['attribute_code']); $result[] = $one; } } return $result; }
/** * Thanks to the (WebserviceOutputBuilder) WebserviceKey::objOutput * Method build the output depend on the WebserviceRequest::outputFormat * and set HTTP header parameters. * * @return array with displaying informations (used in the dispatcher). */ protected function returnOutput() { $return = array(); // write headers $this->objOutput->setHeaderParams('Access-Time', time())->setHeaderParams('X-Powered-By', 'PrestaShop Webservice')->setHeaderParams('PSWS-Version', _PS_VERSION_)->setHeaderParams('Execution-Time', round(microtime(true) - $this->_startTime, 3)); $return['type'] = strtolower($this->outputFormat); // write this header only now (avoid hackers happiness...) if ($this->_authenticated) { $this->objOutput->setHeaderParams('PSWS-Version', _PS_VERSION_); } // If Specific Management is asked if ($this->objectSpecificManagement instanceof WebserviceSpecificManagementInterface) { try { $return['content'] = $this->objectSpecificManagement->getContent(); } catch (WebserviceException $e) { if ($e->getType() == WebserviceException::DID_YOU_MEAN) { $this->setErrorDidYouMean($e->getStatus(), $e->getMessage(), $e->getWrongValue(), $e->getAvailableValues(), $e->getCode()); } elseif ($e->getType() == WebserviceException::SIMPLE) { $this->setError($e->getStatus(), $e->getMessage(), $e->getCode()); } } } // for use a general output if (!$this->hasErrors() && $this->objectSpecificManagement == null) { if (empty($this->objects)) { try { $return['content'] = $this->objOutput->getResourcesList($this->keyPermissions); } catch (WebserviceException $e) { if ($e->getType() == WebserviceException::DID_YOU_MEAN) { $this->setErrorDidYouMean($e->getStatus(), $e->getMessage(), $e->getWrongValue(), $e->getAvailableValues(), $e->getCode()); } elseif ($e->getType() == WebserviceException::SIMPLE) { $this->setError($e->getStatus(), $e->getMessage(), $e->getCode()); } } } else { try { if (isset($this->urlSegment[1]) && !empty($this->urlSegment[1])) { $type_of_view = WebserviceOutputBuilder::VIEW_DETAILS; } else { $type_of_view = WebserviceOutputBuilder::VIEW_LIST; } if (in_array($this->method, array('PUT', 'POST'))) { $type_of_view = WebserviceOutputBuilder::VIEW_DETAILS; $this->fieldsToDisplay = 'full'; } $return['content'] = $this->objOutput->getContent($this->objects, $this->schemaToDisplay, $this->fieldsToDisplay, $this->depth, $type_of_view); } catch (WebserviceException $e) { if ($e->getType() == WebserviceException::DID_YOU_MEAN) { $this->setErrorDidYouMean($e->getStatus(), $e->getMessage(), $e->getWrongValue(), $e->getAvailableValues(), $e->getCode()); } elseif ($e->getType() == WebserviceException::SIMPLE) { $this->setError($e->getStatus(), $e->getMessage(), $e->getCode()); } } catch (Exception $e) { $this->setError(500, $e->getMessage(), $e->getCode()); } } } // if the output is not enable, delete the content // the type content too if (!$this->_outputEnabled) { if (isset($return['type'])) { unset($return['type']); } if (isset($return['content'])) { unset($return['content']); } } elseif (isset($return['content'])) { $this->objOutput->setHeaderParams('Content-Sha1', sha1($return['content'])); } // if errors happends when creating returned xml, // the usual xml content is replaced by the nice error handler content if ($this->hasErrors()) { $this->_outputEnabled = true; $return['content'] = $this->objOutput->getErrors($this->errors); } if (!isset($return['content']) || strlen($return['content']) <= 0) { $this->objOutput->setHeaderParams('Content-Type', ''); } $return['headers'] = $this->objOutput->buildHeader(); restore_error_handler(); return $return; }