public function forField($field) { if (method_exists($this->model, $field)) { throw new Exception('The field name: ' . $field . ' cannot be used as it is reserved'); } $this->field = $field; $this->config = $this->model->getBlueprintFields()->get($this->field); if (is_a($this->model, 'Page')) { $source = $this->model->content()->get($this->field); $decode = true; } else { if (is_a($this->model, 'File')) { $source = $this->model->meta()->get($this->field); $decode = true; } else { if (is_a($this->model, 'User')) { $source = $this->model->{$this->field}(); $decode = false; } else { throw new Exception('Invalid model for structure field: ' . $this->field); } } } $this->source = $decode ? (array) yaml::decode($source) : (array) $source; $this->store = new Store($this, $this->source); return $this; }
public function get_page_name($page_name, $toolname, $parent_id) { if (!empty($page_name)) { if ('get' == $page_name) { return yaml::does_value_exist($this->site_name, 'pages_config', "{$toolname}-{$parent_id}"); } else { return $page_name; } } return $this->homepage; }
public function forField($field) { if (method_exists($this->model, $field)) { throw new Exception('The field name: ' . $field . ' cannot be used as it is reserved'); } $this->field = $field; $this->config = $this->model->getBlueprintFields()->get($this->field); $this->source = (array) yaml::decode($this->model->{$this->field}()); $this->store = new Store($this, $this->source()); return $this; }
public function result() { $result = parent::result(); $raw = (array) json_decode($result); $data = array(); foreach ($raw as $key => $row) { unset($row->_id); unset($row->_csfr); $data[$key] = (array) $row; } return yaml::encode($data); }
public function getEmailParams() { //if we have a correct email template if ($this->emailTemplate) { //store template content in a string $emailWithPlaceholders = $this->emailTemplate->read(); //replace placeholders in $emailWithPlaceholders with data $emailWithData = str::template($emailWithPlaceholders, $this->emailData); //return array return yaml::decode($emailWithData); } //return emmpty array in case of error while getting email template return ''; }
/** * 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 parse_tokens($body) { # NEWSLETTER TOKEN. str_replace('{{newsletter}}', '', $body, $count); if (0 < $count) { $pages_config = yaml::parse($this->site_name, 'pages_config'); if (empty($pages_config['newsletter'])) { return $body; } $parent_id = explode('-', $pages_config['newsletter']); $parent_id = $parent_id['1']; # get the newsletter HTML. $newsletter = new Newsletter_Controller(); $body = str_replace('{{newsletter}}', $newsletter->_index($parent_id), $body); } # ------------------------------------------------------ # SHOWROOM TOKEN. format: {showroom_cats:parent_id:parameters} $pattern = '/{showroom_cats:(\\d+)\\:(\\w+)\\}/'; if (0 < preg_match($pattern, $body, $match)) { # get the page name. $page_name = yaml::does_value_exist($this->site_name, 'pages_config', "showroom-{$match[1]}"); if (!$page_name) { return $body; } # get the showroom category html. $showroom = ORM::factory('showroom', $match[1]); if (!$showroom->loaded) { return $body; } # how should the list be displayed? if (!empty($match[2]) and 'flat' == $match[2]) { # showing only root categories. $root_cats = ORM::factory('showroom_cat')->where(array('fk_site' => $this->site_id, 'showroom_id' => $showroom->id, 'local_parent' => $showroom->root_id))->orderby(array('lft' => 'asc'))->find_all(); $categories = Tree::display_flat_tree('showroom', $root_cats, $page_name); } else { $categories = Tree::display_tree('showroom', $showroom->showroom_cats, $page_name); } $body = preg_replace($pattern, $categories, $body, 1); } /* -------------------------------------------- */ # google map! format: {google_map:parent_id:parameters} $pattern = '/{google_map:(\\d+)\\:(\\w+)\\}/'; if (0 < preg_match($pattern, $body, $match)) { } return $body; }
/** * Loads URI, and Input into this controller. * * @return void */ public function __construct() { $session = Session::instance(); $site_config = yaml::parse($_SESSION['site_name'], 'site_config'); foreach ($site_config as $key => $value) { $this->{$key} = $value; } // --- Setup our required library instances --- // -------------------------------------------- # Auth Instance for editing site capability $this->client = new Auth($this->claimed); # Account Instance for user account tool. $this->account_user = new Account(); # assets instance to fetch datapath urls. $this->assets = Assets::instance($this->site_name, $this->theme); # URI should always be available $this->uri = URI::instance(); # Input should always be available $this->input = Input::instance(); if (Kohana::$instance == NULL) { # Set the instance to the first controller loaded Kohana::$instance = $this; } }
public function userSubscribetoSession($newRegisteredUser, array $unsetFields) { //get user's data $userData = $newRegisteredUser->data(); //remove private data from user's data foreach ($unsetFields as $k => $v) { if (array_key_exists($v, $userData)) { unset($userData[$v]); } } //get full path to user's results' file $userResultsFile = $this->getUserResultsFile(); //if file could be created if (yaml::write($userResultsFile, $userData)) { //return true return true; } else { //add error: user's results file couldn't be created $this->addError('session.fail.resultsFile'); } //return false return false; }
public function settings($page_id = NULL) { valid::id_key($page_id); $page = ORM::factory('page')->where('fk_site', $this->site_id)->find($page_id); if (!$page->loaded) { die('invalid page id'); } if ($_POST) { # Validate page_name & duplicate check $directory = empty($_POST['directory']) ? NULL : $_POST['directory']; $new_page_name = $filename = self::validate_page_name($_POST['label'], $_POST['page_name'], $directory, $_POST['page_name']); if (!empty($directory)) { $new_page_name = "{$directory}/{$filename}"; } # if this page was the homepage, update homepage value if ($this->homepage == $_POST['old_page_name']) { $site = ORM::factory('site', $this->site_id); $site->homepage = $filename; $site->save(); yaml::edit_site_value($this->site_name, 'site_config', 'homepage', $filename); $_POST['enable'] = 'yes'; # force homepage to be enabled. } $page->page_name = $new_page_name; $page->title = $_POST['title']; $page->meta = $_POST['meta']; $page->label = $_POST['label']; $page->template = $_POST['template']; $page->menu = $_POST['menu']; $page->enable = isset($_POST['enable']) ? $_POST['enable'] : 'yes'; $page->save(); # did the page name change? # update all children within this "folder" if ($_POST['old_page_name'] != $filename) { # if this page is protected update the pages_config file. yaml::edit_key($this->site_name, 'pages_config', $_POST['old_page_name'], $filename); $old_full_page = empty($_POST['directory']) ? $_POST['old_page_name'] : $_POST['directory'] . '/' . $_POST['old_page_name']; $dir_pages = self::get_folder_filenames($old_full_page, 'change'); # if this page has children, update them! foreach ($dir_pages as $page_id => $page_name) { $page = ORM::factory('page')->where('fk_site', $this->site_id)->find($page_id); if (!$page->loaded) { continue; } $page->page_name = "{$new_page_name}/{$page_name}"; $page->save(); } } # if the page was the account page, update site_config if ($this->account_page == $_POST['old_page_name']) { yaml::edit_site_value($this->site_name, 'site_config', 'account_page', $filename); } # should we publish this page? if (isset($_POST['publish']) and 'yes' == $_POST['publish']) { $cache = DATAPATH . "{$this->site_name}/cache/{$page_id}.html"; if (file_exists($cache)) { unlink($cache); } } die('Page Settings Saved'); # success } # Is this a subpage? (pop the end filename node from the directory.) $filename = $page->page_name; $directory = ''; $directory_array = explode('/', $filename); if (1 < count($directory_array)) { $filename = array_pop($directory_array); $directory = implode('/', $directory_array); } $primary = new View("page/page_settings"); $primary->page = $page; $primary->filename = $filename; $primary->dir = $directory; # get available templates from theme. if ($templates = yaml::parse($this->site_name, NULL, "themes/{$this->theme}/config")) { $primary->templates = $templates; } else { $primary->templates = array('master' => 'default layout'); } # Javascript duplicate page_name filter Validation # convert filter_array to string to use as javascript array $filter_array = self::get_folder_filenames($directory, NULL, $filename); $filter_string = implode("','", $filter_array); $primary->page_filter_js = "'{$filter_string}'"; # is page protected? $primary->is_protected = yaml::does_key_exist($this->site_name, 'pages_config', $page->page_name) ? TRUE : FALSE; die($primary); }
public function remove() { if (empty($_GET['instance_id'])) { die('invalid instance_id'); } $instance_id = valid::id_key($_GET['instance_id']); $db = Database::instance(); # get the instance $instance = $db->query("\n SELECT * FROM pages_tools\n WHERE id = '{$instance_id}'\n AND fk_site = '{$this->site_id}'\n ")->current(); if (!is_object($instance)) { die('invalid instance'); } # get the tool. $tool = ORM::factory('tool')->where('fk_site', $this->site_id)->find($instance->tool_id); # is this tool protected? if ('yes' == $tool->system_tool->protected) { # get the page. $page = ORM::factory('page')->where('fk_site', $this->site_id)->find($instance->page_id); # remove the protected signifier for this page. yaml::delete_value($this->site_name, 'pages_config', $page->page_name); } # delete the instance. $db->delete('pages_tools', array('id' => $instance_id, 'fk_site' => $this->site_id)); die('Tool instance removed from page.'); }
protected function parse_formatted_request_parameters() { if ($this->content_length() == 0) { return array(); } $mpb = self::extract_multipart_boundary($this->content_type_with_parameters()); if (count($mpb) > 1) { list($content_type, $boundary) = $mpb; } else { $content_type = $mpb; } # Don't parse params for unknown requests if (empty($content_type)) { return array(); } $mime_type = \mime\type::lookup($content_type); $strategy = base::$param_parsers[strtoupper($mime_type->symbol)]; $body = $strategy && $strategy != 'multipart_form' ? $this->raw_post() : $this->body(); try { switch ($strategy) { case 'url_encoded_form': self::clean_up_ajax_request_body($body); return self::parse_query_parameters($body); case 'multipart_form': return self::parse_multipart_form_parameters($body, $boundary, $content_length, $env); case 'xml_simple': case 'xml_node': break; case 'yaml': return yaml::load($body); break; default: return array(); } } catch (\biru_controller\sake_exception $e) { throw $e; } }
/** * Save the order to persistent storage * * @return mixed Order ID if successfully saved, otherwise false */ public function store($data) { $id = time() . dechex(intval(time())); $guests = []; foreach ($this->guests() as $guest) { $guests[] = ['name' => $guest, 'checkedIn' => false]; } $order = ['title' => $id, 'customerName' => $data['name'], 'customerPhone' => $data['phone'], 'customerEmail' => $data['email'], 'comments' => $data['comments'], 'date' => date('Y-m-d'), 'time' => date('g:ia'), 'total' => $this->total(), 'guests' => yaml::encode($guests)]; try { $orderPage = $this->event->children()->find('orders')->children()->create($id, 'order', $order); } catch (Exception $e) { die($e->getMessage()); } return $orderPage; }
function get_blueprint($blueprint) { $file = get_blueprint_path($blueprint); if ($file) { return yaml::read($file); } else { return false; } }
public function claim_login() { if (!$_POST) { die('nothing sent'); } # atttempt to log user in. if ($this->account_user->login($_POST['username'], (int) self::plusjade_site_id, $_POST['password'])) { $plusjade_user = ORM::factory('account_user')->where('fk_site', self::plusjade_site_id)->find($_POST['username']); # add edit rights for this site. $plusjade_user->add(ORM::factory('site', $this->site_id)); $plusjade_user->save(); # mark site as claimed. database it as well. yaml::edit_site_value($this->site_name, 'site_config', 'claimed', 'TRUE'); $site = ORM::factory('site', $this->site_id); $site->claimed = 'yes'; $site->save(); # setup the auth session. $this->client->force_login($plusjade_user); # FYI: this might log some newly created "account_user" out. $this->account_user->logout(); die('<div class="success">Thanks! This website has been claimed and added to your account.</div>'); } die('<div class="error">Invalid username or password</div>'); }
private function serialize() { yaml::write($this->file_path, $this->data); }
private function save_page_cache() { # never save an admin view of a page. if ($this->client->can_edit($this->site_id)) { return FALSE; } if (!$this->save_page_as) { return FALSE; } if (file_exists("{$this->page_cache_dir}/{$this->save_page_as}.html") and !$this->save_page_force) { return FALSE; } # cannot save a protected (dynamic) page. if ($this->page_name) { if (yaml::does_key_exist($this->site_name, 'pages_config', $this->page_name)) { return FALSE; } } if (!is_dir("{$this->page_cache_dir}")) { mkdir("{$this->page_cache_dir}"); } $date = date('m.d.y g:ia e'); file_put_contents("{$this->page_cache_dir}/{$this->save_page_as}.html", $this->template->render() . "\n<!-- cached {$date} -->"); return TRUE; }
$urls[] = $param; s::set('stats', $urls); } require_once __DIR__ . DS . '../widgets/stats/helpers.php'; $stats = getPage(); // Get data $data = $stats->pages()->yaml(); $dates = $stats->dates()->yaml(); $date = date($date_format); if ($data == null) { $data = array(); } if ($dates == null) { $dates = array(); } // calculate new values $val = array_key_exists($param, $data) ? (int) $data[$param]['count'] + 1 : 1; $today = array_key_exists($date, $dates) ? (int) $dates[$date]['count'] + 1 : 1; $total = !$stats->total_stats_count()->isEmpty() ? $stats->total_stats_count()->int() + 1 : 1; // update arrays $data[$param] = array('count' => $val); $dates[$date] = array('count' => $today); // keep only the last $days days $dates = array_slice($dates, $days * -1, $days, true); try { $stats->update(array('pages' => yaml::encode($data), 'dates' => yaml::encode($dates), 'total_stats_count' => $total)); } catch (Exception $e) { echo $e->getMessage(); exit; } //}
/** * Setter and getter for the file content * * @param string $content * @return string */ public function content($content = null, $format = null) { if (!is_null($content)) { if (is_array($content)) { switch ($format) { case 'json': $content = json_encode($content); break; case 'yaml': $content = yaml::encode($content); break; default: $content = serialize($content); break; } } else { if (is_object($content)) { $content = serialize($content); } } return $this->content = $content; } if (is_null($this->content)) { $this->content = file_get_contents($this->root); } return $this->content; }
public function toYaml() { return trim(yaml::encode($this->toArray())); }
/** * set some sitewide settings */ public function settings() { if (!$this->client->can_edit($this->site_id)) { die('Please login'); } $site = ORM::factory('site', $this->site_id); if (!$site->loaded) { die('site not found'); } if ($_POST) { $homepage = explode(':', $_POST['homepage']); $site->custom_domain = $_POST['custom_domain']; $site->homepage = $homepage[0]; $site->save(); # should we publish the entire site? if (isset($_POST['publish']) and 'yes' == $_POST['publish']) { $cache_dir = DATAPATH . "{$this->site_name}/cache"; if (is_dir($cache_dir)) { Jdirectory::remove($cache_dir); } mkdir($cache_dir); } # update site_config.yml if new homepage # and force page to be enabled. if ($this->homepage != $homepage[0]) { yaml::edit_site_value($this->site_name, 'site_config', 'homepage', $_POST['homepage']); $page = ORM::factory('page', $homepage[1]); $page->enable = 'yes'; $page->save(); } die('Sitewide settings saved.'); } $pages = ORM::factory('page')->where('fk_site', $this->site_id)->orderby('page_name')->find_all(); $primary = new View('admin/settings'); $primary->pages = $pages; $primary->custom_domain = $site->custom_domain; $primary->js_rel_command = 'close-base'; die($primary); }
/** * After a successful transaction, update product stock * * $txn page object */ function updateStock($txn) { foreach ($txn->products()->toStructure() as $i => $item) { $product = page($item->uri()); $variants = $product->variants()->yaml(); foreach ($variants as $key => $variant) { if (str::slug($variant['name']) === $item->variant()->value) { if ($variant['stock'] === '') { // Unlimited stock $variants[$key]['stock'] = ''; } else { // Limited stock $variants[$key]['stock'] = intval($variant['stock']) - intval($item->quantity()->value); } // Update the entire variants field (only one variant has changed) $product->update(array('variants' => yaml::encode($variants))); } } } }
try { // Make sure we're on a product page if ($page->template() !== 'product') { return true; } // Numeric stock, price and sale price $variants = $page->variants()->yaml(); foreach ($variants as $key => $variant) { if (!is_numeric($variant['price'])) { $variants[$key]['price'] = preg_replace('/[^0-9.]/', '', $variant['price']); } if (!is_numeric($variant['sale_price'])) { $variants[$key]['sale_price'] = preg_replace('/[^0-9.]/', '', $variant['sale_price']); } if (!is_numeric($variant['stock'])) { $variants[$key]['stock'] = preg_replace('/[^0-9.]/', '', $variant['stock']); } } // Numeric tax rates $taxes = $page->tax()->yaml(); foreach ($taxes as $key => $tax) { if (!is_numeric($tax['rate'])) { $taxes[$key]['rate'] = preg_replace('/[^0-9.]/', '', $tax['rate']); } } // Save changes $page->update(['variants' => yaml::encode($variants), 'tax' => yaml::encode($taxes)]); } catch (Exception $e) { return response::error($e->getMessage()); } });
<?php if (!defined('DS')) { define('DS', DIRECTORY_SEPARATOR); } /* --------------------------------------- License Setup --------------------------------------- Please add your license key, which you've received via email after purchasing Kirby on http://getkirby.com/buy It is not permitted to run a public website without a valid license key. Please read the End User License Agreement for more information: http://getkirby.com/license */ c::set('license', yaml::read(detect::documentRoot() . DS . 'secrets.yml')['licenses']['kirby']); /* --------------------------------------- Kirby Configuration --------------------------------------- By default you don't have to configure anything to make Kirby work. For more fine-grained configuration of the system, please check out http://getkirby.com/docs/advanced/options */ c::set('markdown.extra', true); c::set('smartypants', true);
/** * Parses yaml structured text * * @param string $text * @return string parsed text */ function yaml($string) { return yaml::decode($string); }
public function value() { $value = parent::value(); return yaml::decode($value); }
protected function updateMethodPage($method, $methodPage) { try { $methodPage->update(array('title' => $method['name'], 'excerpt' => $method['excerpt'], 'call' => $method['call'], 'return' => yaml::encode($method['return']), 'params' => yaml::encode($method['params']))); var_dump($methodPage->uri() . ' has been updated'); } catch (Exception $e) { var_dump($e->getMessage()); } }
public static function _tool_adder($tool_id, $site_id, $sample = FALSE) { # add account_page name to site_config. # HACK, this won't work if the page name is changed. need to pass page_name. yaml::edit_site_value($site_name, 'site_config', 'account_page', 'account'); # other tools may depend on this admin user being logged in at site creation! if ($sample) { # add an admin user. $account_user = ORM::factory('account_user'); $account_user->fk_site = $site_id; $account_user->email = '*****@*****.**'; $account_user->username = '******'; $account_user->password = '******'; $account_user->save(); } }
// loop through all fields and add them to the content foreach ($fields as $field) { $pos = strpos($field, ':'); $key = str_replace(array('-', ' '), '_', strtolower(trim(substr($field, 0, $pos)))); // Don't add fields with empty keys if (empty($key)) { continue; } $data[$key] = trim(substr($field, $pos + 1)); } return $data; }); /** * PHP serializer adapter */ data::$adapters['php'] = array('extension' => array('php'), 'encode' => function ($array) { return '<?php ' . PHP_EOL . PHP_EOL . 'return ' . var_export($array, true) . PHP_EOL . PHP_EOL . '?>'; }, 'decode' => function ($string) { throw new Error('Decoding PHP strings is not supported'); }, 'read' => function ($file) { $array = (require $file); return $array; }); /** * YAML adapter */ data::$adapters['yaml'] = array('extension' => array('yaml', 'yml'), 'encode' => function ($data) { return yaml::encode($data); }, 'decode' => function ($string) { return yaml::decode($string); });
if ($func == 'dump-schema') { $table = $argv[2]; echo yaml::schema_to_yaml($table); } if ($func == 'load-schema') { $table = $argv[2]; echo yaml::load_schema_from_yaml($table); } if ($func == 'drop-table') { $table = $argv[2]; echo yaml::drop_table($table); } if ($func == 'convert-table') { $source = $argv[2]; $target = $argv[3]; echo yaml::convert_table($source, $target); } if ($func == 'dump-to-screen') { $table = $argv[2]; $renderer = new ArrayToTextTable((array) yaml::dump_to_screen($table)); $renderer->showHeaders(true); $renderer->render(); echo "\r\n"; } if ($func == '' or $func == 'help') { echo "dump-schema <tablename> \r\n"; echo "load-schema <tablename> \r\n"; echo "drop-table <tablename> \r\n"; echo "convert-table <source> <target> \r\n"; echo "dump-to-screen <table>\r\n"; }