public function update($id = '') { $page = $this->page($id); if (!$page) { return response::error(l('pages.error.missing')); } $blueprint = blueprint::find($page); $fields = $blueprint->fields($page); $oldTitle = (string) $page->title(); // trigger the validation $form = new Form($fields->toArray()); $form->validate(); // fetch the data for the form $data = pagedata::createByInput($page, $form->serialize()); // stop at invalid fields if (!$form->isValid()) { return response::error(l('pages.show.error.form'), 400, array('fields' => $form->fields()->filterBy('error', true)->pluck('name'))); } try { $page->update($data, app::$language); // make sure that the sorting number is correct if ($page->isVisible()) { $num = api::createPageNum($page); if ($num !== $page->num()) { if ($num > 0) { $page->sort($num); } else { // update the slug if ($data['title'] != $oldTitle) { $uid = str::slug($data['title']); $page->move($uid); } } } } history::visit($page->id()); return response::success('success', array('file' => $page->content()->root(), 'data' => $data, 'uid' => $page->uid(), 'uri' => $page->id())); } catch (Exception $e) { return response::error($e->getMessage()); } }
/** * @param string $id * @param PageAbstract $product */ public function __construct($id, PageAbstract $product, $quantity) { $variant = false; // Break cart ID into uri, variant, and option (:: is used as a delimiter) $id_array = explode('::', $id); // Set variant and option $variantName = $id_array[1]; $variants = $product->variants()->yaml(); foreach ($variants as $key => $array) { if (str::slug($array['name']) === $variantName) { $variant = $variants[$key]; } } $this->id = $id; $this->sku = $variant['sku']; $this->uri = $product->uri(); $this->name = $product->title()->value; $this->variant = str::slug($variant['name']); $this->option = $id_array[2]; $this->amount = $variant['price']; $this->sale_amount = salePrice($variant); $this->weight = $variant['weight']; $this->quantity = $quantity; $this->noshipping = $product->noshipping()->value; $this->notax = $product->notax()->value; }
function create_post($page, $blueprint, $title, $data) { // Where we'll put the content. $PATH = get_content_path($page); $SLUG = str::slug($title); $dir = $PATH . DS . $SLUG; $dir_matches = glob($PATH . DS . "*" . $SLUG . "*"); // If the directory already exists don't override it, // append a number to it, no matter its visibility. // 1-directory // directory_1 // 8-directory_2 if (count($dir_matches) > 0) { $dir .= "_" . count($dir_matches); $title .= "_" . count($dir_matches); } // Pass $title into the $data array for easiest manipulation. $data["title"] = $title; // Create the directory with read&write permissions. mkdir($dir, 0777, true); // Filename with (almost) multilingual support. // Peraphs you'll want to create different files for each // languages code. $filename = $blueprint . ".fr.txt"; // Write the file. $file = fopen($dir . DS . $filename, 'w'); if (flock($file, LOCK_EX)) { fwrite($file, parse_data(get_blueprint($blueprint), $data)); flock($file, LOCK_EX); } fclose($file); }
protected function inspectOptions($options) { $page = page('docs/cheatsheet/options'); $children = $page->children(); foreach ($options as $key => $value) { if (!$children->find(str::slug($key))) { $this->results[] = 'Missing option: ' . $key; } } }
/** * Save the submission * * @return void */ public function store($page) { $timestamp = date('YmdHis', $this->data['timestamp']); $title = $this->data['business_name'] . '-' . $timestamp; $uid = String::slug($title); $data = $this->data; $data['title'] = $title; $data['date'] = date('Y-m-d', $this->data['timestamp']); $page->children()->create($uid, 'list-request', $data); }
private function updateQty($id, $newQty) { // $id is formatted uri::variantslug::optionslug $idParts = explode('::', $id); $uri = $idParts[0]; $variantSlug = $idParts[1]; $optionSlug = $idParts[2]; // Get combined quantity of this option's siblings $siblingsQty = 0; foreach ($this->data as $key => $qty) { if (strpos($key, $uri . '::' . $variantSlug) === 0 and $key != $id) { $siblingsQty += $qty; } } foreach (page($uri)->variants()->toStructure() as $variant) { if (str::slug($variant->name()) === $variantSlug) { // Store the stock in a variable for quicker processing $stock = inStock($variant); // If there are no siblings if ($siblingsQty === 0) { // If there is enough stock if ($stock === true or $stock >= $newQty) { return $newQty; } else { if ($stock === false) { return 0; } else { return $stock; } } } else { // If the siblings plus $newQty won't exceed the max stock, go ahead if ($stock === true or $stock >= $siblingsQty + $newQty) { return $newQty; } else { if ($stock === false or $stock <= $siblingsQty) { return 0; } else { if ($stock > $siblingsQty and $stock <= $siblingsQty + $newQty) { return $stock - $siblingsQty; } } } } } } // The script should never get to this point return 0; }
/** * After a successful transaction, update product stock * Expects an array * $items = [ * [uri, variant, quantity] * ] */ function updateStock($items) { foreach ($items as $i => $item) { $product = page($item['uri']); $variants = $product->variants()->yaml(); foreach ($variants as $key => $variant) { if (str::slug($variant['name']) === $item['variant']) { // Edit stock in the original $variants array. If $newStock is false/blank, that means it's unlimited. $newStock = $variant['stock'] - $item['quantity']; $variants[$key]['stock'] = $newStock ? $newStock : ''; // Update the entire variants field (only one variant has changed) $product->update(array('variants' => yaml::encode($variants))); } } } }
public function update($id = '') { $page = $this->page($id); if (!$page) { return response::error(l('pages.error.missing')); } $blueprint = blueprint::find($page); $fields = $blueprint->fields($page); $oldTitle = (string) $page->title(); // trigger the validation $form = new Form($fields->toArray()); $form->validate(); // fetch the data for the form $data = pagedata::createByInput($page, $form->serialize()); // stop at invalid fields if (!$form->isValid()) { return response::error(l('pages.show.error.form'), 400, array('fields' => $form->fields()->filterBy('error', true)->pluck('name'))); } try { PageStore::discard($page); $page->update($data); // make sure that the sorting number is correct if ($page->isVisible()) { $num = api::createPageNum($page); if ($num !== $page->num()) { if ($num > 0) { $page->sort($num); } } } // get the blueprint of the parent page to find the // correct sorting mode for this page $parentBlueprint = blueprint::find($page->parent()); // auto-update the uid if the sorting mode is set to zero if ($parentBlueprint->pages()->num()->mode() == 'zero') { $uid = str::slug($page->title()); $page->move($uid); } history::visit($page->id()); kirby()->trigger('panel.page.update', $page); return response::success('success', array('file' => $page->content()->root(), 'data' => $data, 'uid' => $page->uid(), 'uri' => $page->id())); } catch (Exception $e) { return response::error($e->getMessage()); } }
/** * Returns the slug for the page * The slug is the last part of the URL path * For multilang sites this can be translated with a URL-Key field * in the text file for this page. * * @param string $lang Optional language code to get the translated slug * @return string i.e. 01-projects returns projects */ public function slug($lang = null) { $default = $this->site->defaultLanguage->code; $current = $this->site->language->code; // get the slug for the current language if (is_null($lang)) { // the current language's slug can be cached if (isset($this->cache['slug'])) { return $this->cache['slug']; } // if the current language is the default language // simply return the uid if ($current == $default) { return $this->cache['slug'] = $this->uid(); } // geth the translated url key if available $key = (string) a::get((array) $this->content()->data(), 'url_key'); // return the translated slug or otherwise the uid return empty($key) ? $this->uid() : $key; } else { // if the passed language code is the current language code // we can simply return the slug method without a language code specified if ($lang == $current) { return $this->slug(); } // the slug for the default language is just the name of the folder if ($lang == $default) { return $this->uid(); } // search for content in the specified language if ($content = $this->content($lang)) { // search for a translated url_key in that language if ($slug = a::get((array) $content->data(), 'url_key')) { // if available, use the translated url key as slug return str::slug($slug); } } // use the uid if no translation could be found return $this->uid(); } }
public function fetchMethod($className, $method) { $phpdoc = new DocBlock($method->getDocComment()); $call = array(); $params = array(); $return = null; // build the call example string foreach ($method->getParameters() as $param) { if ($param->isOptional()) { try { $value = var_export($param->getDefaultValue(), true); $value = str_replace(PHP_EOL, '', $value); $value = str_replace('NULL', 'null', $value); $value = str_replace('array ()', 'array()', $value); $call[] = '$' . $param->getName() . ' = ' . $value; } catch (Exception $e) { $call[] = '$' . $param->getName(); } } else { $call[] = '$' . $param->getName(); } } // get all parameter docs foreach ($phpdoc->getTags() as $tag) { switch ($tag->getName()) { case 'param': $params[] = array('name' => $tag->getVariableName(), 'type' => $tag->getType(), 'text' => $tag->getDescription()); break; case 'return': $return = array('type' => $tag->getType(), 'text' => $tag->getDescription()); break; } } // a::first $methodName = strtolower($className) . '::' . $method->getName(); $methodSlug = str::slug($method->getName()); // build the full method array return array('name' => $methodName, 'slug' => $methodSlug, 'excerpt' => str_replace(PHP_EOL, ' ', $phpdoc->getShortDescription()), 'call' => $methodName . '(' . implode(', ', $call) . ')', 'return' => $return, 'params' => $params); }
public static function createPage($uri, $title, $template, $uid) { $parent = empty($uri) ? site() : page($uri); $uid = empty($uid) ? str::slug($title) : str::slug($uid); if (empty($title)) { throw new Exception(l('pages.add.error.title')); } if (empty($template)) { throw new Exception(l('pages.add.error.template')); } $data = pagedata::createByBlueprint($template, array('title' => $title)); $page = $parent->children()->create($uid, $template, $data); $blueprint = blueprint::find($page); if (is_array($blueprint->pages()->build())) { foreach ($blueprint->pages()->build() as $build) { $missing = a::missing($build, array('title', 'template', 'uid')); if (!empty($missing)) { continue; } static::createPage($page->uri(), $build['title'], $build['template'], $build['uid']); } } return $page; }
/** * @param string $originalString String to be sluggified * @param string $expectedResult What we expect our slug result to be * * @dataProvider strProvider */ public function testSlug($originalString, $expectedString) { $result = str::slug($originalString); $this->assertEquals($expectedString, $result); }
public function setSlugAttribute($value) { $this->attributes['slug'] = str::slug($value); }
/** * Generate file slug * * @since 1.0.0 * * @param \File $file * @return string */ public function itemId($file) { return $this->name() . '-' . str::slug($file->filename()); }
/** * Changes the uid for the page * * @param string $uid */ public function move($uid) { $uid = str::slug($uid); if (empty($uid)) { throw new Exception('The uid is missing'); } // don't do anything if the uid exists if ($this->uid() === $uid) { return true; } // check for an existing page with the same UID if ($this->siblings()->not($this)->find($uid)) { throw new Exception('A page with this uid already exists'); } $dir = $this->isVisible() ? $this->num() . '-' . $uid : $uid; $root = dirname($this->root()) . DS . $dir; if (!dir::move($this->root(), $root)) { throw new Exception('The directory could not be moved'); } $this->dirname = $dir; $this->root = $root; $this->uid = $uid; // assign a new id and uri $this->id = $this->uri = ltrim($this->parent->id() . '/' . $this->uid, '/'); // clean the cache $this->kirby->cache()->flush(); $this->reset(); return true; }
public static function sanitize($data, $mode = 'insert') { // all usernames must be lowercase $data['username'] = str::slug(a::get($data, 'username')); // return the cleaned up data return $data; }
/** * Sanitize a filename to strip unwanted special characters * * <code> * * $safe = f::safeName('über genious.txt'); * // safe will be ueber-genious.txt * * </code> * * @param string $string The file name * @return string */ public static function safeName($string) { $name = static::name($string); $extension = static::extension($string); $end = !empty($extension) ? '.' . str::slug($extension) : ''; return str::slug($name) . $end; }
<?php kirbytext::$post[] = function ($kirbytext, $value) { return preg_replace_callback('!\\(toc\\)!', function ($match) use($value) { preg_match_all('!<h2>(.*)</h2>!', $value, $matches); $ul = brick('ul'); $ul->addClass('toc'); foreach ($matches[1] as $match) { $li = brick('li', '<a href="#' . str::slug($match) . '">' . $match . '</a>'); $ul->append($li); } return $ul; }, $value); };
} } // Get countries $countries = page('/shop/countries')->children()->invisible(); // Get shipping rates $shipping_rates = $cart->getShippingRates(); // Set shipping method as a session variable // Shipping method is an array containing 'title' and 'rate' $shippingMethods = $cart->getShippingRates(); if (get('shipping')) { // First option: see if a shipping method was set through a form submission if (get('shipping') == 'free-shipping') { $shippingMethod = ['title' => l::get('free-shipping'), 'rate' => 0]; } foreach ($shippingMethods as $key => $method) { if (get('shipping') == str::slug($method['title'])) { $shippingMethod = $method; } } } else { if (s::get('shipping')) { // Second option: the shipping has already been set in the session $shippingMethod = s::get('shipping'); } else { // Last resort: choose the first shipping method $shippingMethod = array_shift($shippingMethods); } } s::set('shipping', $shippingMethod); // Get selected shipping rate $shipping = s::get('shipping');
} /** * Json adapter */ data::$adapters['json'] = array('extension' => 'json', 'encode' => function ($data) { return json_encode($data); }, 'decode' => function ($string) { return json_decode($string, true); }); /** * Kirby data adapter */ data::$adapters['kd'] = array('extension' => array('md', 'txt'), 'encode' => function ($data) { $result = array(); foreach ($data as $key => $value) { $key = str::ucfirst(str::slug($key)); if (empty($key) or is_null($value)) { continue; } // escape accidental dividers within a field $value = preg_replace('!(\\n|^)----(.*?\\R*)!', "\$1\\----\$2", $value); // multi-line content if (preg_match('!\\R!', $value, $matches)) { $result[$key] = $key . ": \n\n" . trim($value); // single-line content } else { $result[$key] = $key . ': ' . trim($value); } } return implode("\n\n----\n\n", $result); }, 'decode' => function ($string) {
<?php // Initialize user variable so we can use it in the file name $user = site()->user(); try { // Create transaction record $neworder = page('shop/orders')->children()->create(str::slug($user->username . '-paylater-' . date('U')), 'order', array('txn-id' => 'paylater-' . date('U'), 'txn-date' => date('U'), 'txn-currency' => page('shop')->currency_code()->value, 'status' => 'Invoice', 'products' => urldecode($_POST['products']), 'subtotal' => $_POST['subtotal'], 'shipping' => $_POST['shipping'], 'tax' => $_POST['tax'], 'payer-id' => $user->username, 'payer-name' => $user->name, 'payer-email' => $user->email, 'payer-address' => '')); // Empty the cart s::set('cart', array()); } catch (Exception $e) { // Failure message to be passed through }
<?php $company = $page->company(); ?> <?php if ($company == 'Isle of Wight') { ?> <a rel="up" href="/regions/england/isle-of-wight">Isle of Wight</a> <?php } elseif ($company == 'London') { ?> <a rel="up" href="/regions/england/london">London</a> <?php } else { ?> <a rel="up" href="/companies/<?php echo preg_replace('/-railway$/', '', str::slug($company)); ?> "><?php echo $company->title(); ?> </a> <?php } ?> </nav> </header> <?php if ($page->text()->isNotEmpty()) { ?> <div class="e-content prose">
<?php return function ($page) { // label option $option = new Brick('a', icon('magic', 'left') . l('pages.url.uid.label.option'), array('class' => 'btn btn-icon label-option', 'href' => '#', 'data-title' => str::slug($page->title()))); // url preview $preview = new Brick('div', '', array('class' => 'uid-preview')); $preview->append(ltrim($page->parent()->uri() . '/', '/')); $preview->append('<span>' . $page->slug() . '</span>'); // create the form $form = new Kirby\Panel\Form(array('uid' => array('label' => l('pages.url.uid.label') . $option, 'type' => 'text', 'icon' => 'chain', 'autofocus' => true, 'help' => $preview, 'default' => $page->slug()))); $form->buttons->submit->val(l('change')); $form->cancel($page); return $form; };
public function slug() { return str::slug(get('string')); }
?> </button> </form> <span class="uk-margin-small-left uk-margin-small-right"><?php echo $item->quantity; ?> </span> <form class="uk-display-inline" action="" method="post"> <input type="hidden" name="action" value="add"> <input type="hidden" name="id" value="<?php echo $item->id; ?> "> <?php foreach (page($item->uri)->variants()->toStructure() as $variant) { if (str::slug($variant->name()) === $item->variant) { // Get combined quantity of this option's siblings $siblingsQty = 0; foreach ($cart->data as $key => $qty) { if (strpos($key, $item->uri . '::' . $item->variant) === 0 and $key != $item->id) { $siblingsQty += $qty; } } // Determine if we are at the maximum quantity if (inStock($variant) !== true and inStock($variant) <= $item->quantity + $siblingsQty) { $maxQty = true; } else { $maxQty = false; } } }
public function updateUid() { // auto-update the uid if the sorting mode is set to zero if ($this->parent()->blueprint()->pages()->num()->mode() == 'zero') { $uid = str::slug($this->title()); $this->move($uid); } return $this->uid(); }
<div property="description"> <?php ecco(trim($variant->description()) != '', $variant->description()->kirbytext()->bidi()); ?> </div> <?php if ($variant->hasOptions) { ?> <select dir="auto" class="uk-width-1-1" name="option"> <?php foreach (str::split($variant->options()) as $option) { ?> <option value="<?php echo str::slug($option); ?> "><?php echo str::ucfirst($option); ?> </option> <?php } ?> </select> <?php } ?> <button <?php e(inStock($variant), '', 'disabled');
public static function sanitize($data, $mode = 'insert') { // all usernames must be lowercase $data['username'] = str::slug(a::get($data, 'username')); // convert all keys to lowercase $data = array_change_key_case($data, CASE_LOWER); // return the cleaned up data return $data; }
echo l::get('update-country'); ?> </button> </form> <!-- Set shipping --> <form class="col--6 left" id="setShipping" action="" method="POST"> <select name="shipping" onChange="document.forms['setShipping'].submit();"> <?php if (count($shipping_rates) > 0) { ?> <?php foreach ($shipping_rates as $rate) { ?> <option value="<?php echo str::slug($rate['title']); ?> " <?php e($shipping['title'] === $rate['title'], 'selected'); ?> > <?php echo $rate['title']; ?> (<?php echo formatPrice($rate['rate']); ?> ) </option> <?php }
public function testSlug() { // Double dashes $this->assertEquals('a-b', str::slug('a--b')); // Dashes at the end of the line $this->assertEquals('a', str::slug('a-')); // Dashes at the beginning of the line $this->assertEquals('a', str::slug('-a')); // Underscores converted to dashes $this->assertEquals('a-b', str::slug('a_b')); // Unallowed characters $this->assertEquals('a-b', str::slug('a@b')); // Spaces characters $this->assertEquals('a-b', str::slug('a b')); // Double Spaces characters $this->assertEquals('a-b', str::slug('a b')); // Custom separator $this->assertEquals('a+b', str::slug('a-b', '+')); // Allow underscores $this->assertEquals('a_b', str::slug('a_b', '-', 'a-z0-9_')); // store default defaults $defaults = str::$defaults['slug']; // Custom str defaults str::$defaults['slug']['separator'] = '+'; str::$defaults['slug']['allowed'] = 'a-z0-9_'; $this->assertEquals('a+b', str::slug('a-b')); $this->assertEquals('a_b', str::slug('a_b')); // Reset str defaults str::$defaults['slug'] = $defaults; }