/** * Fetches a value in the app's configuration array * @param string $key In dot-notation format * @return mixed */ public static function config($key) { $app = Strata::app(); if (!is_null($app)) { return $app->getConfig($key); } }
/** * Assigns all the declared shell commands of the middlewares. */ public function assign() { $app = Strata::app(); foreach ($app->getMiddlewares() as $middleware) { $this->attemptMultipleRegistrations($middleware->shellCommands); } }
private function logMessage($message = "") { $logger = Strata::app()->getLogger(); if (!is_null($logger)) { $logger->error($message, "Strata:Error"); } }
protected function getTextdomain($default = "strata") { $app = Strata::app(); if ($app && $app->hasConfig("i18n.textdomain")) { return $app->getConfig("i18n.textdomain"); } return $default; }
public function logQueryCompletion($sql) { $executionTime = microtime(true) - $this->executionStart; $timer = sprintf(" (Done in %s seconds)", round($executionTime, 4)); $oneLine = preg_replace('/\\s+/', ' ', trim($sql)); $label = "<magenta>Polyglot</magenta>"; Strata::app()->log($oneLine . $timer, $label); }
public function onTermSave($term_id, $tt_id, $taxonomy) { $this->logger = Strata::app()->getLogger(); if ($this->isAKnownTaxonomy($taxonomy)) { $this->term = get_term_by('id', $term_id, $taxonomy); $this->distributeFields(); } }
/** * Goes through the list of defined middlewares to attempt * to initialize them. */ public function initialize() { if ($this->hasMiddlewares()) { foreach ($this->middlewares as $middleware) { $middleware->initialize(); } Strata::app()->log(sprintf("Loaded <info>%d</info> middlewares", count($this->middlewares)), "<info>Middleware</info>"); } }
public function testCtpAdminMenuRegistered() { $this->wordpress->reset(); $strata = Strata::app(); $strata->setConfig("custom-post-types", array("TestCustomPostType")); $strata->run(); $this->assertArrayHasKey('admin_menu', $this->wordpress->actions); $this->assertTrue($this->wordpress->actions['admin_menu'][0][0] instanceof Registrar); }
public function rewriteStrataPost($postTypekey, $config) { try { $cpt = CustomPostType::factory(substr($postTypekey, 4)); $localizedSlugs = array_merge(array($cpt->hasConfig("rewrite.slug") ? $cpt->getConfig("rewrite.slug") : $postTypekey), $cpt->extractConfig("i18n.{s}.rewrite.slug")); $this->addCustomPostTypeRewrites(implode("|", $localizedSlugs), $postTypekey); } catch (Exception $e) { Strata::app()->log("Tried to translate {$slug}, but could not find the associated model.", "<magenta>Polyglot:UrlRewriter</magenta>"); } }
private function rewriteStrataTaxonomy($taxonomyKey, $config) { try { $taxonomy = Taxonomy::factory(substr($taxonomyKey, 4)); $localizedSlugs = array_merge(array($taxonomy->hasConfig("rewrite.slug") ? $taxonomy->getConfig("rewrite.slug") : $taxonomyKey), $taxonomy->extractConfig("i18n.{s}.rewrite.slug")); $this->addTaxonomyRewrites(implode("|", $localizedSlugs), $config->query_var); } catch (Exception $e) { Strata::app()->log("Tried to translate {$taxonomyKey}, but could not find the associated model.", "<magenta>Polyglot:UrlRewriter</magenta>"); } }
/** * Overrides the default i18n function in order to use * our custom Locale object and have our own set of functions. * @return array */ protected function rebuildLocaleList() { $app = Strata::app(); $original = Hash::normalize($app->getConfig("i18n.locales")); $newLocales = array(); foreach ($original as $key => $config) { $newLocales[$key] = new Locale($key, $config); } return $newLocales; }
/** * {@inheritdoc} */ public function register() { $message = "Timezone set to <info>%s</info>"; $timezone = Strata::app()->getConfig("timezone"); if (is_null($timezone)) { $timezone = self::DEFAULT_TIMEZONE; $message = "Timezone automatically set to <info>%s</info>"; } date_default_timezone_set($timezone); Strata::app()->setConfig("runtime.timezone", sprintf($message, $timezone)); }
/** * Returns the internal custom post type slug * @return string */ public static function wordpressKey() { $app = Strata::app(); $classHash = md5(get_called_class()); $cacheKey = "runtime.static.{$classHash}.wpkey"; if (!$app->hasConfig($cacheKey)) { $obj = self::staticFactory(); $app->setConfig($cacheKey, $obj->getWordpressKey()); } return $app->getConfig($cacheKey); }
public function filter_onSavePost($postId) { if (!$this->isWorking) { $this->logger = Strata::app()->getLogger(); if ($this->isAKnownPost($postId) && Strata::i18n()->currentLocaleIsDefault()) { $this->isWorking = true; $this->distributePostFields(); $this->distributeTemplate(); } $this->isWorking = false; } }
/** * Applies the rules that have been defined at runtime. Note that * the rules are added in the same order as they have been defined * and this may cause racing condition in how rules are applied. * @return boolean Returns whether the process has written in the database */ public function applyRules() { if (!$this->hasRules()) { return false; } $rules = $this->getRules(); foreach ($rules as $rewrite) { add_rewrite_rule($rewrite[0], $rewrite[1], $rewrite[2]); } $wroteInDB = $this->flush(); $message = $wroteInDB ? sprintf("Added <info>%d</info> and flushed the rewrite list.", count($rules)) : sprintf("Added <info>%d</info> while using the cached rewrites.", count($rules)); Strata::app()->log($message, "<info>Rewriter</info>"); return $wroteInDB; }
/** * Registers a taxonomy * @param Taxonomy $taxonomy The taxonomy model * @return object What is being returned by register_taxonomy */ private function registerTaxonomy(Taxonomy $taxonomy) { $labelParser = new LabelParser($taxonomy); $labelParser->parse(); $singular = $labelParser->singular(); $plural = $labelParser->plural(); $key = $this->model->getWordpressKey() . "_" . $taxonomy->getWordpressKey(); $customizedOptions = $taxonomy->getConfiguration() + array('hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'update_count_callback' => '_update_post_term_count', 'query_var' => $key, 'show_in_nav_menus' => false, 'show_tagcloud' => false, 'rewrite' => array(), 'capabilities' => array(), 'labels' => array()); $customizedOptions['capabilities'] += array('manage_terms' => 'read', 'edit_terms' => 'read', 'delete_terms' => 'read', 'assign_terms' => 'read'); $customizedOptions['rewrite'] += array('with_front' => true, 'slug' => $key); $customizedOptions['labels'] += array('name' => _x($plural, 'Post Type General Name', 'strata'), 'singular_name' => _x($singular, 'Post Type Singular Name', 'strata'), 'menu_name' => __($plural, 'strata'), 'parent_item_colon' => __($singular . ' Item:', 'strata'), 'all_items' => __('All ' . $plural, 'strata'), 'view_item' => __('View ' . $singular . ' Item', 'strata'), 'add_new_item' => __('Add New', 'strata'), 'add_new' => __('Add New', 'strata'), 'edit_item' => __('Edit ' . $singular, 'strata'), 'update_item' => __('Update ' . $singular, 'strata'), 'search_items' => __('Search ' . $plural, 'strata'), 'not_found' => __('Not found', 'strata'), 'not_found_in_trash' => __('Not found in Trash', 'strata')); $wordpressKey = $taxonomy->getWordpressKey(); Strata::app()->setConfig("runtime.taxonomy.query_vars.{$wordpressKey}", $customizedOptions['query_var']); return register_taxonomy($wordpressKey, array($this->model->getWordpressKey()), $customizedOptions); }
/** * Sends the email and returns the delivery status * @return boolean */ public function send() { $useHtml = (bool) $this->getConfig("use_html"); $mergedHeaders = $this->getMergedHeaders(); if ($useHtml) { $this->setHtmlEmails(); } $status = wp_mail($this->getConfig("to"), $this->getConfig("title"), $this->getConfig("contents"), $this->toHeaderString($mergedHeaders) . $this->buildBCCString(), $this->getConfig("attachedFile")); $logMessage = $status ? sprintf("<success>Sent an email</success> to %s with title \"%s\" and a body length of %d characters.", implode(", ", (array) $this->getConfig("to")), $this->getConfig("title"), strlen($this->getConfig("contents"))) : sprintf("<warning>Failed to send an email</warning> to %s with title \"%s\" and a body length of %d characters.", implode(", ", (array) $this->getConfig("to")), $this->getConfig("title"), strlen($this->getConfig("contents"))); Strata::app()->log($logMessage, "<info>Strata:Mailer</info>"); if ($useHtml) { $this->setHtmlEmails(false); } return $status; }
/** * Loads up the file located at $templateFilePath, assigns it $variables * and saves the generated HTML. * @param string $templateFilePath * @param array $variables * @param boolean $allowDebug * @return string */ public static function parseFile($templateFilePath, $variables = array(), $allowDebug = true) { ob_start(); // Print debug info in the the logs // only when Strata is running as the development // environment. if (Strata::isDev() && $allowDebug) { $app = Strata::app(); $startedAt = microtime(true); // Print in the html as a comment $partialFilePath = defined('ABSPATH') ? str_replace(dirname(dirname(ABSPATH)), "", $templateFilePath) : $templateFilePath; } extract($variables); include $templateFilePath; if (Strata::isDev() && $allowDebug) { $executionTime = microtime(true) - $startedAt; $timer = sprintf(" (Done in %s seconds)", round($executionTime, 4)); $app->log($partialFilePath . $timer, "<yellow>Template</yellow>"); } return ob_get_clean(); }
/** * Returns this object's class name without the full namespace. * @return string */ public function getShortName() { $app = Strata::app(); $classHash = md5(get_class($this)); $cacheKey = "runtime.static.{$classHash}.shortname"; if (!$app->hasConfig($cacheKey)) { $rc = new ReflectionClass($this); $app->setConfig($cacheKey, $rc->getShortName()); } return $app->getConfig($cacheKey); }
/** * Logs a message warning a routing process had end. */ protected function logRouteCompletion() { $executionTime = microtime(true) - $this->executionStart; $logger = Strata::app()->getLogger(); if ($logger) { $logger->logContextEnd(sprintf("Done in %s seconds", round($executionTime, 4)), "<green>Route</green>"); } }
/** * Generated a Wordpress nonce value. * @param mixed $mixedNonceSalt Something to salt the nonce * @return string */ public function generateNonceKey($mixedNonceSalt = null) { if (!is_string($mixedNonceSalt)) { if (is_object($mixedNonceSalt)) { $methods = get_class_methods($mixedNonceSalt); $mixedNonceSalt = get_class($mixedNonceSalt) . implode("", $methods); } elseif (is_array($mixedNonceSalt)) { $mixedNonceSalt = json_encode($mixedNonceSalt); } } $strataSalt = Strata::app()->hasConfig('security.salt') ? Strata::app()->getConfig('security.salt') : crc32(getenv('SERVER_ADDR')); return $strataSalt . md5($mixedNonceSalt); }
/** * Truncates text. * * Cuts a string to the length of $length and replaces the last characters * with the ellipsis if the text is longer than length. * * ### Options: * * - `ellipsis` Will be used as Ending and appended to the trimmed string (`ending` is deprecated) * - `exact` If false, $text will not be cut mid-word * - `html` If true, HTML tags would be handled correctly * * @param string $text String to truncate. * @param int $length Length of returned string, including ellipsis. * @param array $options An array of html attributes and options. * @return string Trimmed string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate */ public static function truncate($text, $length = 100, $options = array()) { $defaults = array('ellipsis' => '...', 'exact' => true, 'html' => false); if (isset($options['ending'])) { $defaults['ellipsis'] = $options['ending']; } elseif (!empty($options['html']) && Strata::app()->getConfig('app.encoding') === 'UTF-8') { $defaults['ellipsis'] = "…"; } $options += $defaults; extract($options); if (!function_exists('mb_strlen')) { class_exists('Multibyte'); } if ($html) { if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } $totalLength = mb_strlen(strip_tags($ellipsis)); $openTags = array(); $truncate = ''; preg_match_all('/(<\\/?([\\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER); foreach ($tags as $tag) { if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) { if (preg_match('/<[\\w]+[^>]*>/s', $tag[0])) { array_unshift($openTags, $tag[2]); } elseif (preg_match('/<\\/([\\w]+)[^>]*>/s', $tag[0], $closeTag)) { $pos = array_search($closeTag[1], $openTags); if ($pos !== false) { array_splice($openTags, $pos, 1); } } } $truncate .= $tag[1]; $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3])); if ($contentLength + $totalLength > $length) { $left = $length - $totalLength; $entitiesLength = 0; if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) { foreach ($entities[0] as $entity) { if ($entity[1] + 1 - $entitiesLength <= $left) { $left--; $entitiesLength += mb_strlen($entity[0]); } else { break; } } } $truncate .= mb_substr($tag[3], 0, $left + $entitiesLength); break; } else { $truncate .= $tag[3]; $totalLength += $contentLength; } if ($totalLength >= $length) { break; } } } else { if (mb_strlen($text) <= $length) { return $text; } $truncate = mb_substr($text, 0, $length - mb_strlen($ellipsis)); } if (!$exact) { $spacepos = mb_strrpos($truncate, ' '); if ($html) { $truncateCheck = mb_substr($truncate, 0, $spacepos); $lastOpenTag = mb_strrpos($truncateCheck, '<'); $lastCloseTag = mb_strrpos($truncateCheck, '>'); if ($lastOpenTag > $lastCloseTag) { preg_match_all('/<[\\w]+[^>]*>/s', $truncate, $lastTagMatches); $lastTag = array_pop($lastTagMatches[0]); $spacepos = mb_strrpos($truncate, $lastTag) + mb_strlen($lastTag); } $bits = mb_substr($truncate, $spacepos); preg_match_all('/<\\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER); if (!empty($droppedTags)) { if (!empty($openTags)) { foreach ($droppedTags as $closingTag) { if (!in_array($closingTag[1], $openTags)) { array_unshift($openTags, $closingTag[1]); } } } else { foreach ($droppedTags as $closingTag) { $openTags[] = $closingTag[1]; } } } } $truncate = mb_substr($truncate, 0, $spacepos); } $truncate .= $ellipsis; if ($html) { foreach ($openTags as $tag) { $truncate .= '</' . $tag . '>'; } } return $truncate; }
protected function cachePageAtId($id) { global $wpdb; $this->logger->logQueryStart(); $app = Strata::app(); $configValue = (int) $app->getConfig("i18n.cache_page_size"); $cachePageSize = $configValue > 0 ? $configValue : $this->pageSize; // Don't reload the same ids, if we have already cached rows. $count = count($this->cachedIds); $notIn = $count > 0 ? " AND polyglot_ID NOT IN (" . implode(",", $this->cachedIds) . ")" : ""; $records = $wpdb->get_results($wpdb->prepare("\n SELECT *\n FROM {$wpdb->prefix}polyglot\n WHERE polyglot_ID > %d\n {$notIn}\n ORDER BY polyglot_ID\n LIMIT {$cachePageSize}", $id)); $this->logger->logQueryCompletion($wpdb->last_query); foreach ($records as $record) { $this->cache->addEntity(TranslationEntity::factory($record)); } $this->nbPageSaved++; }
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(-1); $cwd = getcwd(); // Prevent calls form our vendor directory. // The cwd should always be a project's root. if ($cwd === dirname(__FILE__)) { // Up from 'vendor/strata-mvc/strata/src/Scripts' $projectedRoot = dirname(dirname(dirname(dirname(dirname($cwd))))); if (file_exists($projectedRoot) && file_exists($projectedRoot . DIRECTORY_SEPARATOR . 'composer.json')) { $cwd = $projectedRoot; } else { echo "[ERROR] Strata could not understand it's working directory."; return; } } // Because of the way we need to be in a running Strata instance before running // the shell script, there's a global reference already available (and configured). // The only case where it does not exist is when runnign db create. if (!class_exists('Strata\\Strata')) { require_once $cwd . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php'; require_once $cwd . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'application.php'; $app = \Strata\Strata::bootstrap(\Strata\Strata::requireVendorAutoload()); $app->init(); } // Make strata understand that the server variables are being // set by WP-CLI. \Strata\Strata::app()->takeOverWPCLIArgs(); // Get and run the shell. \Strata\Shell\Shell::run();
public function __construct($loaderPath) { $app = Strata::app(); $app->setConfig('runtime.polyglot.loaderPath', $loaderPath); }
/** * Logs the names of the entities the loader is attempting * to load. */ private function logAutoloadedEntities() { $cpts = array_keys($this->getConfiguration()); $message = sprintf("Found %s custom post types : %s", count($cpts), implode(", ", $cpts)); Strata::app()->setConfig("runtime.custom_post_types", $cpts); }
/** * Sends a message to the global logger. * @param string $msg * @param string $type */ private function log($msg, $type = "<success>Router</success>") { Strata::app()->log($msg, $type); }
/** * Checks the configuration file to ensure we are expected to * force Strata' comment parser. * @return boolean */ protected function shouldParseComments() { return !(bool) Strata::app()->getConfig("security.ignore_comment_validation"); }
/** * Returns the current textdomain as defined either * from Strata's configuration or the default value. * @return string */ public function getTextdomain() { $textDomain = Strata::app()->getConfig("i18n.textdomain"); return is_null($textDomain) ? self::DOMAIN : $textDomain; }
</h3> <?php echo $error['trace']; ?> </div> <?php } ?> </div> <div class="context"> <?php if (method_exists("\\Strata\\Strata", "app")) { ?> <?php $app = Strata::app(); ?> <?php $router = Strata::router(); ?> <h3>Context</h3> <?php $controller = null; $method = strtoupper($_SERVER['REQUEST_METHOD']); if (isset($router)) { $controller = $router->getCurrentController(); $action = $router->getCurrentAction(); } ?> <p>[<?php echo $method;