public function __construct($name, $data = false) { if ($data instanceof WaxModelField) { $this->bound_data = $data; if ($this->show_label && !$this->bound_data->label) { $this->bound_data->label = Inflections::humanize($this->bound_data->field); } } else { $this->defaults["name"] = $name; $this->defaults["id"] = $name; if ($this->show_label) { $this->defaults["label"] = Inflections::humanize($name); } $settings = array_merge($this->defaults, (array) $data); foreach ($settings as $set => $val) { $this->{$set} = $val; } $this->value = $this->value(); } /** * the validation details */ $this->setup_validations(); $this->validation_classes(); }
public function __construct($name, $data = false) { if ($data instanceof WaxModelField) { $this->bound_data = $data; } elseif (is_array($data)) { $this->defaults["name"] = $name; $this->defaults["id"] = $name . "_id"; $this->defaults["label"] = Inflections::humanize($name); $settings = array_merge($this->defaults, $data); foreach ($settings as $datum => $value) { $this->{$datum} = $value; } } else { $this->name = $name; $this->id = $name . "_id"; $this->editable = true; $this->label = Inflections::humanize($name); } /** * the validation details */ $this->validator = new WaxValidate($this, $name); if (is_array($data) && isset($data['validate']) && is_array($data['validate'])) { foreach ($data['validate'] as $type) { $this->validator->validate($type, $data); } } elseif (is_array($data) && $data['validate']) { $this->validator->validate($data['validate'], $data); } }
/** * Returns an inflector for the specified locale. * * Note: Inflectors are shared for the same locale. If you need to alter an inflector you * MUST clone it first. * * @param string $locale * * @return \ICanBoogie\Inflector */ public static function get($locale = self::DEFAULT_LOCALE) { if (isset(self::$inflectors[$locale])) { return self::$inflectors[$locale]; } return self::$inflectors[$locale] = new static(Inflections::get($locale)); }
/** * Returns an inflector for the specified locale. * * Note: Inflectors are shared for the same locale. If you need to alter an inflector you * MUST clone it first. * * @param string $locale * * @return \ICanBoogie\Inflector */ public static function get($locale = 'en') { if (isset(self::$inflectors[$locale])) { return self::$inflectors[$locale]; } return self::$inflectors[$locale] = new static(Inflections::get($locale)); }
public function handle_error() { if ($email = self::$email_on_error) { mail($email, self::$email_subject_on_error, $this->cli_error_message); } if ($location = self::$redirect_on_error) { error_log($this->cli_error_message); if (!self::$double_redirect) { self::$double_redirect = true; header("HTTP/1.1 500 Application Error", 1, 500); if (is_readable(PUBLIC_DIR . ltrim($location, "/"))) { $content = file_get_contents(PUBLIC_DIR . ltrim($location, "/")); ob_end_clean(); foreach (self::$replacements as $value => $replace) { $content = str_ireplace($replace, $this->{$value}, $content); } echo $content; exit; } $_GET["route"] = $location; $delegate = Inflections::slashcamelize(WaxUrl::get("controller"), true) . "Controller"; $delegate_controller = new $delegate(); $delegate_controller->execute_request(); exit; } } header("Status: 500 Application Error"); echo $this->error_message; exit; }
public function standalone_partial() { if (!$this->routed_controller && WaxUrl::$params["controller"]) { $controller = WaxUrl::$params["controller"]; } else { if (!$this->routed_controller) { $controller = WaxUrl::$default_controller; } else { $controller = $this->routed_controller; } } $delegate = Inflections::slashcamelize($controller, true) . "Controller"; $p_controller = new $delegate(); $p_controller->controller = $controller; $p_controller->use_layout = false; $p_controller->use_format = $this->format; if (strpos($this->path, "/")) { $partial = substr($this->path, strrpos($this->path, "/") + 1); $path = substr($this->path, 0, strrpos($this->path, "/") + 1); $path = $path . $partial; } else { $partial = $this->path; } if (is_array($this->data)) { foreach ($this->data as $var => $val) { $p_controller->{$var} = $val; } } $p_controller->use_view = $partial; if ($p_controller->is_public_method($p_controller, $partial)) { $p_controller->{$partial}(); } $this->output = $p_controller->render_view(); }
/** * constructor * @param mixed param PDO instance, * or record id (if integer), * or constraints (if array) but param['pdo'] is PDO instance */ function __construct($params = null) { try { if (!static::$db && static::$adapter) { static::$db = new static::$adapter(static::$db_settings); } } catch (Exception $e) { throw new WaxDbException("Cannot Initialise DB", "Database Configuration Error"); } $class_name = get_class($this); if ($class_name != 'WaxModel' && !$this->table) { $this->table = Inflections::underscore($class_name); } $this->define($this->primary_key, $this->primary_type, $this->primary_options); $this->setup(); $this->set_identifier(); // If a scope is passed into the constructor run a method called scope_[scope](). if ($params) { $method = "scope_" . $params; if (method_exists($this, $method)) { $this->{$method}; } else { $res = $this->filter(array($this->primary_key => $params))->first(); $this->row = $res->row; $this->clear(); } } }
public function error_messages_for($object) { if ($object instanceof WaxForm) { if ($object->bound_to_model) { if ($object->bound_to_model->errors) { $html = "<ul class='user_errors'>"; } foreach ($object->bound_to_model->errors as $err => $mess) { $html .= "<li>" . $mess[0]; } } else { foreach ($object->elements as $el) { foreach ($el->errors as $er) { $html .= sprintf($er->error_template, $er); } } } $html .= "</ul>"; return $html; } if (strpos($object, "_")) { $object = camelize($object, 1); } $class = new $object(); $errors = $class->get_errors(); foreach ($errors as $error) { $html .= $this->content_tag("li", Inflections::humanize($error['field']) . " " . $error['message'], array("class" => "user_error")); } if (count($errors) > 0) { return $this->content_tag("ul", $html, array("class" => "user_errors")); } return false; }
/** * the setup function for this field is different, as this is a many to many relationship it takes into * account both sides of the relationship, initialises the join table if its missing and preps the * filter */ public function setup() { $this->col_name = false; if (!$this->target_model) { $this->target_model = Inflections::camelize($this->field, true); } if ($this->model->primval) { $this->setup_join_model(); } }
public function setup() { $this->col_name = false; $class_name = get_class($this->model); if (!$this->target_model) { $this->target_model = Inflections::camelize($this->field, true); } if (!$this->join_field) { $this->join_field = Inflections::underscore($class_name) . "_" . $this->model->primary_key; } }
/** * Create four routes for the given controller. * * index, edit, create, delete * * @param string $name * @param string $controller * @return void * @author Justin Palmer */ function resources($name, $controller) { $path = '/' . $name; $this->add($name, $path, $controller, 'index'); $this->add(Inflections::singularize($name), $path . '/{id}', $controller, 'view'); $this->add('edit-' . Inflections::singularize($name), $path . '/{id}/edit', $controller, 'edit'); $this->add('update-' . Inflections::singularize($name), $path . '/{id}/update', $controller, 'update'); $this->add('new-' . Inflections::singularize($name), $path . '/new', $controller, 'init'); $this->add('create-' . Inflections::singularize($name), $path . '/create', $controller, 'create'); $this->add('delete-' . Inflections::singularize($name), $path . '/{id}/delete', $controller, 'delete'); }
public function setup() { if (!$this->target_model) { $this->target_model = Inflections::camelize($this->field, true); } $link = new $this->target_model(); // Overrides naming of field to model_id if col_name is not explicitly set if ($this->col_name == $this->field) { $this->col_name = Inflections::underscore($this->target_model) . "_" . $link->primary_key; } }
/** * new function to return a default array of settings for any * new element added via define / add_element * main purpose is to prefix name attribute and ids with form_prefix * to make them unique */ public function element_settings($name, $settings = array()) { if (!$settings['post_fields']) { $settings['post_fields']['model'] = $this->form_prefix; $settings['post_fields']['attribute'] = $name; } if (!$settings['label']) { $settings['label'] = ucwords($name); } if (!$settings['id']) { $settings['id'] = $settings['post_fields']['model'] . "_" . Inflections::underscore($name); } return $settings; }
function __construct($params = null) { if (self::$adapter && !($this->db = new self::$adapter(self::$db_settings))) { throw new WaxDbException("Cannot Initialise API Connection", "Database Configuration Error"); } $class_name = get_class($this); if ($class_name != 'WaxModel' && !$this->table) { $this->table = Inflections::underscore($class_name); } if ($params && is_string($params)) { //set the primary key to the right value; $this->{$this->primary_key} = $params; } $this->define($this->primary_key, $this->primary_type, $this->primary_options); $this->setup(); $this->set_identifier(); }
/** * Partial Helper Function * Renders a partial from path $path into the current view * To inherit an existing view use this method: eg..... * * <?=partial("mypartial", $this);?> * * Alternate syntax allows standalone execution that runs the partialname() method * <?=partial("mypartial")?> * * @param string $path * @param array $extra_vals * @param string $format */ public function partial($path, $extra_vals = array(), $format = "html") { $controller = WaxUrl::route_controller($path); $cache = new WaxCache($_SERVER['HTTP_HOST'] . md5($path . $_SERVER['REQUEST_URI'] . serialize($_GET)) . '.partial'); if (count($_POST)) { $cache->expire(); } if (Config::get('partial_cache') && !substr_count($path, "admin") && !substr_count(strtolower($controller), "admin") && $cache->valid()) { $partial = $cache->get(); } else { if ($extra_vals instanceof WaxTemplate) { $old_template_paths = $extra_vals->template_paths; foreach ($extra_vals as $var => $val) { $this->{$var} = $val; } $view = new WXTemplate(); if (count($extra_vals->plugins) > 0) { foreach ($old_template_paths as $template) { $view->add_path(str_replace($extra_vals->use_view, $path, $template)); } } $view->add_path(VIEW_DIR . $path); foreach ($this as $var => $val) { if (!$view->{$var}) { $view->{$var} = $val; } } $view->add_path(VIEW_DIR . $view->controller . "/" . $path); $partial = $view->parse($format, "partial"); } else { if (!$controller) { $controller = WaxUrl::$default_controller; } $delegate = Inflections::slashcamelize($controller, true); $delegate .= "Controller"; $delegate_controller = new $delegate(); $delegate_controller->controller = $controller; $partial = $delegate_controller->execute_partial($path, $format); } } if (Config::get('partial_cache') && !substr_count($controller, "admin")) { $cache->set($partial); } return $partial; }
public function __construct($column, $model, $options = array()) { $this->model = $model; foreach ($options as $option => $val) { $this->{$option} = $val; } if (!$this->field) { $this->field = $column; } if (!$this->table) { $this->table = $this->model->table; } if (!$this->col_name) { $this->col_name = $this->field; } if ($this->label === true) { $this->label = Inflections::humanize($this->field); } $this->errors = $this->model->errors[$this->field]; $this->setup(); $this->map_choices(); $this->validator = new $this->validator($this->model, $this->field, $this->label); }
function __construct($message, $code = "Page cannot be found", $status = "404") { if ($location = self::$redirect_on_error) { $this->error_heading = $code; $this->error_message = $this->format_trace($this); $this->error_site = str_ireplace("www.", '', $_SERVER['HTTP_HOST']); $this->error_site = substr($this->error_site, 0, strpos($this->error_site, '.')); $this->error_site_name = ucwords(Inflections::humanize($this->error_site)); $this->simple_routing_error_log(); if (!self::$double_redirect) { self::$double_redirect = true; header("HTTP/1.1 404 Not Found", 1, 404); if (is_readable(PUBLIC_DIR . ltrim($location, "/"))) { $content = file_get_contents(PUBLIC_DIR . ltrim($location, "/")); foreach (self::$replacements as $value => $replace) { $content = str_ireplace($replace, $this->{$value}, $content); } ob_end_clean(); echo $content; exit; } $_GET["route"] = $location; WaxUrl::$params = false; WaxUrl::perform_mappings(); $delegate = Inflections::slashcamelize(WaxUrl::get("controller"), true) . "Controller"; $delegate_controller = new $delegate(); $delegate_controller->execute_request(); exit; } else { WaxLog::log("error", "[Routing] Double redirect error"); $code = "Application Error"; $message = "A Page not found error was triggered and you have not set up a page to handle it"; } } parent::__construct($message, $code); }
/** * Return the ElasticSearch type * * @return string type name */ public static function getElasticSearchType() { $cls = get_called_class(); return Util::decamelize(Inflections::pluralize($cls)); }
/** * Push an objet to a has many association * * @param mixed $obj object * * @return pushed */ public function push($obj) { if (!$obj) { return; } $cls = get_called_class(); $escape = Driver::$escape_char; $value = array_key_exists(self::getPK(), $this->_data) ? $this->_data[self::getPK()] : null; $other_cls = get_class($obj); $other_pk = $other_cls::getPK(); $other_value = $obj->get($other_pk); $table = Model::getTableName($other_cls); $foreign = self::hasManyForeignKey(Inflections::pluralize(strtolower($other_cls))); // if the current object exists ... if (!is_null($value)) { $obj->set(strtolower($foreign), $value); // if the pushed object is still not saved if (is_null($other_value)) { if (!$obj->save()) { return false; } $other_value = $obj->get($other_pk); } $foreign = self::$_mapping[$other_cls][$foreign]; $other_pk = self::$_mapping[$other_cls][$other_pk]; $sql = "update {$escape}{$table}{$escape} set {$escape}{$foreign}{$escape}={$value} where {$escape}{$other_pk}{$escape}={$other_value}"; $stmt = self::query($sql); $rst = $stmt->rowCount() == 1; self::closeCursor($stmt); return $rst; } // if current object does not exists ... if (is_null($value)) { $this->_pushLater($obj); } }
/** * Add the relationship * * @return Schema * @author Justin Palmer **/ private function addRelationship($name, $type) { $options = new stdClass(); $options->name = $name; $options->type = $type; $options->alias = Inflections::underscore(str_replace('-', '_', $name)); $options->table = Inflections::tableize($options->alias); $options->foreign_key = Inflections::foreignKey(Inflections::singularize($this->model->table_name())); $this->relationships->set($name, $options); $options->on = $this->autoGenerateOn($name); $this->relationships->set($name, $options); return $this; }
/** * Find by primary key * * @todo No Builder direct access to conditions * @return void * @author Justin Palmer **/ public function find($id = null) { if ($id == null) { $primary_key = $this->model->primary_key(); if ($this->model->{$primary_key} == null) { throw new Exception('Model::find did not receive an id and the model does not have the id.'); } else { $id = $this->model->{$primary_key}; } } $database_name = $this->model->database_name(); $table_name = $this->model->table_name(); $primary_key = $this->model->alias() . '.' . $this->model->primary_key(); $primary = " ({$primary_key} = ?)"; if (!empty($this->builder->conditions)) { $and = $this->builder->conditions[0] != '' ? ' AND' : ''; $this->builder->conditions[0] = $this->builder->conditions[0] . $and . $primary; } else { $this->builder->conditions[] = $primary; } $this->builder->conditions[] = $id; $query = $this->builder->build("SELECT ? FROM `{$database_name}`.`{$table_name}`"); $this->builder->reset(); $this->Statement = $this->prepare(array_shift($query->query)); $params = $query->params; $this->Statement->execute($query->params); try { //$model = get_class($this->model); $result = ResultFactory::factory($this->Statement); foreach ($query->query as $key => $query) { //print $key; $key = Inflections::pluralize($key); $stmt = $this->prepare($query); //print $stmt->queryString . "<br/>"; //var_dump($query->params); $stmt->execute($params); $result->{$key} = ResultFactory::factory($stmt, true); } } catch (RecordNotFoundException $e) { throw $e; } return $result; }
public function file() { return $this->cache_dir . Inflections::underscore(Inflections::slashcamelize($this->label)) . ".cache"; }
public function get_templates($action) { $view = Inflections::underscore(get_class($this)) . "/" . $action; $view_path = new WaxTemplate($this); $view_path->add_path(VIEW_DIR . $view); $view_path->add_path(PLUGIN_DIR . "cms/view/" . $view); foreach ($view_path->template_paths as $path) { if (is_readable($path . ".html")) { $html = $view_path->parse(); } if (is_readable($path . ".txt")) { $txt = $view_path->parse("txt"); } } if ($html && $txt) { $this->is_html(true); $this->body = $html; $this->alt_body = $txt; } elseif ($html) { $this->is_html(true); $this->content_for_layout = $html; if ($content = $this->render_layout()) { $this->body = $content; } else { $this->body = $this->content_for_layout; } } elseif (!$html && $txt) { $this->body = $txt; } }
/** * Change a table name into a class name * * @return string * @author Justin Palmer **/ public static function classify($string) { $string = Inflections::singularize($string); $string = str_replace('_', ' ', $string); return str_replace(' ', '', ucwords($string)); }
public function dealer_creation() { $class = CONTENT_MODEL; $dealer_class = get_class($this); $model = new $class("live"); $url = $dealer_class::$dealer_section . Inflections::to_url($this->title) . "/"; if (($pages = $this->pages) && $pages->count() || $model->filter("permalink", $url)->first()) { return true; } else { //find dealers section if ($dealers = $model->filter("permalink", $dealer_class::$dealer_section)->first()) { $model = $model->clear(); //create the first level of this dealer $dealer_data = array('title' => $this->title, 'layout' => 'dealer', 'page_type' => $dealer_class::$dealer_homepage_partial, 'content' => $this->content, 'parent_id' => $dealers->primval); //create the dealer skel if ($saved = $model->update_attributes($dealer_data)) { $saved = $saved->generate_permalink()->map_live()->children_move()->show()->save(); $saved->dealers = $this; $this->pages = $saved; $subs = array(); //copy the national main pages $i = 0; foreach ($dealer_class::$dealer_top_pages as $title => $skel) { $look = new $class("live"); if ($found = $look->filter("permalink", $skel)->first()) { $info = $found->row; unset($info['id'], $info['permalink']); $info['parent_id'] = $saved->primval; $info['sort'] = $i; //custom names if (!is_numeric($title)) { $info['title'] = $title; } else { $info['title'] = str_replace("Latest ", "", $info['title']); } $info['dealer_content_id'] = $found->primval; $subs[] = $page = $look->update_attributes($info)->generate_permalink()->map_live()->children_move()->show()->save(); //manytomany copy foreach ($found->columns as $name => $info) { if ($info[0] == "ManyToManyField") { foreach ($found->{$name} as $assoc) { $page->{$name} = $assoc; } } } $i++; } } foreach ($dealer_class::$dealer_extra_pages as $info) { $pg = new $class(); $info['parent_id'] = $saved->primval; $info['date_start'] = date("Y-m-d", strtotime("now-1 day")); $info['sort'] = $i; $extras[] = $pg->update_attributes($info)->generate_permalink()->map_live()->children_move()->show()->save(); $i++; } } } $class = get_class($this); WaxEvent::run($class . ".dealer_creation", $this); } return array("subs" => $subs, "extras" => $extras); }
public function file_upload() { if ($url = $_POST["upload_from_url"]) { $str = ""; foreach ($_POST as $k => $v) { $str .= "{$k}:{$v}\n"; } WaxLog::log('error', 'running...' . $str); $path = $_POST['wildfire_file_folder']; $fs = new CmsFilesystem(); $filename = basename($url); $ext = strtolower(array_pop(explode(".", $filename))); if ($_POST["wildfire_file_filename"]) { $filename = $_POST["wildfire_file_filename"] . "." . $ext; } $filename = $_POST["wildfire_file_filename"] = File::safe_file_save($fs->defaultFileStore . $path, $filename); $file = $fs->defaultFileStore . $path . "/" . $filename; $handle = fopen($file, 'x+'); fwrite($handle, file_get_contents($url)); fclose($handle); $fname = $fs->defaultFileStore . $path . "/" . $filename; chmod($fname, 0777); $dimensions = getimagesize($fname); if (AdminFilesController::$max_image_width && $dimensions[0] > AdminFilesController::$max_image_width) { $flag = File::resize_image($fname, $fname, AdminFilesController::$max_image_width, false, true); if (!$flag) { WaxLog::log('error', '[resize] FAIL'); } } $fs->databaseSync($fs->defaultFileStore . $path, $path); $file = new WildfireFile(); $newfile = $file->filter(array("filename" => $filename, "rpath" => $path))->first(); $newfile->description = $_POST["wildfire_file_description"]; $newfile->save(); //if these are set then attach the image to the doc! if (Request::post('content_id') && Request::post('model_string') && Request::post('join_field')) { $model_id = Request::post('content_id'); $class = Inflections::camelize(Request::post('model_string'), true); $field = Request::post('join_field'); $model = new $class($model_id); $model->{$field} = $newfile; } echo "Uploaded"; } elseif ($_FILES) { error_log("Starting File upload"); error_log(print_r($_POST, 1)); $path = $_POST['wildfire_file_folder']; $fs = new CmsFilesystem(); $_FILES['upload'] = $_FILES["Filedata"]; $_FILES['upload']['name'] = str_replace(' ', '', $_FILES['upload']['name']); $fs->upload($path); $fs->databaseSync($fs->defaultFileStore . $path, $path); $fname = $fs->defaultFileStore . $path . "/" . $_FILES['upload']['name']; if ($dimensions = getimagesize($fname)) { if ($dimensions[2] == "7" || $dimensions[2] == "8") { WaxLog::log("error", "Detected TIFF Upload"); $command = "mogrify " . escapeshellcmd($fname) . " -colorspace RGB -format jpg"; system($command); $newname = str_replace(".tiff", ".jpg", $fname); $newname = str_replace(".tif", ".jpg", $newname); rename($fname, $newname); } } chmod($fname, 0777); $file = new WildfireFile(); $newfile = $file->filter(array("filename" => $_FILES['upload']['name'], "rpath" => $path))->first(); $newfile->description = $_POST["wildfire_file_description"]; $newfile->save(); //if these are set then attach the image to the doc! if (Request::post('content_id') && Request::post('model_string') && Request::post('join_field')) { $model_id = Request::post('content_id'); $class = Inflections::camelize(Request::post('model_string')); $field = Request::post('join_field'); $model = new $class($model_id); $model->{$field} = $newfile; } echo "Uploaded"; } else { die("UPLOAD ERROR"); } exit; }
protected function is_controller($test) { $path = ""; if (strpos($test, "/")) { $path = substr($test, 0, strpos($test, "/") + 1); } if (is_file(CONTROLLER_DIR . $path . Inflections::slashcamelize($test, true) . "Controller.php")) { return true; } if (is_file(FRAMEWORK_DIR . "/dispatch/" . Inflections::slashcamelize($test, true) . "Controller.php")) { return true; } return false; }
function clear($scope = "all") { if ($scope == "all") { self::$plurals = self::$singulars = self::$uncountables = self::$humans = array(); } else { self::${$scope} = array(); } }
/** * Returns the table name. * If not specified one, get the current class name and pluralize it. * * @param string $cls class name * * @return string table name */ public static function getTableName($cls = null) { $fullcls = $cls ? $cls : get_called_class(); if (array_key_exists($fullcls, self::$_table_name)) { return self::$_table_name[$fullcls]; } $cls = self::_extractClassName($fullcls); $name = Inflections::pluralize($cls); if (self::isIgnoringCase()) { $name = strtolower($name); } return $name; }
/** * Add reference to another table * * @return void * @author Justin Palmer **/ public function references($table, $options = '') { $column = Inflections::tableize($table) . '_id'; $this->integer($column, $options); $this->index($this->table, $column); }