示例#1
0
文件: localization.php 项目: nob/joi
 /**
  * Fetch an L10n content string
  *
  * @param $key      string  YAML key of the desired text string
  * @param $language string  Optionally override the desired language
  * @return mixed
  */
 public static function fetch($key, $language = null, $lower = false)
 {
     $app = \Slim\Slim::getInstance();
     $language = $language ? $language : Config::getCurrentLanguage();
     $value = $key;
     /*
     |--------------------------------------------------------------------------
     | Check for new language
     |--------------------------------------------------------------------------
     |
     | English is loaded by default. If requesting a language not already
     | cached, go grab it.
     |
     */
     if (!isset($app->config['_translations'][$language])) {
         $app->config['_translations'][$language] = YAML::parse(Config::getTranslation($language));
     }
     /*
     |--------------------------------------------------------------------------
     | Resolve translation
     |--------------------------------------------------------------------------
     |
     | If the set language is found and the key exists, return it. Falls back to
     | English, and then falls back to the slug-style key itself.
     |
     */
     if (array_get($app->config['_translations'][$language]['translations'], $value, false)) {
         $value = array_get($app->config['_translations'][$language]['translations'], $value);
     } else {
         $value = array_get($app->config['_translations']['en']['translations'], $value, $value);
     }
     return $lower ? strtolower($value) : $value;
 }
 /**
  * Singleton pattern.
  *
  * @throws Exceptions\DatacashRequestException
  */
 protected function __construct()
 {
     // Get the default configurations.
     $env_config = YAML::parse(file_get_contents(__DIR__ . "/../../config/environment.yaml"));
     $datacash_config = YAML::parse(file_get_contents(__DIR__ . "/../../config/datacash.yaml"));
     $datacash_config = $datacash_config[$env_config['environment']]['parameters'];
     // Set the configurations for the request.
     if (!empty($datacash_config['server_url'])) {
         $this->hostName = $datacash_config['server_url'];
     } else {
         throw new DatacashRequestException("Not set or invalid hostname.");
     }
     if (!empty($datacash_config['timeout'])) {
         $this->timeout = $datacash_config['timeout'];
     }
     if (!empty($datacash_config['datacash_network_ssl_path'])) {
         $this->sslCertPath = $datacash_config['datacash_network_ssl_path'];
         // Do not set cert SSL verifiation if we don't have a certificate.
         if (!empty($datacash_config['datacash_network_ssl_verify'])) {
             $this->sslVerify = $datacash_config['datacash_network_ssl_verify'];
         }
     } else {
         $this->sslVerify = FALSE;
     }
     // Use proxy only if proxy url is available.
     if (!empty($datacash_config['proxy_url'])) {
         $this->proxyUrl = $datacash_config['proxy_url'];
     }
 }
 /**
  * Get datacash redirect URL for payment page.
  *
  * @return string
  */
 public function getRedirectUrl()
 {
     // Get the default configurations.
     $env_config = YAML::parse(file_get_contents(__DIR__ . "/../../config/environment.yaml"));
     $datacash_config = YAML::parse(file_get_contents(__DIR__ . "/../../config/datacash.yaml"));
     $datacash_config = $datacash_config[$env_config['environment']]['parameters'];
     return $datacash_config['redirect_url'] . $this->HpsTxn->session_id->getValue();
 }
 /**
  * Sets the current environment to the given $environment
  *
  * @param string  $environment  Environment to set
  * @param array  $config  Config to set to
  * @return void
  */
 public static function set($environment, &$config)
 {
     $config['environment'] = $environment;
     $config['is_' . $environment] = true;
     $environment_config = YAML::parse("_config/environments/{$environment}.yaml");
     if (is_array($environment_config)) {
         $config = array_merge($config, $environment_config);
     }
 }
示例#5
0
 public static function fetch($form_name)
 {
     $filename = dirname(__DIR__) . '/forms/' . $form_name . '.yaml';
     if (file_exists($filename)) {
         return YAML::parse(file_get_contents($filename));
     } else {
         $error = 'missing form: ' . $filename;
         throw new Exception($error);
     }
 }
示例#6
0
文件: environment.php 项目: nob/joi
 /**
  * Sets the current environment to the given $environment
  *
  * @param string  $environment  Environment to set
  * @return void
  */
 public static function set($environment)
 {
     $app = \Slim\Slim::getInstance();
     $app->config['environment'] = $environment;
     $app->config['is_' . $environment] = TRUE;
     $environment_config = YAML::parse("_config/environments/{$environment}.yaml");
     if (is_array($environment_config)) {
         $app->config = array_merge($app->config, $environment_config);
     }
 }
 /**
  * Parse YAML data into an array
  * @param  {String}       the text to be parsed
  *
  * @return {Array}        the parsed content
  */
 public static function convertYAML($text)
 {
     try {
         $yaml = YAML::parse($text);
     } catch (ParseException $e) {
         printf("unable to parse documentation: %s..\n", $e->getMessage());
     }
     // single line of text won't throw a YAML error. returns as string
     if (gettype($yaml) == "string") {
         $yaml = array();
     }
     return $yaml;
 }
示例#8
0
 /**
  * Returns a given user's profile
  * 
  * @param string  $username  Username's profile to return
  * @return array
  */
 public static function getUserProfile($username)
 {
     if (!UserAuth::isUser($username)) {
         return null;
     }
     $content = substr(File::get(Config::getConfigPath() . "/users/" . $username . ".yaml"), 3);
     $divide = strpos($content, "\n---");
     $front_matter = trim(substr($content, 0, $divide));
     $content_raw = trim(substr($content, $divide + 4));
     $profile = YAML::parse($front_matter);
     $profile['biography_raw'] = $content_raw;
     $profile['biography'] = Content::transform($content_raw);
     $profile['username'] = $username;
     return $profile;
 }
 public function testYAMLSerializer()
 {
     $yaml_output = $this->debtAmortizatorFactory->getSerializedResult(new YAMLSerializer());
     $yamlObject = YAML::parse($yaml_output);
     // WE WILL TEST EACH AND EVERY PROPERTY OF THIS OBJECT
     // Debt principal
     $this->assertEquals("40000", $yamlObject["debtPrincipal"]);
     // Debt number of compounding periods
     $this->assertEquals("6", $yamlObject["debtNoOfCompoundingPeriods"]);
     // Debt length period
     $this->assertEquals("1", $yamlObject["debtPeriodLength"]["years"]);
     $this->assertEquals("12", $yamlObject["debtPeriodLength"]["months"]);
     $this->assertEquals("360", $yamlObject["debtPeriodLength"]["days"]);
     // Debt interest
     $this->assertEquals("0.12", $yamlObject["debtInterest"]);
     // Debt discount factor
     $this->assertEquals("0.89", $this->round2DP($yamlObject["debtDiscountFactor"]));
     // Debt duration
     $this->assertEquals("6", $yamlObject["debtDuration"]["years"]);
     $this->assertEquals("72", $yamlObject["debtDuration"]["months"]);
     $this->assertEquals("2160", $yamlObject["debtDuration"]["days"]);
     // Debt amount of single repayment
     $INDIVIDUAL_REPAYMENT = "9729.03";
     $this->assertEquals($INDIVIDUAL_REPAYMENT, $this->round2DP($yamlObject["debtSingleRepayment"]));
     // Debt repayments (principal part, interest part, total = principal part + interest part)
     $this->assertEquals("4929.03", $this->round2DP($yamlObject["debtRepayments"]["1"]["principalAmount"]));
     $this->assertEquals("4800.00", $this->round2DP($yamlObject["debtRepayments"]["1"]["interestAmount"]));
     $this->assertEquals($INDIVIDUAL_REPAYMENT, $this->round2DP($yamlObject["debtRepayments"]["1"]["totalAmount"]));
     $this->assertEquals("5520.51", $this->round2DP($yamlObject["debtRepayments"]["2"]["principalAmount"]));
     $this->assertEquals("4208.52", $this->round2DP($yamlObject["debtRepayments"]["2"]["interestAmount"]));
     $this->assertEquals($INDIVIDUAL_REPAYMENT, $this->round2DP($yamlObject["debtRepayments"]["2"]["totalAmount"]));
     $this->assertEquals("6182.97", $this->round2DP($yamlObject["debtRepayments"]["3"]["principalAmount"]));
     $this->assertEquals("3546.06", $this->round2DP($yamlObject["debtRepayments"]["3"]["interestAmount"]));
     $this->assertEquals($INDIVIDUAL_REPAYMENT, $this->round2DP($yamlObject["debtRepayments"]["3"]["totalAmount"]));
     $this->assertEquals("6924.93", $this->round2DP($yamlObject["debtRepayments"]["4"]["principalAmount"]));
     $this->assertEquals("2804.10", $this->round2DP($yamlObject["debtRepayments"]["4"]["interestAmount"]));
     $this->assertEquals($INDIVIDUAL_REPAYMENT, $this->round2DP($yamlObject["debtRepayments"]["4"]["totalAmount"]));
     $this->assertEquals("7755.92", $this->round2DP($yamlObject["debtRepayments"]["5"]["principalAmount"]));
     $this->assertEquals("1973.11", $this->round2DP($yamlObject["debtRepayments"]["5"]["interestAmount"]));
     $this->assertEquals($INDIVIDUAL_REPAYMENT, $this->round2DP($yamlObject["debtRepayments"]["5"]["totalAmount"]));
     $this->assertEquals("8686.63", $this->round2DP($yamlObject["debtRepayments"]["6"]["principalAmount"]));
     $this->assertEquals("1042.4", $this->round2DP($yamlObject["debtRepayments"]["6"]["interestAmount"]));
     $this->assertEquals($INDIVIDUAL_REPAYMENT, $this->round2DP($yamlObject["debtRepayments"]["6"]["totalAmount"]));
 }
 public function run($depth, $ext, $path, $pathName, $name)
 {
     // load default vars
     $patternTypeDash = PatternData::getPatternTypeDash();
     // should this pattern get rendered?
     $hidden = $name[0] == "_";
     // set-up the names, $name == foo.json
     $pattern = str_replace("." . $ext, "", $name);
     // foo
     $patternDash = $this->getPatternName($pattern, false);
     // foo
     $patternPartial = $patternTypeDash . "-" . $patternDash;
     // atoms-foo
     if (!$hidden) {
         $patternStoreData = array("category" => "pattern");
         $file = file_get_contents(Config::getOption("patternSourceDir") . "/" . $pathName);
         if ($ext == "json") {
             $data = json_decode($file, true);
             if ($jsonErrorMessage = JSON::hasError()) {
                 JSON::lastErrorMsg($name, $jsonErrorMessage, $data);
             }
         } else {
             try {
                 $data = YAML::parse($file);
             } catch (ParseException $e) {
                 printf("unable to parse " . $pathNameClean . ": %s..\n", $e->getMessage());
             }
             // single line of text won't throw a YAML error. returns as string
             if (gettype($data) == "string") {
                 $data = array();
             }
         }
         $patternStoreData["data"] = $data;
         // create a key for the data store
         $patternStoreKey = $patternPartial;
         // if the pattern data store already exists make sure it is merged and overwrites this data
         $patternStoreData = PatternData::checkOption($patternStoreKey) ? array_replace_recursive(PatternData::getOption($patternStoreKey), $patternStoreData) : $patternStoreData;
         PatternData::setOption($patternStoreKey, $patternStoreData);
     }
 }
 /**
  * Updates the internal content cache
  *
  * @return boolean
  */
 public static function update()
 {
     // start measuring
     $content_hash = Debug::markStart('caching', 'content');
     // track if any files have changed
     $files_changed = false;
     $settings_changed = false;
     $members_changed = false;
     // grab length of content type extension
     $content_type = Config::getContentType();
     $full_content_root = rtrim(Path::tidy(BASE_PATH . "/" . Config::getContentRoot()), "/");
     $content_type_length = strlen($content_type) + 1;
     // the cache files we'll use
     $cache_file = BASE_PATH . '/_cache/_app/content/content.php';
     $settings_file = BASE_PATH . '/_cache/_app/content/settings.php';
     $structure_file = BASE_PATH . '/_cache/_app/content/structure.php';
     $time_file = BASE_PATH . '/_cache/_app/content/last.php';
     $members_file = BASE_PATH . '/_cache/_app/members/members.php';
     $now = time();
     // start measuring settings hash
     $settings_hash = Debug::markStart('caching', 'settings');
     // check for current and new settings
     $settings = unserialize(File::get($settings_file));
     if (!is_array($settings)) {
         $settings = array('site_root' => '', 'site_url' => '', 'timezone' => '', 'date_format' => '', 'time_format' => '', 'content_type' => '', 'taxonomy' => '', 'taxonomy_case_sensitive' => '', 'taxonomy_force_lowercase' => '', 'entry_timestamps' => '', 'base_path' => '', 'app_version' => '');
     }
     // look up current settings
     $current_settings = array('site_root' => Config::getSiteRoot(), 'site_url' => Config::getSiteURL(), 'timezone' => Config::get('timezone'), 'date_format' => Config::get('date_format'), 'time_format' => Config::get('time_format'), 'content_type' => Config::get('content_type'), 'taxonomy' => Config::getTaxonomies(), 'taxonomy_case_sensitive' => Config::getTaxonomyCaseSensitive(), 'taxonomy_force_lowercase' => Config::getTaxonomyForceLowercase(), 'entry_timestamps' => Config::getEntryTimestamps(), 'base_path' => BASE_PATH, 'app_version' => STATAMIC_VERSION);
     // have cache-altering settings changed?
     if ($settings !== $current_settings) {
         // settings have changed
         $settings_changed = true;
         // clear the cache and set current settings
         $cache = self::getCleanCacheArray();
         $settings = $current_settings;
         $last = null;
     } else {
         // grab the existing cache
         $cache = unserialize(File::get($cache_file));
         if (!is_array($cache)) {
             $cache = self::getCleanCacheArray();
         }
         $last = File::get($time_file);
     }
     // mark end of settings hash measuring
     Debug::markEnd($settings_hash);
     // grab a list of all content files
     $files = File::globRecursively(Path::tidy(BASE_PATH . '/' . Config::getContentRoot() . '/*'), Config::getContentType());
     // grab a separate list of files that have changed since last check
     $updated = array();
     $current_files = array();
     // loop through files, getting local paths and checking for updated files
     foreach ($files as $file) {
         $local_file = Path::trimFilesystemFromContent(Path::standardize($file));
         // add to current files
         $current_files[] = $local_file;
         // is this updated?
         if ($last && File::getLastModified($file) >= $last) {
             $updated[] = $local_file;
         }
     }
     // get a diff of files we know about and files currently existing
     $known_files = array();
     foreach ($cache['urls'] as $url_data) {
         array_push($known_files, $url_data['path']);
     }
     $new_files = array_diff($current_files, $known_files);
     // create a master list of files that need updating
     $changed_files = array_unique(array_merge($new_files, $updated));
     // store a list of changed URLs
     $changed_urls = array();
     // add to the cache if files have been updated
     if (count($changed_files)) {
         $files_changed = true;
         // build content cache
         foreach ($changed_files as $file) {
             $file = $full_content_root . $file;
             $local_path = Path::trimFilesystemFromContent($file);
             // before cleaning anything, check for hidden or draft content
             $is_hidden = Path::isHidden($local_path);
             $is_draft = Path::isDraft($local_path);
             // now clean up the path
             $local_filename = Path::clean($local_path);
             // file parsing
             $content = substr(File::get($file), 3);
             $divide = strpos($content, "\n---");
             $front_matter = trim(substr($content, 0, $divide));
             $content_raw = trim(substr($content, $divide + 4));
             // parse data
             $data = YAML::parse($front_matter);
             if ($content_raw) {
                 $data['content'] = 'true';
                 $data['content_raw'] = 'true';
             }
             // set additional information
             $data['_file'] = $file;
             $data['_local_path'] = $local_path;
             $data['_order_key'] = null;
             $data['datetimestamp'] = null;
             // legacy
             $data['datestamp'] = null;
             $data['date'] = null;
             $data['time'] = null;
             $data['numeric'] = null;
             $data['last_modified'] = filemtime($file);
             $data['_is_hidden'] = $is_hidden;
             $data['_is_draft'] = $is_draft;
             // get initial slug (may be changed below)
             $data['slug'] = ltrim(basename($file, "." . $content_type), "_");
             // folder
             $instance = $data['slug'] == 'page' ? 1 : 0;
             $data['_folder'] = Path::clean($data['_local_path']);
             $slash = Helper::strrpos_count($data['_folder'], '/', $instance);
             $data['_folder'] = !$slash ? '' : substr($data['_folder'], 1, $slash - 1);
             $data['_folder'] = !strlen($data['_folder']) ? "/" : $data['_folder'];
             $data['_basename'] = $data['slug'] . '.' . $content_type;
             $data['_filename'] = $data['slug'];
             $data['_is_entry'] = preg_match(Pattern::ENTRY_FILEPATH, $data['_basename']);
             $data['_is_page'] = preg_match(Pattern::PAGE_FILEPATH, $data['_basename']);
             // 404 is special
             if ($data['_local_path'] === "/404.{$content_type}") {
                 $local_filename = $local_path;
                 // order key: date or datetime
             } elseif (preg_match(Pattern::DATE_OR_DATETIME, $data['_basename'], $matches)) {
                 // order key: date or datetime
                 $date = $matches[1] . '-' . $matches[2] . '-' . $matches[3];
                 $time = null;
                 if (Config::getEntryTimestamps() && isset($matches[4])) {
                     $time = substr($matches[4], 0, 2) . ":" . substr($matches[4], 2);
                     $date = $date . " " . $time;
                     $data['slug'] = substr($data['slug'], 16);
                     $data['datetimestamp'] = $data['_order_key'];
                 } else {
                     $data['slug'] = substr($data['slug'], 11);
                 }
                 $data['_order_key'] = strtotime($date);
                 $data['datestamp'] = $data['_order_key'];
                 $data['date'] = Date::format(Config::getDateFormat(), $data['_order_key']);
                 $data['time'] = $time ? Date::format(Config::getTimeFormat(), $data['_order_key']) : null;
                 // order key: slug is page, back up a level
             } elseif ($data['slug'] == 'page' && preg_match(Pattern::NUMERIC, substr($data['_local_path'], Helper::strrpos_count($data['_local_path'], '/', 1)), $matches)) {
                 // order key: slug is page, back up a level
                 $data['_order_key'] = $matches[1];
                 $data['numeric'] = $data['_order_key'];
                 // order key: numeric
             } elseif (preg_match(Pattern::NUMERIC, $data['_basename'], $matches)) {
                 // order key: numeric
                 $data['_order_key'] = $matches[1];
                 $data['numeric'] = $data['_order_key'];
                 $data['slug'] = substr($data['slug'], strlen($matches[1]) + 1);
                 // order key: other
             } else {
                 // order key: other
                 $data['_order_key'] = $data['_basename'];
             }
             // determine url
             $data['url'] = preg_replace('#/__?#', '/', $local_filename);
             // remove any content type extensions from the end of filename
             if (substr($data['url'], -$content_type_length) === '.' . $content_type) {
                 $data['url'] = substr($data['url'], 0, strlen($data['url']) - $content_type_length);
             }
             // remove any base pages from filename
             if (substr($data['url'], -5) == '/page') {
                 $data['url'] = substr($data['url'], 0, strlen($data['url']) - 5);
             }
             // add the site root
             $data['url'] = Path::tidy(Config::getSiteRoot() . $data['url']);
             // add the site URL to get the permalink
             $data['permalink'] = Path::tidy(Config::getSiteURL() . $data['url']);
             // new content
             if (!isset($cache['content'][$data['_folder']]) || !is_array($cache['content'][$data['_folder']])) {
                 $cache['content'][$data['_folder']] = array();
             }
             $slug_with_extension = $data['_filename'] == 'page' ? substr($data['url'], strrpos($data['url'], '/') + 1) . '/' . $data['_filename'] . "." . $content_type : $data['_filename'] . "." . $content_type;
             $cache['content'][$data['_folder']][$slug_with_extension] = array('folder' => $data['_folder'], 'path' => $local_path, 'file' => $slug_with_extension, 'url' => $data['url'], 'data' => $data);
             $cache['urls'][$data['url']] = array('folder' => $data['_folder'], 'path' => $local_path, 'file' => $slug_with_extension);
             $changed_urls[$data['url']] = true;
         }
     }
     // loop through all cached content for deleted files
     // this isn't as expensive as you'd think in real-world situations
     foreach ($cache['content'] as $folder => $folder_contents) {
         foreach ($folder_contents as $path => $data) {
             if (File::exists($full_content_root . $data['path'])) {
                 // still here, keep it
                 continue;
             }
             $files_changed = true;
             // get URL
             $url = isset($cache['content'][$folder][$path]['url']) ? $cache['content'][$folder][$path]['url'] : null;
             // only remove from URLs list if not in changed URLs list
             if (!isset($changed_urls[$url]) && !is_null($url)) {
                 // remove from url cache
                 unset($cache['urls'][$url]);
             }
             // remove from content cache
             unset($cache['content'][$folder][$path]);
         }
     }
     // build taxonomy cache
     // only happens if files were added, updated, or deleted above
     if ($files_changed) {
         $taxonomies = Config::getTaxonomies();
         $force_lowercase = Config::getTaxonomyForceLowercase();
         $case_sensitive = Config::getTaxonomyCaseSensitive();
         $cache['taxonomies'] = array();
         // rebuild taxonomies
         if (count($taxonomies)) {
             // set up taxonomy array
             foreach ($taxonomies as $taxonomy) {
                 $cache['taxonomies'][$taxonomy] = array();
             }
             // loop through content to build cached array
             foreach ($cache['content'] as $pages) {
                 foreach ($pages as $item) {
                     $data = $item['data'];
                     // loop through the types of taxonomies
                     foreach ($taxonomies as $taxonomy) {
                         // if this file contains this type of taxonomy
                         if (isset($data[$taxonomy])) {
                             $values = Helper::ensureArray($data[$taxonomy]);
                             // add the file name to the list of found files for a given taxonomy value
                             foreach ($values as $value) {
                                 if (!$value) {
                                     continue;
                                 }
                                 $key = !$case_sensitive ? strtolower($value) : $value;
                                 if (!isset($cache['taxonomies'][$taxonomy][$key])) {
                                     $cache['taxonomies'][$taxonomy][$key] = array('name' => $force_lowercase ? strtolower($value) : $value, 'files' => array());
                                 }
                                 array_push($cache['taxonomies'][$taxonomy][$key]['files'], $data['url']);
                             }
                         }
                     }
                 }
             }
         }
         // build structure cache
         $structure = array();
         $home = Path::tidy('/' . Config::getSiteRoot() . '/');
         foreach ($cache['content'] as $pages) {
             foreach ($pages as $item) {
                 // set up base variables
                 $parent = null;
                 // Trim off home and any /page.md ending so that all URLs are treated
                 // equally regardless of page type.
                 $order_key = str_replace('/page.md', '', str_replace($home, '', $item['path']));
                 $sub_order_key = $item['data']['_order_key'];
                 // does this have a parent (and if so, what is it?)
                 if ($item['url'] !== $home) {
                     $parent = $home;
                     $depth = substr_count(str_replace($home, '/', $item['url']), '/');
                     $last_slash = strrpos($item['url'], '/', 1);
                     $last_order_slash = strrpos($order_key, '/', 0);
                     if ($last_slash !== false) {
                         $parent = substr($item['url'], 0, $last_slash);
                     }
                     if ($last_order_slash !== false) {
                         $order_key = substr($order_key, 0, $last_order_slash);
                     }
                     if ($item['data']['_is_page']) {
                         $type = $item['data']['slug'] == 'page' ? 'folder' : 'page';
                     } else {
                         $type = 'entry';
                     }
                 } else {
                     $depth = 0;
                     $type = 'folder';
                     $order_key = $home;
                 }
                 $structure[$item['url']] = array('parent' => $parent, 'is_entry' => $item['data']['_is_entry'], 'is_page' => $item['data']['_is_page'], 'is_hidden' => $item['data']['_is_hidden'], 'is_draft' => $item['data']['_is_draft'], 'depth' => $depth, 'order_key' => $order_key ? $order_key : $sub_order_key, 'sub_order_key' => $sub_order_key, 'type' => $type);
             }
         }
     }
     // mark ending of content cache measuring
     Debug::markEnd($content_hash);
     if (!Config::get('disable_member_cache')) {
         // build member cache
         // ----------------------------------------------------------------
         // start measuring
         $member_hash = Debug::markStart('caching', 'member');
         // grab a list of existing members
         $users = File::globRecursively(Path::tidy(Config::getConfigPath() . '/users/*'), 'yaml');
         // clone for reuse, set up our list of updated users
         $updated = array();
         $current_users = array();
         foreach ($users as $user) {
             $local_file = Path::trimFilesystemFromContent(Path::standardize($user));
             // add to current users
             $current_users[] = $local_file;
             // is this updated?
             if ($last && File::getLastModified($user) >= $last) {
                 $updated[] = $local_file;
             }
         }
         // get users from the file
         $members = unserialize(File::get($members_file));
         // get a diff of users we know about and files currently existing
         $known_users = array();
         if (!empty($members)) {
             foreach ($members as $username => $member_data) {
                 $known_users[$username] = $member_data['_path'];
             }
         }
         // create a master list of users that need updating
         $changed_users = array_unique(array_merge(array_diff($current_users, $known_users), $updated));
         $removed_users = array_diff($known_users, $current_users);
         if (count($changed_users)) {
             $members_changed = true;
             foreach ($changed_users as $user_file) {
                 // file parsing
                 $last_slash = strrpos($user_file, '/') + 1;
                 $last_dot = strrpos($user_file, '.');
                 $username = substr($user_file, $last_slash, $last_dot - $last_slash);
                 $content = substr(File::get($user_file), 3);
                 $divide = strpos($content, "\n---");
                 $data = YAML::parse(trim(substr($content, 0, $divide)));
                 $bio_raw = trim(substr($content, $divide + 4));
                 $data['_path'] = $user_file;
                 if ($bio_raw) {
                     $data['biography'] = 'true';
                     $data['biography_raw'] = 'true';
                 }
                 $members[$username] = $data;
             }
         }
         // loop through all cached content for deleted files
         // this isn't as expensive as you'd think in real-world situations
         if (!empty($removed_users)) {
             $members_changed = true;
             $members = array_diff_key($members, $removed_users);
         }
         // mark ending of member cache measuring
         Debug::markEnd($member_hash);
     }
     // write to caches
     // --------------------------------------------------------------------
     // add file-writing to content-cache actions
     $content_hash = Debug::markStart('caching', 'content');
     if ($files_changed) {
         // store the content cache
         if (File::put($cache_file, serialize($cache)) === false) {
             if (!File::isWritable($cache_file)) {
                 Log::fatal('Cache folder is not writable.', 'core', 'content-cache');
             }
             Log::fatal('Could not write to the cache.', 'core', 'content-cache');
             return false;
         }
         // store the structure cache
         if (File::put($structure_file, serialize($structure)) === false) {
             if (!File::isWritable($structure_file)) {
                 Log::fatal('Structure cache file is not writable.', 'core', 'structure-cache');
             }
             Log::fatal('Could not write to the structure cache.', 'core', 'structure-cache');
             return false;
         }
     }
     // mark ending of content cache file write measuring
     Debug::markEnd($content_hash);
     // add file-writing to settings-cache actions
     $settings_hash = Debug::markStart('caching', 'settings');
     // store the settings cache
     if ($settings_changed) {
         if (File::put($settings_file, serialize($settings)) === false) {
             if (!File::isWritable($settings_file)) {
                 Log::fatal('Settings cache file is not writable.', 'core', 'settings-cache');
             }
             Log::fatal('Could not write to the settings cache file.', 'core', 'settings-cache');
             return false;
         }
     }
     // mark ending of settings cache file write measuring
     Debug::markEnd($settings_hash);
     if (!Config::get('disable_member_cache')) {
         // add file-writing to settings-cache actions
         $member_hash = Debug::markStart('caching', 'member');
         // store the members cache
         if ($members_changed) {
             if (File::put($members_file, serialize($members)) === false) {
                 if (!File::isWritable($members_file)) {
                     Log::fatal('Member cache file is not writable.', 'core', 'member-cache');
                 }
                 Log::fatal('Could not write to the member cache file.', 'core', 'member-cache');
                 return false;
             }
         }
         // mark ending of member cache file write measuring
         Debug::markEnd($member_hash);
     }
     File::put($time_file, $now - 1);
     return true;
 }
 private function loadProfile($profile)
 {
     $profile_file = "./profiles/{$profile}.yml";
     if (file_exists($profile_file)) {
         $data = YAML::parse(file_get_contents($profile_file));
         if (isset($data['pct'])) {
             foreach ($data['pct'] as $var => $val) {
                 $this->{$var} = $val;
             }
         }
         if (isset($data['files'])) {
             foreach ($data['files'] as $var => $val) {
                 $this->{$var} = $val;
             }
         }
         if (isset($data['addBaseUrls']) && $data['addBaseUrls'] === FALSE) {
             $this->addBaseUrls = FALSE;
         }
         // Load geo data.
         if (isset($this->geoFile) && file_exists($this->geoFile)) {
             $this->loadGeo();
         }
         // Load cat data.
         if (isset($this->catFile) && file_exists($this->catFile)) {
             $this->loadCat();
         }
         // Load SPs.
         if (isset($this->spsFile) && file_exists($this->spsFile)) {
             $this->loadSps();
         }
     } else {
         throw new Exception('Profile not found.');
     }
 }
示例#13
0
use DMS\Service\Meetup\MeetupKeyAuthClient;
use Symfony\Component\Yaml\Yaml;
use Neoxygen\NeoClient\ClientBuilder;
$skipSchemaSetup = false;
$dropDbOnInit = false;
if (!isset($argv[1]) || empty($argv[1])) {
    throw new \InvalidArgumentException('You need to pass the event ID as argument : php import.php 12345678');
}
if (isset($argv[2]) && true == (bool) $argv[2]) {
    $skipSchemaSetup = true;
}
if (isset($argv[3]) && (bool) $argv[3] == true) {
    $dropDbOnInit = true;
}
$eventId = (int) $argv[1];
$config = YAML::parse(file_get_contents(__DIR__ . '/config.yml'));
$meetupClient = MeetupKeyAuthClient::factory(array('key' => $config['meetup_api_key']));
$neoClient = ClientBuilder::create()->addConnection('default', $config['neo4j_scheme'], $config['neo4j_host'], $config['neo4j_port'], true, $config['neo4j_user'], $config['neo4j_password'])->setAutoFormatResponse(true)->build();
// Creating Schema Indexes And Constraints
if (!$skipSchemaSetup) {
    $neoClient->createUniqueConstraint('Event', 'id');
    $neoClient->createUniqueConstraint('Member', 'id');
    $neoClient->createUniqueConstraint('Topic', 'id');
    $neoClient->createUniqueConstraint('Country', 'code');
    $neoClient->createIndex('City', 'name');
    echo 'Schema created' . "\n";
} else {
    echo 'Skipping Schema Creation' . "\n";
}
if ($dropDbOnInit) {
    echo 'Dropping DB' . "\n";
 /**
  * Loads a Member's profile
  * 
  * @param string  $username  username to load data for
  * @return array
  * @throws Exception
  */
 private static function loadMemberData($username)
 {
     // pull profile data from filesystem
     $file = Config::getConfigPath() . '/users/' . $username . '.yaml';
     $raw_profile = substr(File::get($file), 3);
     // no profile found, throw an exception
     if (!$raw_profile) {
         throw new Exception('Member `' . $username . '` not found.');
     }
     // split out the profile into parts
     $divide = strpos($raw_profile, "\n---");
     $front_matter = trim(substr($raw_profile, 0, $divide));
     $content_raw = trim(substr($raw_profile, $divide + 4));
     // create data array for populating into the Member object
     $data = YAML::parse($front_matter);
     $data['biography_raw'] = $content_raw;
     $data['biography'] = Content::transform($content_raw);
     $data['username'] = $username;
     // return the Member data
     return $data;
 }
 public static function nav_count()
 {
     $default_config = YAML::parse(Config::getAppConfigPath() . '/default.settings.yaml');
     $admin_nav = array_merge($default_config['_admin_nav'], Config::get('_admin_nav', array()));
     return count(array_filter($admin_nav, 'strlen'));
 }
示例#16
0
文件: Data.php 项目: hutchike/YAWF
 /**
  * Decode the YAML type and return data
  *
  * @param String $text the text to decode
  * @return Array the decoded data as an assoc array
  */
 public static function from_yaml($text)
 {
     load_tool('YAML');
     return YAML::parse($text);
 }
示例#17
0
 public function render()
 {
     $field_data = $this->field_data;
     /*
     |--------------------------------------------------------------------------
     | Multi-select
     |--------------------------------------------------------------------------
     |
     | We need to set an empty array brace [] and add the "multiple" attribute
     | in the event we want to allow multi-selects. We also change the
     | plurality of the placeholder content.
     |
     */
     $max_items = array_get($this->field_config, 'max_items', 'null');
     $force_list = array_get($this->field_config, 'force_list', false);
     $multiple = array_get($this->field_config, 'multiple', true);
     $allow_blank = array_get($this->field_config, 'allow_blank', false);
     $placeholder = array_get($this->field_config, 'placeholder', false);
     if ($max_items === 1 && !$force_list) {
         $multiple = false;
     }
     $multiple_array_holder = $multiple ? '[]' : '';
     $multiple_string = $multiple ? "multiple='multiple'" : '';
     $placeholder_string = $placeholder ? "placeholder='{$placeholder}'" : '';
     $suggestions = array();
     /*
     |--------------------------------------------------------------------------
     | Getting the Array from either library page
     |--------------------------------------------------------------------------
     |
     | Fetch an associative array (grid-style) from the library. If world data are requested, we ask for the language (locale).
     |
     */
     $field = $this->field_config['region'];
     $locale = $this->field_config['locale'];
     $key = $this->field_config['key'];
     $content = array();
     if ($field == 'world') {
         $content = YAML::parse('_config/add-ons/regionalize/world-library.md');
         $values = array_get($content, $locale);
     } else {
         $content = YAML::parse('_config/add-ons/regionalize/states-library.md');
         $values = array_get($content, $field);
     }
     $vs = array();
     foreach ($values as $k => $v) {
         $vs[] = array_get($v, $key);
     }
     $values = $vs;
     $suggestions = array_merge($suggestions, $values);
     /*
     |--------------------------------------------------------------------------
     | Input HTML
     |--------------------------------------------------------------------------
     |
     | Generate the HTML for the select field. A single, blank option is
     | needed if allow blank is true.
     |
     */
     if ($max_items === null && $multiple === false) {
         $max_items = 1;
     }
     $options = json_encode(array('sortField' => 'text', 'maxItems' => $max_items, 'delimiter' => ',', 'create' => array_get($this->field_config, 'create', false), 'persist' => array_get($this->field_config, 'persist', true), 'hideSelected' => array_get($this->field_config, 'hide_selected', true), 'sortDirection' => array_get($this->field_config, 'sort_dir', 'asc'), 'plugins' => array('drag_drop'), 'dropdownParent' => 'body'));
     $required_str = $this->is_required ? 'required' : '';
     $html = "<div id='{$this->field_id}' class='suggest-field-container' data-config='{$options}'>";
     $html .= "<select {$required_str} name='{$this->fieldname}{$multiple_array_holder}' tabindex='{$this->tabindex}' {$multiple_string} {$placeholder_string} class='suggest'>\n";
     $is_indexed = array_values($suggestions) === $suggestions;
     // Preserve existing data's order
     if (is_array($field_data)) {
         $field_data = array_combine($field_data, $field_data);
         $suggestions = array_merge($field_data, $suggestions);
     }
     if ($allow_blank) {
         $html .= "<option value=''></option>\n";
     }
     foreach ($suggestions as $value => $label) {
         $value = $is_indexed ? $label : $value;
         #allows setting custom values and labels
         if ($multiple && is_array($field_data)) {
             $selected = in_array($value, $field_data, true) ? " selected " : '';
         } else {
             $selected = $field_data == $value ? " selected " : '';
         }
         $html .= '<option value="' . $value . '" ' . $selected . '>' . $label . '</option>';
     }
     $html .= "</select>";
     $html .= "<div class='count-placeholder'></div></div>";
     $html .= "<script>\$('#{$this->field_id}').statamicSuggest();</script>";
     return $html;
 }
 public function run($depth, $ext, $path, $pathName, $name)
 {
     // load default vars
     $patternSubtype = PatternData::getPatternSubtype();
     $patternSubtypeClean = PatternData::getPatternSubtypeClean();
     $patternSubtypeDash = PatternData::getPatternSubtypeDash();
     $patternType = PatternData::getPatternType();
     $patternTypeClean = PatternData::getPatternTypeClean();
     $patternTypeDash = PatternData::getPatternTypeDash();
     $dirSep = PatternData::getDirSep();
     $frontMeta = PatternData::getFrontMeta();
     // should this pattern get rendered?
     $hidden = $name[0] == "_";
     $noviewall = $name[0] == "-";
     // set-up the names
     $patternFull = in_array($name[0], $frontMeta) ? substr($name, 1) : $name;
     // 00-colors~foo.mustache
     $patternState = "";
     // check for pattern state
     if (strpos($patternFull, "@") !== false) {
         $patternBits = explode("@", $patternFull, 2);
         $patternState = str_replace("." . $ext, "", $patternBits[1]);
         $patternFull = preg_replace("/@(.*?)\\./", ".", $patternFull);
     }
     // finish setting up vars
     $patternBits = explode("~", $patternFull);
     $patternBase = $patternBits[0] . "." . Config::getOption("patternExtension");
     // 00-homepage.mustache
     $patternBaseDash = $this->getPatternName($patternBits[0], false);
     // homepage
     $patternBaseOrig = $patternTypeDash . "-" . $patternBaseDash;
     // pages-homepage
     $patternBaseData = $patternBits[0] . "." . $ext;
     // 00-homepage.json
     $stripJSON = str_replace("." . $ext, "", $patternBits[1]);
     $patternBitClean = preg_replace("/@(.*?)/", "", $patternBits[0]);
     $pattern = $patternBitClean . "-" . $stripJSON;
     // 00-homepage-00-emergency
     $patternInt = $patternBitClean . "-" . $this->getPatternName($stripJSON, false);
     // 00-homepage-emergency
     $patternDash = $this->getPatternName($patternInt, false);
     // homepage-emergency
     $patternClean = str_replace("-", " ", $patternDash);
     // homepage emergency
     $patternPartial = $patternTypeDash . "-" . $patternDash;
     // pages-homepage-emergency
     $patternPath = str_replace("." . $ext, "", str_replace("~", "-", $pathName));
     // 00-atoms/01-global/00-colors
     $patternPathDash = str_replace($dirSep, "-", $patternPath);
     // 00-atoms-01-global-00-colors (file path)
     // check the original pattern path. if it doesn't exist make a guess
     $patternPathOrig = PatternData::getPatternOption($patternBaseOrig, "pathName");
     // 04-pages/00-homepage
     $patternPathOrigDash = PatternData::getPatternOption($patternBaseOrig, "pathDash");
     // 04-pages-00-homepage
     if (!$patternPathOrig) {
         $patternPathOrigBits = explode("~", $pathName);
         $patternPathOrig = $patternPathOrigBits[0];
         // 04-pages/00-homepage
         $patternPathOrigDash = str_replace($dirSep, "-", $patternPathOrig);
         // 04-pages-00-homepage
     }
     // create a key for the data store
     $patternStoreKey = $patternPartial;
     // collect the data
     $patternStoreData = array("category" => "pattern", "name" => $pattern, "partial" => $patternPartial, "nameDash" => $patternDash, "nameClean" => $patternClean, "type" => $patternType, "typeDash" => $patternTypeDash, "breadcrumb" => array("patternType" => $patternTypeClean), "state" => $patternState, "hidden" => $hidden, "noviewall" => $noviewall, "depth" => $depth, "ext" => $ext, "path" => $path, "pathName" => $patternPath, "pathDash" => $patternPathDash, "isDir" => $this->isDirProp, "isFile" => $this->isFileProp, "pseudo" => true, "original" => $patternBaseOrig, "pathOrig" => $patternPathOrig, "pathOrigDash" => $patternPathOrigDash);
     // add any subtype info if necessary
     if ($depth > 1) {
         $patternStoreData["subtype"] = $patternSubtype;
         $patternStoreData["subtypeDash"] = $patternSubtypeDash;
         $patternStoreData["breadcrumb"] = array("patternType" => $patternTypeClean, "patternSubtype" => $patternSubtypeClean);
     }
     $patternDataBase = array();
     if (file_exists(Config::getOption("patternSourceDir") . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $patternBaseData)) {
         $data = file_get_contents(Config::getOption("patternSourceDir") . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $patternBaseData);
         if ($ext == "json") {
             $patternDataBase = json_decode($data, true);
             if ($jsonErrorMessage = JSON::hasError()) {
                 JSON::lastErrorMsg($patternBaseJSON, $jsonErrorMessage, $data);
             }
         } else {
             try {
                 $patternDataBase = YAML::parse($data);
             } catch (ParseException $e) {
                 printf("unable to parse " . $pathNameClean . ": %s..\n", $e->getMessage());
             }
             // single line of text won't throw a YAML error. returns as string
             if (gettype($patternDataBase) == "string") {
                 $patternDataBase = array();
             }
         }
     }
     // get the data for the pseudo-pattern
     $data = file_get_contents(Config::getOption("patternSourceDir") . DIRECTORY_SEPARATOR . $pathName);
     if ($ext == "json") {
         $patternData = json_decode($data, true);
         if ($jsonErrorMessage = JSON::hasError()) {
             JSON::lastErrorMsg($name, $jsonErrorMessage, $data);
         }
     } else {
         try {
             $patternData = YAML::parse($data);
         } catch (ParseException $e) {
             printf("unable to parse " . $pathNameClean . ": %s..\n", $e->getMessage());
         }
         // single line of text won't throw a YAML error. returns as string
         if (gettype($patternData) == "string") {
             $patternData = array();
         }
     }
     // make sure the pattern data is an array before merging the data
     $patternStoreData["data"] = is_array($patternData) ? array_replace_recursive($patternDataBase, $patternData) : $patternDataBase;
     // if the pattern data store already exists make sure it is merged and overwrites this data
     $patternStoreData = PatternData::checkOption($patternStoreKey) ? array_replace_recursive(PatternData::getOption($patternStoreKey), $patternStoreData) : $patternStoreData;
     PatternData::setOption($patternStoreKey, $patternStoreData);
 }
示例#19
0
 public static function yamlize_content($meta_raw, $content_key = 'content')
 {
     if (File::exists($meta_raw)) {
         $meta_raw = File::get($meta_raw);
     }
     if (Pattern::endsWith($meta_raw, "---")) {
         $meta_raw .= "\n";
         # prevent parse failure
     }
     // Parse YAML Front Matter
     if (strpos($meta_raw, "---") === false) {
         $meta = YAML::parse($meta_raw);
         $meta['content'] = "";
     } else {
         list($yaml, $content) = preg_split("/---/", $meta_raw, 2, PREG_SPLIT_NO_EMPTY);
         $meta = YAML::parse($yaml);
         $meta[$content_key . '_raw'] = trim($content);
         $meta[$content_key] = Content::transform($content);
         return $meta;
     }
 }
示例#20
0
文件: addon.php 项目: nob/joi
 /**
  * Gets a file from this plugin's namespaced cache and parses it as YAML
  *
  * @param string  $filename  Name of file to get
  * @param mixed  $default  Default value to return if no file is found, or file is not YAML-parsable
  * @return mixed
  */
 public function getYAML($filename, $default = null)
 {
     $data = $this->get($filename);
     if (!is_null($data)) {
         return YAML::parse($data);
     }
     return $default;
 }
示例#21
0
 doStatamicVersionCheck($admin_app);
 $data = array();
 if (!Statamic::are_users_writable()) {
     $url = $admin_app->urlFor('error') . "?code=users_not_writable";
     $admin_app->redirect($url);
 }
 $name = Session::getFlash('member_is_new', filter_input(INPUT_GET, 'name', FILTER_SANITIZE_STRING));
 $new = Session::getFlash('member_is_new', filter_input(INPUT_GET, 'new', FILTER_SANITIZE_NUMBER_INT));
 $original_name = $name;
 if ($new) {
     $data['status_message'] = Localization::fetch('creating_member');
 } else {
     $data = Member::getProfile($name, array('password'));
     $data['status_message'] = Localization::fetch('editing_member');
 }
 $data['fields'] = YAML::parse(Config::getConfigPath() . '/bundles/member/fields.yaml');
 $data['original_name'] = $original_name;
 $data['full_name'] = array_get($data, 'first_name', $name) . ' ' . array_get($data, 'last_name', '');
 // overwrite 'biography' as it needs to be 'biography_raw' here
 if (isset($data['fields']['fields']['biography'])) {
     $data['fields']['fields']['biography_raw'] = $data['fields']['fields']['biography'];
     unset($data['fields']['fields']['biography']);
 }
 $template_list = array("member");
 // check for flash data
 $errors = Session::getFlash('member_errors', array());
 $old_values = Session::getFlash('member_old_values', array());
 // merge
 $data = $old_values + $data + array('_errors' => $errors, 'new' => $new);
 Statamic_View::set_templates(array_reverse($template_list));
 $admin_app->render(null, array('route' => 'members', 'app' => $admin_app) + $data);
示例#22
0
 /**
  * Create the data for a piece of content
  *
  * @param  array $data  The cache data
  * @return array        The data for the content to be added to the migration
  */
 private function createData($data)
 {
     $file = $data['_file'];
     // Get and parse the file for YAML and content
     $content = substr(File::get($file), 3);
     $divide = strpos($content, "\n---");
     $front_matter = trim(substr($content, 0, $divide));
     $content_raw = trim(substr($content, $divide + 4));
     $yaml = YAML::parse($front_matter);
     // We want the content in `content`, please.
     $yaml['content'] = $content_raw;
     $yaml = $this->removeUnderscores($yaml);
     return $yaml;
 }
示例#23
0
 /**
  * Import (merge) values from a yaml file.
  *
  * @param string $yamlString
  * @param string $key
  *
  * @return array
  * @throws \InvalidArgumentException
  *
  * @throws ParseException
  */
 public function importYAML($yamlString, $key = '')
 {
     $yamlString = $this->getValue($yamlString);
     $import = YAML::parse($yamlString);
     return $this->importValue($import, $key);
 }
示例#24
0
文件: parse.php 项目: nob/joi
 /**
  * Parse a block of YAML into PHP
  *
  * @param string  $yaml  YAML-formatted string to parse
  * @return array
  */
 public static function yaml($yaml)
 {
     return YAML::parse($yaml);
 }
示例#25
0
 /**
  * Generate the listItems array
  * @param  {String}       the filename for the pattern to be parsed
  * @param  {String}       the extension so that a flag switch can be used to parse data
  *
  * @return {Array}        the final set of list items
  */
 public static function getListItems($filepath, $ext = "json")
 {
     // set-up the dispatcher
     $dispatcherInstance = Dispatcher::getInstance();
     // dispatch that the data gather has started
     $dispatcherInstance->dispatch("data.getListItemsStart");
     // default vars
     $sourceDir = Config::getOption("sourceDir");
     $listItems = array();
     $listItemsData = array();
     // add list item data, makes 'listItems' a reserved word
     if (file_exists($sourceDir . "/" . $filepath)) {
         $file = file_get_contents($sourceDir . "/" . $filepath);
         if ($ext == "json") {
             $listItemsData = json_decode($file, true);
             if ($jsonErrorMessage = JSON::hasError()) {
                 JSON::lastErrorMsg($filepath, $jsonErrorMessage, $listItems);
             }
         } else {
             try {
                 $listItemsData = YAML::parse($file);
             } catch (ParseException $e) {
                 printf("unable to parse " . $pathNameClean . ": %s..\n", $e->getMessage());
             }
             // single line of text won't throw a YAML error. returns as string
             if (gettype($listItemsData) == "string") {
                 $listItemsData = array();
             }
         }
         $numbers = array("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve");
         $i = 0;
         $k = 1;
         $c = count($listItemsData) + 1;
         while ($k < $c) {
             shuffle($listItemsData);
             $itemsArray = array();
             while ($i < $k) {
                 $itemsArray[] = $listItemsData[$i];
                 $i++;
             }
             $listItems[$numbers[$k - 1]] = $itemsArray;
             $i = 0;
             $k++;
         }
     }
     $dispatcherInstance->dispatch("data.getListItemsEnd");
     return $listItems;
 }
示例#26
0
文件: cache.php 项目: nob/joi
 /**
  * Updates the internal content cache
  *
  * @return boolean
  */
 public static function update()
 {
     // track if any files have changed
     $files_changed = false;
     // grab length of content type extension
     $content_type = Config::getContentType();
     $full_content_root = rtrim(Path::tidy(BASE_PATH . "/" . Config::getContentRoot()), "/");
     $content_type_length = strlen($content_type) + 1;
     // the cache file we'll use
     $cache_file = BASE_PATH . "/_cache/_app/content/content.php";
     $time_file = BASE_PATH . "/_cache/_app/content/last.php";
     $now = time();
     // grab the existing cache
     $cache = unserialize(File::get($cache_file));
     if (!is_array($cache)) {
         $cache = array("urls" => array(), "content" => array(), "taxonomies" => array());
     }
     $last = File::get($time_file);
     // grab a list of all files
     $finder = new Finder();
     $files = $finder->files()->name("*." . Config::getContentType())->in(Config::getContentRoot());
     // grab a separate list of files that have changed since last check
     $updated_files = clone $files;
     $updated = array();
     if ($last) {
         $updated_files->date(">= " . Date::format("Y-m-d H:i:s", $last));
         foreach ($updated_files as $file) {
             // we don't want directories, they may show up as being modified
             // if a file inside them has changed or been renamed
             if (is_dir($file)) {
                 continue;
             }
             // this isn't a directory, add it to the list
             $updated[] = Path::trimFilesystem(Path::standardize($file->getRealPath()));
         }
     }
     // loop over current files
     $current_files = array();
     foreach ($files as $file) {
         $current_files[] = Path::trimFilesystem(Path::standardize($file->getRealPath()));
     }
     // get a diff of files we know about and files currently existing
     $new_files = array_diff($current_files, $cache['urls']);
     // create a master list of files that need updating
     $changed_files = array_unique(array_merge($new_files, $updated));
     // add to the cache if files have been updated
     if (count($changed_files)) {
         $files_changed = true;
         // build content cache
         foreach ($changed_files as $file) {
             $file = $full_content_root . $file;
             $local_path = Path::trimFilesystem($file);
             $local_filename = Path::clean($local_path);
             // file parsing
             $content = substr(File::get($file), 3);
             $divide = strpos($content, "\n---");
             $front_matter = trim(substr($content, 0, $divide));
             // parse data
             $data = YAML::parse($front_matter);
             // set additional information
             $data['_file'] = $file;
             $data['_local_path'] = $local_path;
             $data['_order_key'] = null;
             $data['datetimestamp'] = null;
             // legacy
             $data['datestamp'] = null;
             $data['date'] = null;
             $data['time'] = null;
             $data['numeric'] = null;
             $data['last_modified'] = filemtime($file);
             $data['_is_hidden'] = false;
             $data['_is_draft'] = false;
             // folder
             $data['_folder'] = preg_replace(Pattern::ORDER_KEY, "", str_replace($full_content_root, "", $data['_file']));
             $slash = strrpos($data['_folder'], "/");
             $data['_folder'] = $slash === 0 ? "" : substr($data['_folder'], 1, $slash - 1);
             // fix hidden/draft files
             $slug = basename($file, "." . $content_type);
             if (substr($slug, 0, 2) === "__") {
                 $data['_is_hidden'] = true;
                 $data['slug'] = substr($slug, 2);
             } elseif (substr($slug, 0, 1) === "_") {
                 $data['_is_draft'] = true;
                 $data['slug'] = substr($slug, 1);
             } else {
                 $data['slug'] = $slug;
             }
             $data['_basename'] = $data['slug'] . "." . $content_type;
             $data['_filename'] = $data['slug'];
             $data['_is_entry'] = preg_match(Pattern::ENTRY_FILEPATH, $data['_basename']);
             $data['_is_page'] = preg_match(Pattern::PAGE_FILEPATH, $data['_basename']);
             // 404 is special
             if ($data['_local_path'] === "/404.{$content_type}") {
                 $local_filename = $local_path;
                 // order key
             } elseif (preg_match(Pattern::DATE_OR_DATETIME, $data['_basename'], $matches)) {
                 $date = $matches[1] . '-' . $matches[2] . '-' . $matches[3];
                 $time = NULL;
                 if (isset($matches[4])) {
                     $time = substr($matches[4], 0, 2) . ":" . substr($matches[4], 2);
                     $date = $date . " " . $time;
                     $data['slug'] = substr($data['slug'], 16);
                     $data['datetimestamp'] = $data['_order_key'];
                 } else {
                     $data['slug'] = substr($data['slug'], 11);
                 }
                 $data['_order_key'] = strtotime($date);
                 $data['datestamp'] = $data['_order_key'];
                 $data['date'] = Date::format(Config::getDateFormat(), $data['_order_key']);
                 $data['time'] = $time ? Date::format(Config::getTimeFormat(), $data['_order_key']) : NULL;
             } elseif (preg_match(Pattern::NUMERIC, $data['_basename'], $matches)) {
                 $data['_order_key'] = $matches[1];
                 $data['numeric'] = $data['_order_key'];
                 $data['slug'] = substr($data['slug'], strlen($matches[1]) + 1);
             } else {
                 $data['_order_key'] = $data['_basename'];
             }
             // determine url
             $data['url'] = preg_replace("/\\/__?/", "/", $local_filename);
             // remove any content type extensions from the end of filename
             if (substr($data['url'], -$content_type_length) === "." . $content_type) {
                 $data['url'] = substr($data['url'], 0, strlen($data['url']) - $content_type_length);
             }
             // remove any base pages from filename
             if (substr($data['url'], -5) == "/page") {
                 $data['url'] = substr($data['url'], 0, strlen($data['url']) - 5);
             }
             // add the site root
             $data['url'] = Path::tidy(Config::getSiteRoot() . $data['url']);
             // add the site URL to get the permalink
             $data['permalink'] = Path::tidy(Config::getSiteURL() . $data['url']);
             // add to cache file
             $cache['content'][$local_path] = $data;
             $cache['urls'][$data['url']] = $local_path;
         }
     }
     // loop through all cached content for deleted files
     // this isn't as expensive as you'd think in real-world situations
     foreach ($cache['content'] as $local_path => $data) {
         if (File::exists($full_content_root . $local_path)) {
             continue;
         }
         $files_changed = TRUE;
         // remove from content cache
         unset($cache['content'][$local_path]);
         // remove from url cache
         $url = array_search($local_path, $cache['urls']);
         if ($url !== FALSE) {
             unset($cache['urls'][$url]);
         }
     }
     // build taxonomy cache
     // only happens if files were added, updated, or deleted above
     if ($files_changed) {
         $taxonomies = Config::getTaxonomies();
         $force_lowercase = Config::getTaxonomyForceLowercase();
         $case_sensitive = Config::getTaxonomyCaseSensitive();
         $cache['taxonomies'] = array();
         if (count($taxonomies)) {
             // set up taxonomy array
             foreach ($taxonomies as $taxonomy) {
                 $cache['taxonomies'][$taxonomy] = array();
             }
             // loop through content to build cached array
             foreach ($cache['content'] as $file => $data) {
                 // do not grab anything not public
                 if (array_get($data, '_is_hidden', FALSE) || array_get($data, '_is_draft', FALSE)) {
                     continue;
                 }
                 // loop through the types of taxonomies
                 foreach ($taxonomies as $taxonomy) {
                     // if this file contains this type of taxonomy
                     if (isset($data[$taxonomy])) {
                         $values = Helper::ensureArray($data[$taxonomy]);
                         // add the file name to the list of found files for a given taxonomy value
                         foreach ($values as $value) {
                             if (!$value) {
                                 continue;
                             }
                             $key = !$case_sensitive ? strtolower($value) : $value;
                             if (!isset($cache['taxonomies'][$taxonomy][$key])) {
                                 $cache['taxonomies'][$taxonomy][$key] = array("name" => $force_lowercase ? strtolower($value) : $value, "files" => array());
                             }
                             array_push($cache['taxonomies'][$taxonomy][$key]['files'], $data['url']);
                         }
                     }
                 }
             }
         }
         if (File::put($cache_file, serialize($cache)) === false) {
             if (!File::isWritable($cache_file)) {
                 Log::fatal("Cache folder is not writable.", "core", "content-cache");
             }
             Log::fatal("Could not write to the cache.", "core", "content-cache");
             return false;
         }
     }
     File::put($time_file, $now);
     return true;
 }
示例#27
0
    /**
     * Gets a file from this plugin's namespaced storage and parses it as YAML
     *
     * @param string  $filename  Name of file to get
     * @param mixed  $default  Default value to return if no file is found, or file is not YAML-parsable
     * @return mixed
     */
    public function getYAML($filename, $default=null)
    {
        $this->verifyStorageFolder();
        $data = $this->get($filename);

        if (!is_null($data)) {
            return YAML::parse($data);
        }

        return $default;
    }