makeSafe() public static method

Returns a "safe" version of the given string - basically only US-ASCII and numbers. Needed because filenames and titles and such, can't use all characters.
public static makeSafe ( string $str, boolean $strict = false, string $extrachars = '' ) : string
$str string
$strict boolean
$extrachars string
return string
 public function testMakeSafe()
 {
     // basic
     $input = "this is a ƃuıɹʇs ʇsǝʇ";
     $this->assertEquals("this is a uis s", Str::makeSafe($input));
     //strict
     $input = ";this is a ƃuıɹʇs ʇsǝʇ";
     $this->assertEquals("this-is-a-uis-s", Str::makeSafe($input, true));
     // extra chars
     $input = ";this is a ƃuıɹʇs ʇsǝʇ";
     $this->assertEquals(";this-is-a-uis-s", Str::makeSafe($input, true, ';'));
     // German
     $input = "Ich lässt öfter mit Vätern in einer kleinen Straße";
     $this->assertEquals("ich-laesst-oefter-mit-vaetern-in-einer-kleinen-strasse", Str::makeSafe($input, true, ';'));
     // French
     $input = "Et le proxénète s'est avancé à la barre";
     $this->assertEquals("et-le-proxenete-sest-avance-a-la-barre", Str::makeSafe($input, true, ';'));
     // Swedish
     $input = "Skämt åsido satan vilket uruselt tillvägagångsätt";
     $this->assertEquals("skaemt-aasido-satan-vilket-uruselt-tillvaegagaangsaett", Str::makeSafe($input, true, ';'));
 }
Esempio n. 2
0
 /**
  * Return a 'safe string' version of a given string.
  *
  * @see function Bolt\Library::safeString()
  *
  * @param string  $str
  * @param boolean $strict
  * @param string  $extrachars
  *
  * @return string
  */
 public function safeString($str, $strict = false, $extrachars = '')
 {
     return Str::makeSafe($str, $strict, $extrachars);
 }
Esempio n. 3
0
 /**
  * Parse a Contenttype's filed and determine the grouping
  *
  * @param array $fields
  * @param array $generalConfig
  *
  * @return array
  */
 protected function parseFieldsAndGroups(array $fields, array $generalConfig)
 {
     $acceptableFileTypes = $generalConfig['accept_file_types'];
     $currentGroup = 'ungrouped';
     $groups = [];
     $hasGroups = false;
     foreach ($fields as $key => $field) {
         unset($fields[$key]);
         $key = str_replace('-', '_', strtolower(Str::makeSafe($key, true)));
         // If field is a "file" type, make sure the 'extensions' are set, and it's an array.
         if ($field['type'] == 'file' || $field['type'] == 'filelist') {
             if (empty($field['extensions'])) {
                 $field['extensions'] = $acceptableFileTypes;
             }
             $field['extensions'] = (array) $field['extensions'];
         }
         // If field is an "image" type, make sure the 'extensions' are set, and it's an array.
         if ($field['type'] == 'image' || $field['type'] == 'imagelist') {
             if (empty($field['extensions'])) {
                 $field['extensions'] = array_intersect(['gif', 'jpg', 'jpeg', 'png'], $acceptableFileTypes);
             }
             $field['extensions'] = (array) $field['extensions'];
         }
         // Make indexed arrays into associative for select fields
         // e.g.: [ 'yes', 'no' ] => { 'yes': 'yes', 'no': 'no' }
         if ($field['type'] === 'select' && isset($field['values']) && is_array($field['values']) && Arr::isIndexedArray($field['values'])) {
             $field['values'] = array_combine($field['values'], $field['values']);
         }
         if (!empty($field['group'])) {
             $hasGroups = true;
         }
         // Make sure we have these keys and every field has a group set.
         $field = array_replace(['class' => '', 'default' => '', 'group' => $currentGroup, 'label' => '', 'variant' => ''], $field);
         // Collect group data for rendering.
         // Make sure that once you started with group all following have that group, too.
         $currentGroup = $field['group'];
         $groups[$currentGroup] = 1;
         $fields[$key] = $field;
         // Repeating fields checks
         if ($field['type'] === 'repeater') {
             $fields[$key] = $this->parseFieldRepeaters($fields, $key);
             if ($fields[$key] === null) {
                 unset($fields[$key]);
             }
         }
     }
     // Make sure the 'uses' of the slug is an array.
     if (isset($fields['slug']) && isset($fields['slug']['uses'])) {
         $fields['slug']['uses'] = (array) $fields['slug']['uses'];
     }
     return [$fields, $hasGroups ? array_keys($groups) : []];
 }
Esempio n. 4
0
 /**
  * Get the parameter for the 'order by' part of a query.
  *
  * This is tightly coupled to $this->getContent()
  *
  * @param array  $contenttype
  * @param string $orderValue
  *
  * @return string
  */
 private function decodeQueryOrder($contenttype, $orderValue)
 {
     $order = false;
     if ($orderValue === false || $orderValue === '') {
         if ($this->isValidColumn($contenttype['sort'], $contenttype, true)) {
             $order = $this->getEscapedSortorder($contenttype['sort'], false);
         }
     } else {
         $parOrder = Str::makeSafe($orderValue);
         if ($parOrder == 'RANDOM') {
             $dboptions = $this->app['db']->getParams();
             $order = $dboptions['randomfunction'];
         } elseif ($this->isValidColumn($parOrder, $contenttype, true)) {
             $order = $this->getEscapedSortorder($parOrder, false);
         }
     }
     return $order;
 }
Esempio n. 5
0
 /**
  * Parse a Contenttype's filed and determine the grouping
  *
  * @param array $fields
  * @param array $generalConfig
  *
  * @return array
  */
 protected function parseFieldsAndGroups(array $fields, array $generalConfig)
 {
     $acceptableFileTypes = $generalConfig['accept_file_types'];
     $currentGroup = 'ungrouped';
     $groups = array();
     $hasGroups = false;
     foreach ($fields as $key => $field) {
         unset($fields[$key]);
         $key = str_replace('-', '_', strtolower(Str::makeSafe($key, true)));
         // If field is a "file" type, make sure the 'extensions' are set, and it's an array.
         if ($field['type'] == 'file' || $field['type'] == 'filelist') {
             if (empty($field['extensions'])) {
                 $field['extensions'] = $acceptableFileTypes;
             }
             if (!is_array($field['extensions'])) {
                 $field['extensions'] = array($field['extensions']);
             }
         }
         // If field is an "image" type, make sure the 'extensions' are set, and it's an array.
         if ($field['type'] == 'image' || $field['type'] == 'imagelist') {
             if (empty($field['extensions'])) {
                 $field['extensions'] = array_intersect(array('gif', 'jpg', 'jpeg', 'png'), $acceptableFileTypes);
             }
             if (!is_array($field['extensions'])) {
                 $field['extensions'] = array($field['extensions']);
             }
         }
         // If field is a "Select" type, make sure the array is a "hash" (as opposed to a "map")
         // For example: [ 'yes', 'no' ] => { 'yes': 'yes', 'no': 'no' }
         // The reason that we do this, is because if you set values to ['blue', 'green'], that is
         // what you'd expect to see in the database. Not '0' and '1', which is what would happen,
         // if we didn't "correct" it here.
         // @see used hack: http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
         if ($field['type'] == 'select' && isset($field['values']) && is_array($field['values']) && array_values($field['values']) === $field['values']) {
             $field['values'] = array_combine($field['values'], $field['values']);
         }
         if (!empty($field['group'])) {
             $hasGroups = true;
         }
         // Make sure we have these keys and every field has a group set
         $field = array_replace(array('label' => '', 'variant' => '', 'default' => '', 'pattern' => '', 'group' => $currentGroup), $field);
         // Collect group data for rendering.
         // Make sure that once you started with group all following have that group, too.
         $currentGroup = $field['group'];
         $groups[$currentGroup] = 1;
         // Prefix class with "form-control"
         $field['class'] = 'form-control' . (isset($field['class']) ? ' ' . $field['class'] : '');
         $fields[$key] = $field;
     }
     // Make sure the 'uses' of the slug is an array.
     if (isset($fields['slug']) && isset($fields['slug']['uses']) && !is_array($fields['slug']['uses'])) {
         $fields['slug']['uses'] = array($fields['slug']['uses']);
     }
     return array($fields, $hasGroups ? array_keys($groups) : false);
 }
Esempio n. 6
0
 /**
  * Set a Contenttype record values from a HTTP POST.
  *
  * @param array  $values
  * @param string $contenttype
  *
  * @throws \Exception
  *
  * @return void
  */
 public function setFromPost($values, $contenttype)
 {
     $values = Input::cleanPostedData($values);
     if (!$this->id) {
         // this is a new record: current user becomes the owner.
         $user = $this->app['users']->getCurrentUser();
         $this['ownerid'] = $user['id'];
     }
     // If the owner is set explicitly, check if the current user is allowed
     // to do this.
     if (isset($values['ownerid'])) {
         if ($this['ownerid'] != $values['ownerid']) {
             if (!$this->app['users']->isAllowed("contenttype:{$contenttype['slug']}:change-ownership:{$this->id}")) {
                 throw new \Exception("Changing ownership is not allowed.");
             }
             $this['ownerid'] = intval($values['ownerid']);
         }
     }
     // Make sure we have a proper status.
     if (!in_array($values['status'], ['published', 'timed', 'held', 'draft'])) {
         if ($this['status']) {
             $values['status'] = $this['status'];
         } else {
             $values['status'] = "draft";
         }
     }
     // Make sure we only get the current taxonomies, not those that were fetched from the DB.
     $this->taxonomy = [];
     if (!empty($values['taxonomy'])) {
         foreach ($values['taxonomy'] as $taxonomytype => $value) {
             if (!is_array($value)) {
                 $value = explode(",", $value);
             }
             if (isset($values['taxonomy-order'][$taxonomytype])) {
                 foreach ($value as $k => $v) {
                     $value[$k] = $v . "#" . $values['taxonomy-order'][$taxonomytype];
                 }
             }
             $this->taxonomy[$taxonomytype] = $value;
         }
         unset($values['taxonomy']);
         unset($values['taxonomy-order']);
     }
     // Get the relations from the POST-ed values.
     // @todo use $this->setRelation() for this
     if (!empty($values['relation'])) {
         $this->relation = $values['relation'];
         unset($values['relation']);
     } else {
         $this->relation = [];
     }
     // @todo check for allowed file types.
     // Handle file-uploads.
     if (!empty($_FILES)) {
         foreach ($_FILES as $key => $file) {
             if (empty($file['name'][0])) {
                 continue;
                 // Skip 'empty' uploads.
             }
             $paths = $this->app['resources']->getPaths();
             $filename = sprintf('%sfiles/%s/%s', $paths['rootpath'], date('Y-m'), Str::makeSafe($file['name'][0], false, '[]{}()'));
             $basename = sprintf('/%s/%s', date('Y-m'), Str::makeSafe($file['name'][0], false, "[]{}()"));
             if ($file['error'][0] != UPLOAD_ERR_OK) {
                 $message = 'Error occured during upload: ' . $file['error'][0] . " - {$filename}";
                 $this->app['logger.system']->error($message, ['event' => 'upload']);
                 continue;
             }
             if (substr($key, 0, 11) != 'fileupload-') {
                 $message = "Skipped an upload that wasn't for content: {$filename}";
                 $this->app['logger.system']->error($message, ['event' => 'upload']);
                 continue;
             }
             $fieldname = substr($key, 11);
             $fileSystem = new Filesystem();
             // Make sure the folder exists.
             $fileSystem->mkdir(dirname($filename));
             // Check if we don't have doubles.
             if (is_file($filename)) {
                 while (is_file($filename)) {
                     $filename = $this->upcountName($filename);
                     $basename = $this->upcountName($basename);
                 }
             }
             if (is_writable(dirname($filename))) {
                 // Yes, we can create the file!
                 move_uploaded_file($file['tmp_name'][0], $filename);
                 $values[$fieldname] = $basename;
                 $this->app['logger.system']->info("Upload: uploaded file '{$basename}'.", ['event' => 'upload']);
             } else {
                 $this->app['logger.system']->error("Upload: couldn't write upload '{$basename}'.", ['event' => 'upload']);
             }
         }
     }
     $this->setValues($values);
 }
 /**
  * Get the parameter for the 'order by' part of a query.
  *
  * This is tightly coupled to $this->getContent()
  *
  * @param array  $contenttype
  * @param string $orderValue
  *
  * @return string
  */
 private function decodeQueryOrder($contenttype, $orderValue)
 {
     $order = false;
     if ($orderValue === false || $orderValue === '') {
         if ($this->isValidColumn($contenttype['sort'], $contenttype, true)) {
             $order = $contenttype['sort'];
         }
     } else {
         $parOrder = Str::makeSafe($orderValue);
         if ($parOrder == 'RANDOM') {
             // Unsupported
             return false;
         } elseif ($this->isValidColumn($parOrder, $contenttype, true)) {
             $order = $parOrder;
         }
     }
     return $order;
 }
Esempio n. 8
0
 public function testSwedishMakeSafe()
 {
     // Swedish
     $input = "Skämt åsido satan vilket uruselt tillvägagångsätt";
     $this->assertEquals("skaemt-aasido-satan-vilket-uruselt-tillvaegagaangsaett", Str::makeSafe($input, true, ';'));
 }
Esempio n. 9
0
File: Config.php Progetto: bolt/bolt
 /**
  * Sanity checks for doubles in in contenttypes.
  *
  * @return bool
  */
 public function checkConfig()
 {
     $slugs = [];
     $passed = true;
     foreach ($this->data['contenttypes'] as $key => $ct) {
         // Make sure that there are no hyphens in the contenttype name, advise to change to underscores
         if (strpos($key, '-') !== false) {
             $error = Trans::__('contenttypes.generic.invalid-hyphen', ['%contenttype%' => $key]);
             $this->app['logger.flash']->error($error);
             $original = $this->data['contenttypes'][$key];
             $key = str_replace('-', '_', strtolower(Str::makeSafe($key, true)));
             $this->data['contenttypes'][$key] = $original;
             $passed = false;
         }
         /**
          * Make sure any field that has a 'uses' parameter actually points to a field that exists.
          *
          * For example, this will show a notice:
          * entries:
          *   name: Entries
          *     singular_name: Entry
          *     fields:
          *       title:
          *         type: text
          *         class: large
          *       slug:
          *         type: slug
          *         uses: name
          */
         foreach ($ct['fields'] as $fieldname => $field) {
             // Verify that the contenttype doesn't try to add fields that are reserved.
             if ($fieldname != 'slug' && in_array($fieldname, $this->reservedFieldNames)) {
                 $error = Trans::__('contenttypes.generic.reserved-name', ['%contenttype%' => $key, '%field%' => $fieldname]);
                 $this->app['logger.flash']->danger($error);
                 $passed = false;
             }
             // Check 'uses'. If it's an array, split it up, and check the separate parts. We also need to check
             // for the fields that are always present, like 'id'.
             if (!empty($field['uses']) && is_array($field['uses'])) {
                 foreach ((array) $field['uses'] as $useField) {
                     if (!empty($field['uses']) && empty($ct['fields'][$useField]) && !in_array($useField, $this->reservedFieldNames)) {
                         $error = Trans::__('contenttypes.generic.wrong-use-field', ['%contenttype%' => $key, '%field%' => $fieldname, '%uses%' => $useField]);
                         $this->app['logger.flash']->warning($error);
                         $passed = false;
                     }
                 }
             }
             // Make sure that there are no hyphens in the field names, advise to change to underscores
             if (!isset($field['type']) || !$this->fields->has($field['type'])) {
                 $error = Trans::__('contenttypes.generic.no-proper-type', ['%contenttype%' => $key, '%field%' => $fieldname, '%type%' => $field['type']]);
                 $this->app['logger.flash']->warning($error);
                 unset($ct['fields'][$fieldname]);
                 $passed = false;
             }
         }
         /**
          * Make sure any contenttype that has a 'relation' defined points to a contenttype that exists.
          */
         if (isset($ct['relations'])) {
             foreach ($ct['relations'] as $relKey => $relData) {
                 // For BC we check if relation uses hyphen and re-map to underscores
                 if (strpos($relKey, '-') !== false) {
                     $newRelKey = str_replace('-', '_', strtolower(Str::makeSafe($relKey, true)));
                     unset($this->data['contenttypes'][$key]['relations'][$relKey]);
                     $this->data['contenttypes'][$key]['relations'][$newRelKey] = $relData;
                     $relKey = $newRelKey;
                 }
                 if (!isset($this->data['contenttypes'][$relKey])) {
                     $error = Trans::__('contenttypes.generic.invalid-relation', ['%contenttype%' => $key, '%relation%' => $relKey]);
                     $this->app['logger.flash']->error($error);
                     unset($this->data['contenttypes'][$key]['relations'][$relKey]);
                     $passed = false;
                 }
             }
         }
         // Keep a running score of used slugs.
         if (!isset($slugs[$ct['slug']])) {
             $slugs[$ct['slug']] = 0;
         }
         $slugs[$ct['slug']]++;
         if (!isset($slugs[$ct['singular_slug']])) {
             $slugs[$ct['singular_slug']] = 0;
         }
         if ($ct['singular_slug'] != $ct['slug']) {
             $slugs[$ct['singular_slug']]++;
         }
     }
     // Sanity checks for taxonomy.yml
     foreach ($this->data['taxonomy'] as $key => $taxo) {
         // Show some helpful warnings if slugs or keys are not set correctly.
         if ($taxo['slug'] != $key) {
             $error = Trans::__("The identifier and slug for '%taxonomytype%' are the not the same ('%slug%' vs. '%taxonomytype%'). Please edit taxonomy.yml, and make them match to prevent inconsistencies between database storage and your templates.", ['%taxonomytype%' => $key, '%slug%' => $taxo['slug']]);
             $this->app['logger.flash']->warning($error);
             $passed = false;
         }
     }
     // if there aren't any other errors, check for duplicates across contenttypes.
     if (!$this->app['logger.flash']->has('error')) {
         foreach ($slugs as $slug => $count) {
             if ($count > 1) {
                 $error = Trans::__("The slug '%slug%' is used in more than one contenttype. Please edit contenttypes.yml, and make them distinct.", ['%slug%' => $slug]);
                 $this->app['logger.flash']->warning($error);
                 $passed = false;
             }
         }
     }
     return $passed && $this->checkTaxonomy();
 }