function findCatagory($tweet) { $result = classify($tweet); print_r($result); if ($result["positive"] > $result["negative"]) { return "positive"; } else { return "negative"; } }
function findCatagory($tweet_id, $tweet) { global $positive, $negative; $result = classify($tweet); //print_r($result); //if($result["negative"]==0) //print($result["positive"]." / ".$result["negative"]); $score = $result["positive"] / $result["negative"]; if ($score > 1) { $positive[$tweet_id] = $score; } else { $negative[$tweet_id] = $score; } }
function add_model($name, $table = '', array $columns = array(), array $indexes = array(), $parent = 'database', $connection = 'default') { static $set = array('database' => '\\Servant\\Mapper\\Database', 'mongodb' => '\\Servant\\Mapper\\MongoDB'); $table = $table ?: underscore($name); $ucname = classify($name); $fields['static columns'] = $columns; $fields['static indexes'] = $indexes; $connect = compact('table', 'connection'); $out_file = path(APP_PATH, 'app', 'models', "{$name}.php"); isset($set[$parent]) && ($parent = $set[$parent]); add_class($out_file, $ucname, $parent, array(), $fields, $connect); }
function send_email_notice(&$model, &$rec) { global $db; global $request; if (!(get_profile_id() && $request->resource == 'groups')) { return; } // get data modesl for 3 tables $Entry =& $db->get_table('entries'); $Group =& $db->get_table('groups'); $Person =& $db->get_table('people'); // load the first 20 records from the groups table $Group->find(); // keep a list of people we have notified $sent_to = array(); // get the name of the table from the data model reference we received $notify_table = $model->table; // get the primary key value of the record reference we received $notify_id = $rec->id; // if the table that was modified is a metadata table (comments, reviews) // notify about the "target" table being modified if (array_key_exists('target_id', $model->field_array)) { $e = $Entry->find($rec->attributes['target_id']); if ($e) { $notify_table = $e->resource; $notify_id = $e->record_id; } } // get the data model we are notifying about $datamodel =& $db->get_table($notify_table); // get the profile data for the current user $profile = owner_of($rec); // loop over each group while ($g = $Group->MoveNext()) { if (in_array($g->name, array('administrators', 'everyone', 'members'))) { continue; } // if the GROUP has READ or CREATE then do notify its members if ($rec->id && (in_array($g->name, $datamodel->access_list['read']['id']) || in_array($g->name, $datamodel->access_list['create'][$notify_table]))) { // loop over each member in the group while ($m = $g->NextChild('memberships')) { // get a person activerecord object for the member's person_id $p = $Person->find($m->person_id); if ($p) { $action = $request->action; $notify = "notify_" . $action; // get an identities activerecord object for the person's first identity // this is an example of traversing the result dataset without re-querying $i = $p->FirstChild('identities'); // if we haven't already sent this person a message if (isset($m->{$notify}) && $m->{$notify} && is_email($i->email_value) && !in_array($i->email_value, $sent_to)) { // a token may be set to allow the notify-ee to "EXPRESS" register as a new site user // it fills in some of the "new user" form info such as e-mail address for them if (isset($i->token) && strlen($i->token) > 0) { $addr = $request->url_for(array('resource' => $notify_table, 'id' => $notify_id, 'ident' => $i->token)); } else { $addr = $request->url_for(array('resource' => $notify_table, 'id' => $notify_id)); } // this is the HTML content of the e-mail $html = ' <!DOCTYPE HTML PUBLIC \\"-//W3C//DTD HTML 4.0 Transitional//EN\\"> <html> <body> <br /> <b><u><i>Click on this link:</i></u></b><br /> <br /> <font color="red"><a href="' . $addr . '">' . $addr . '</a></font> </body> </html>'; // oh wait, we are not going to send the HTML it is just wasting space for now // comment this out to try the HTML yourself $html = false; // this is the body of the e-mail if ($html == false) $text = 'Content was updated at the following location:' . "\r\n\r\n" . $addr . "\r\n\r\n"; // change the e-mail subject line depending on what action took place if ($action == 'post') { $actionmessage = " created a new "; } elseif ($action == 'put') { $actionmessage = " updated a "; } elseif ($action == 'delete') { $actionmessage = " deleted a "; } // set the e-mail subject to the current user's first name // classify() converts a table name "nerds" to "Nerd" // the converse is tableize() $subject = $profile->given_name . $actionmessage . classify($request->resource); // this sends e-mail using the xpertmailer package // the environment() function reads a value from the config.yml file send_email($i->email_value, $subject, $text, environment('email_from'), environment('email_name'), $html); // add a new entry to the list of successful (more like woeful) recipients $sent_to[] = $i->email_value; } } } } } }
function handle_posted_file($filename = "", $att, $profile) { global $db, $request, $response; $response->set_var('profile', $profile); load_apps(); if (isset($_FILES['media']['tmp_name'])) { $table = 'uploads'; } else { $table = 'posts'; } $modelvar = classify($table); $_FILES = array(strtolower($modelvar) => array('name' => array('attachment' => $filename), 'tmp_name' => array('attachment' => $att))); $Post =& $db->model('Post'); $Upload =& $db->model('Upload'); $field = 'attachment'; $request->set_param('resource', $table); $request->set_param(array(strtolower(classify($table)), $field), $att); trigger_before('insert_from_post', ${$modelvar}, $request); $content_type = 'text/html'; $rec = ${$modelvar}->base(); $content_type = type_of($filename); $rec->set_value('profile_id', get_profile_id()); $rec->set_value('parent_id', 0); if (isset($request->params['message'])) { $rec->set_value('title', $request->params['message']); } else { $rec->set_value('title', ''); } if ($table == 'uploads') { $rec->set_value('tmp_name', 'new'); } $upload_types = environment('upload_types'); if (!$upload_types) { $upload_types = array('jpg', 'jpeg', 'png', 'gif'); } $ext = extension_for(type_of($filename)); if (!in_array($ext, $upload_types)) { trigger_error('Sorry, this site only allows the following file types: ' . implode(',', $upload_types), E_USER_ERROR); } $rec->set_value($field, $att); $rec->save_changes(); $tmp = $att; if (is_jpg($tmp)) { $thumbsize = environment('max_pixels'); $Thumbnail =& $db->model('Thumbnail'); $t = $Thumbnail->base(); $newthumb = tempnam("/tmp", "new" . $rec->id . ".jpg"); resize_jpeg($tmp, $newthumb, $thumbsize); $t->set_value('target_id', $atomentry->id); $t->save_changes(); update_uploadsfile('thumbnails', $t->id, $newthumb); $t->set_etag(); } $atomentry = ${$modelvar}->set_metadata($rec, $content_type, $table, 'id'); ${$modelvar}->set_categories($rec, $request, $atomentry); $url = $request->url_for(array('resource' => $table, 'id' => $rec->id)); // $title = substr($rec->title,0,140); // $over = ((strlen($title) + strlen($url) + 1) - 140); // if ($over > 0) // $rec->set_value('title',substr($title,0,-$over)." ".$url); // else // $rec->set_value('title',$title." ".$url); // $rec->save_changes(); trigger_after('insert_from_post', ${$modelvar}, $rec); return true; }
<?php $name = array_shift($params); if (!$name or is_numeric($name) or strpos($name, ':') !== FALSE) { error("\n Missing model name\n"); } else { $name = singular($name); $model_file = path(APP_PATH, 'app', 'models', "{$name}.php"); $model_class = arg('c class') ?: classify($name); if (!is_file($model_file) && !arg('c class')) { error("\n Missing '{$name}' model\n"); } else { is_file($model_file) && (require $model_file); $fail = FALSE; $fields = array(); $columns = $model_class::columns(); if (!empty($params)) { foreach ($params as $key) { @(list($key, $type) = explode(':', $key)); $type = $type ?: $columns[$key]['type']; if (!isset($columns[$key])) { $fail = TRUE; error("\n Unknown '{$key}' field\n"); } elseif (!($test = field_for($type, $key))) { $fail = TRUE; error("\n Unknown '{$type}' type on '{$key}' field\n"); } else { $fields[$key] = $test; } } } else {
public function load(Model $model) { $inflector = Inflector::instance(); $class_name = $this->class_name; $table = $this->get_table(); $this->set_keys(get_class($model)); if ($this->through) { $table_name = $table->get_fully_qualified_table_name(); //verify through is a belongs_to or has_many for access of keys if (!($through_relationship = $table->get_relationship($this->through))) { throw new HasManyThroughAssociationException("Could not find the association {$this->through} in model " . get_class($model)); } if (!$through_relationship instanceof HasMany && !$through_relationship instanceof BelongsTo) { throw new HasManyThroughAssociationException('has_many through can only use a belongs_to or has_many association'); } $through_table = Table::load(classify($this->through, true)); $through_table_name = $through_table->get_fully_qualified_table_name(); $through_pk = $this->keyify($class_name); $this->options['joins'] = $this->construct_inner_join_sql($through_table, true); foreach ($this->foreign_key as $index => &$key) { $key = "{$through_table_name}.{$key}"; } } if (!($conditions = $this->create_conditions_from_keys($model, $this->foreign_key, $this->primary_key))) { return null; } $options = $this->unset_non_finder_options($this->options); $options['conditions'] = $conditions; return $class_name::find($this->poly_relationship ? 'all' : 'first', $options); }
public static function execute($controller, $action = 'index', $cache = -1) { $out = \Sauce\Base::$response; $hash = md5(URI . '?' . server('QUERY_STRING') . '#' . session_id()); \Sauce\Logger::debug("Executing {$controller}#{$action}"); if ($cache > 0 && ($test = \Cashier\Base::fetch($hash))) { @(list($out->status, $out->headers, $out->response) = $test); } else { $controller_path = path(APP_PATH, 'app', 'controllers'); $controller_base = path($controller_path, 'base.php'); $controller_file = path($controller_path, "{$controller}.php"); if (!is_file($controller_file)) { throw new \Exception("Missing '{$controller_file}' file"); } is_file($controller_base) && (require $controller_base); require $controller_file; $base_name = classify(basename(APP_PATH)); $class_name = classify($controller); if (!class_exists($class_name)) { throw new \Exception("Missing '{$class_name}' class"); } $app = new $class_name(); $klass = new \ReflectionClass($app); $type = params('format'); $handle = new \Postman\Handle($app, $type); $methods = $klass->getMethods(\ReflectionMethod::IS_STATIC); foreach ($methods as $callback) { $fn = $callback->getName(); if (substr($fn, 0, 3) === 'as_') { $handle->register(substr($fn, 3), function () use($class_name, $fn) { return call_user_func_array("{$class_name}::{$fn}", func_get_args()); }); } } $test = $handle->exists($action) ? $handle->execute($action) : array(); $vars = (array) $class_name::$view; $params = $klass->getStaticProperties(); if ($type) { if (!in_array($type, $params['responds_to'])) { throw new \Exception("Unknown response for '{$type}' type"); } \Sauce\Logger::debug("Using response for '{$type}' type"); if (isset($test[2])) { $test = $handle->responds($test[2], $params); } else { $test = array(202, array(), ''); } } @(list($out->status, $out->headers, $out->response) = $test); $params['status'] && ($out->status = (int) $params['status']); $params['headers'] && ($out->headers = (array) $params['headers']); if ($out->response === NULL) { \Sauce\Logger::debug("Rendering view {$controller}/{$action}.php"); $out->response = partial("{$controller}/{$action}.php", $vars); if ($params['layout']) { \Sauce\Logger::debug("Using layout layouts/{$params['layout']}.php"); $layout_file = "layouts/{$params['layout']}.php"; $out->response = partial($layout_file, array('head' => join("\n", $params['head']), 'title' => $params['title'], 'body' => $out->response, 'view' => $vars)); } } if ($cache > 0) { \Sauce\Logger::debug("Caching for {$cache} seconds ({$controller}#{$action})"); \Cashier\Base::store($hash, array($out->status, $out->headers, $out->response), $cache); } } return $out; }
function get_query($id = NULL, $find_by = NULL, &$model) { if (isset($model->query)) { $q = $model->query; unset($model->query); return $q; } $model->set_param('id', $id); $model->set_param('find_by', $find_by); trigger_before('get_query', $model, $this); $pkfield = $model->primary_key; if ($model->find_by == NULL) { $model->set_param('find_by', $model->primary_key); } $relfields = array(); $relfields = $model->relations; $table = $this->prefix . $model->table; $fieldstring = ''; $sql = "SELECT " . "\n"; if (!array_key_exists($pkfield, $model->field_array)) { $sql .= "{$table}.{$pkfield} as \"{$table}.{$pkfield}\", " . "\n"; } foreach ($model->field_array as $fieldname => $datatypename) { if (strpos($fieldname, ".") === false) { $fieldname = $table . "." . $fieldname; } $fieldstring .= "{$fieldname} as \"{$fieldname}\", " . "\n"; } $leftsql = ""; $first = true; if (count($relfields) > 0) { foreach ($relfields as $key => $val) { $spl = split("\\.", $val["fkey"]); if (!$this->models[$spl[0]]->exists) { ${$spl}[0] =& $this->get_table($spl[0]); } $leftsql .= "("; } foreach ($relfields as $key => $val) { $spl = split("\\.", $val["fkey"]); if ($val["type"] == 'child-many') { $join =& $this->get_table($model->join_table_for($table, $val['tab'])); $spl[0] = $this->prefix . $join->table; $val["fkey"] = $this->prefix . $join->table . '.' . strtolower(classify($table)) . "_" . $model->foreign_key_for($table); } else { foreach ($this->models[$spl[0]]->field_array as $fieldname => $datatypename) { $fieldstring .= $this->prefix . $spl[0] . "." . $fieldname . " as \"" . $this->prefix . $spl[0] . "." . $fieldname . "\", " . "\n"; } } if ($first) { $leftsql .= $table; } $leftsql .= " left join " . $this->prefix . $spl[0] . " on " . $table . "." . $val["col"] . " = " . $val["fkey"]; $leftsql .= ")"; $first = false; } } $fieldstring = substr($fieldstring, 0, -3) . " " . "\n"; $sql .= $fieldstring; $sql .= "FROM "; $sql .= $leftsql; if (!(strlen($leftsql) > 1)) { $sql .= $table; } if (is_array($model->find_by)) { $findfirst = true; $op = "AND"; $eq = '='; foreach ($model->find_by as $col => $val) { if (is_array($val)) { list($col, $val) = each($val); } if ($col == 'op') { $op = $val; } elseif ($col == 'eq') { $eq = $val; } else { if (strpos($col, ".") === false) { $field = "{$table}.{$col}"; } else { $field = $this->prefix . $col; } if ($findfirst) { $sql .= " WHERE {$field} {$eq} '{$val}' "; } else { $sql .= " {$op} {$field} {$eq} '{$val}' "; } $findfirst = false; } } } elseif ($model->id != NULL) { if (strpos($model->find_by, ".") === false) { $field = $table . "." . $model->find_by; } else { $field = $model->find_by; } $sql .= " WHERE {$field} = '" . $model->id . "' "; } if (!isset($model->orderby)) { $model->orderby = $table . "." . $pkfield; } if (!isset($model->order)) { $model->order = "DESC"; } if (!isset($model->offset)) { $model->offset = 0; } if (!isset($model->limit)) { $model->limit = 20; } if (isset($model->groupby)) { $sql .= " GROUP BY " . $model->groupby . " "; } $sql .= " ORDER BY " . $model->orderby . " "; $sql .= $model->order . $this->query_limit($model->limit, $model->offset); trigger_after('get_query', $model, $this); return $sql; }
/** * Infers the $this->className based on $this->attributeName. * * Will try to guess the appropriate class by singularizing and uppercasing $this->attributeName. * * @return void * @see attribute_name */ protected function setInferredClassName() { $singularize = $this instanceof HasMany ? true : false; $this->setClassName(classify($this->attributeName, $singularize)); }
public function load(Model $model) { $class_name = $this->class_name; $this->set_keys(get_class($model)); // since through relationships depend on other relationships we can't do // this initiailization in the constructor since the other relationship // may not have been created yet and we only want this to run once if (!isset($this->initialized)) { if ($this->through) { // verify through is a belongs_to or has_many for access of keys if (!($through_relationship = $this->get_table()->get_relationship($this->through))) { throw new HasManyThroughAssociationException("Could not find the association {$this->through} in model " . get_class($model)); } if (!$through_relationship instanceof HasMany && !$through_relationship instanceof BelongsTo) { throw new HasManyThroughAssociationException('has_many through can only use a belongs_to or has_many association'); } // save old keys as we will be reseting them below for inner join convenience $pk = $this->primary_key; $fk = $this->foreign_key; $this->set_keys($this->get_table()->class->getName(), true); $through_table = Table::load(classify($this->through, true)); $this->options['joins'] = $this->construct_inner_join_sql($through_table, true); // reset keys $this->primary_key = $pk; $this->foreign_key = $fk; } $this->initialized = true; } if (!($conditions = $this->create_conditions_from_keys($model, $this->foreign_key, $this->primary_key))) { return null; } $options = $this->unset_non_finder_options($this->options); $options['conditions'] = $conditions; return $class_name::find($this->poly_relationship ? 'all' : 'first', $options); }
<?php echo '<' . '?php'; ?> class Home extends \<?php echo classify($app_name); ?> \App\Base { }
if (isset($entry['title']['value'])) { $u = add_tweet_user($entry); $title = $entry['title']['value']; $tweeturl = $entry['link'][0]['attr']['href']; $request->set_param(array('post', 'parent_id'), 0); $request->set_param(array('post', 'uri'), $tweeturl); $request->set_param(array('post', 'url'), $tweeturl); $request->set_param(array('post', 'title'), $title); $request->set_param(array('post', 'profile_id'), $u->profile_id); $table = 'posts'; $content_type = 'text/html'; $rec = $Post->base(); $fields = $Post->fields_from_request($request); $fieldlist = $fields['posts']; foreach ($fieldlist as $field => $type) { $rec->set_value($field, $request->params[strtolower(classify($table))][$field]); } $Identity =& $db->model('Identity'); $id = $Identity->find($u->profile_id); $rec->save_changes(); $rec->set_etag($id->person_id); trigger_after('insert_tweets_via_cron', $Post, $rec); } } } } } } if ($latest) { $options[1]['last_id'] = $latest; }
function virtual_resource() { global $request; $model = model_path() . classify($request->resource) . ".php"; if (!file_exists($model)) { return true; } return false; }
`Salary` int(6) NOT NULL, PRIMARY KEY (`sl`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; -- -- Dumping data for table `table1` -- INSERT INTO `table1` (`sl`, `Education`, `Sex`, `Work`, `Disease`, `Salary`) VALUES (1, '9th', 'M', 32, 'Bronchitis', 3000), (2, '9th', 'M', 30, 'Cholera', 1000), (3, '9th', 'M', 33, 'Flu', 2000), (4, '10th', 'F', 35, 'Bronchitis', 2000), (5, '10th', 'F', 36, 'Cholera', 3000), (6, '11th', 'M', 37, 'Flu', 3000), (7, '12th', 'M', 38, 'Cholera', 3000), (8, '12th', 'F', 38, 'Flu', 3000), (9, '11th', 'M', 37, 'Bronchitis', 1000), (10, 'Masters', 'M', 41, 'Cholera', 1000), (11, 'Bachelors', 'F', 39, 'Bronchitis', 2000), (12, 'Masters', 'M', 42, 'Flu', 1000), (13, 'Masters', 'M', 44, 'Flu', 2000), (14, 'Bachelors', 'F', 38, 'Bronchitis', 1000), (15, 'Doctorate', 'F', 44, 'Cholera', 2000), (16, 'Masters', 'F', 40, 'Flu', 1000), (17, 'Doctorate', 'F', 44, 'Bronchitis', 1000), (18, 'Doctorate', 'F', 45, 'Cholera', 3000), (19, 'Doctorate', 'F', 44, 'Cholera', 2000); */ classify($X, $n, $table);
/** * Eagerly loads relationships for $models. * * This method takes an array of models, collects PK or FK (whichever is needed for relationship), then queries * the related table by PK/FK and attaches the array of returned relationships to the appropriately named relationship on * $models. * * @param Table $table * @param $models array of model objects * @param $attributes array of attributes from $models * @param $includes array of eager load directives * @param $query_keys -> key(s) to be queried for on included/related table * @param $model_values_keys -> key(s)/value(s) to be used in query from model which is including * @return void */ protected function queryAndAttachRelatedModelsEagerly(Table $table, $models, $attributes, $includes = [], $query_keys = [], $model_values_keys = []) { $values = []; $options = $this->options; $inflector = Inflector::instance(); $query_key = $query_keys[0]; $model_values_key = $model_values_keys[0]; // foreach ($attributes as $column => $value) original foreach ($attributes as $value) { $values[] = $value[$inflector->variablize($model_values_key)]; } $values = [$values]; $conditions = SQLBuilder::createConditionsFromUnderscoredString($table->conn, $query_key, $values); if (isset($options['conditions']) && \strlen($options['conditions'][0]) > 1) { $utils->addCondition($options['conditions'], $conditions); } else { $options['conditions'] = $conditions; } if (!empty($includes)) { $options['include'] = $includes; } if (!empty($options['through'])) { // save old keys as we will be reseting them below for inner join convenience $pk = $this->primary_key; $fk = $this->foreign_key; $this->setKeys($this->getTable()->class->getName(), true); if (!isset($options['class_name'])) { $class = classify($options['through'], true); if (isset($this->options['namespace']) && !\class_exists($class)) { $class = $this->options['namespace'] . '\\' . $class; } $through_table = $class::table(); } else { $class = $options['class_name']; $relation = $class::table()->getRelationship($options['through']); $through_table = $relation->getTable(); } $options['joins'] = $this->constructInnerJoinSql($through_table, true); $query_key = $this->primary_key[0]; // reset keys $this->primary_key = $pk; $this->foreign_key = $fk; } $options = $this->unsetNonFinderOptions($options); $class = $this->class_name; $related_models = $class::find('all', $options); $used_models = []; $model_values_key = $inflector->variablize($model_values_key); $query_key = $inflector->variablize($query_key); foreach ($models as $model) { $matches = 0; $key_to_match = $model->{$model_values_key}; foreach ($related_models as $related) { if ($related->{$query_key} == $key_to_match) { $hash = \spl_object_hash($related); if (\in_array($hash, $used_models)) { $model->setRelationshipFromEagerLoad(clone $related, $this->attribute_name); } else { $model->setRelationshipFromEagerLoad($related, $this->attribute_name); } $used_models[] = $hash; $matches++; } } if (0 === $matches) { $model->setRelationshipFromEagerLoad(null, $this->attribute_name); } } }
/** * Infers the $this->class_name based on $this->attribute_name. * * Will try to guess the appropriate class by singularizing and uppercasing $this->attribute_name. * * @return void * @see attribute_name */ protected function set_inferred_class_name() { $singularize = $this instanceof HasMany ? true : false; $this->set_class_name(classify($this->attribute_name, $singularize)); }
* A very simple executable script to train and use the LanguageDetector * class. For now it will not use a more complex (and better) structure like * Symfony\Console\Application but it will be a self contained little script. */ include "vendor/autoload.php"; try { $command = isset($_POST['command']) ? $_POST['command'] : ""; switch ($command) { case "train": train($argv); break; case "evaluate": evaluate($argv); break; case "classify": classify($argv); break; case "help": default: help(); break; } } catch (Exception $e) { echo PHP_EOL, $e->getMessage(), PHP_EOL, PHP_EOL; } /** * Just echo a simple help message */ function help() { echo <<<HELP
// Euclidian } // return $distance; // Simple return sqrt($distance); // Euclidian } // 9. WRITING THE CLASSIFIER FUNCTION function classify($trainingData, $unknownPixels) { $neighbors = []; foreach ($trainingData as $i => $knownDigit) { $neighbors[$i] = calculateDistance($unknownPixels, $knownDigit->Pixels); } asort($neighbors); return $trainingData[key($neighbors)]->Label; } // 10. SEE THE CLASSIFIER IN ACTION $predicted = classify($trainingData, $validationData[0]->Pixels); // 11. EVALUATING THE MODEL AGAINST VALIDATION DATA $processed = $matched = $accuracy = 0; foreach ($validationData as $i => $record) { $processed++; $actual = $record->Label; $predicted = classify($trainingData, $record->Pixels); if ($actual == $predicted) { $matched++; } $accuracy = round($matched / $processed * 100, 2); //Visualiser::Draw("$actual == $predicted ?" , $record->Pixels); echo "Actual: {$actual}, Predicted: {$predicted}, Accuracy: {$accuracy} %", PHP_EOL; }
function Collection($resource, $find_by = NULL, $accept = "text/html") { $this->_currentRow = 0; $this->EOF = false; $this->members = array(); $this->fields = array(); if ($resource == NULL) { return; } global $request; global $db; $this->resource = $resource; $this->accept = $accept; if ($resource == 'introspection') { $this->members = introspect_tables(); return; } if ($resource != classify($resource)) { $table =& $db->get_table($this->resource); } else { return; } // $member->member_entry_iri // Entry object of type 'member' or 'media link' // $member->media_iri = ; // (optional) Entry object of type 'media link' if (isset($table->params)) { foreach ($table->params as $key => $val) { if (!isset($this->{$key})) { $this->{$key} = $val; } } } if (isset($request->params['offset'])) { $table->set_offset($request->params['offset']); } if (isset($request->params['orderby'])) { $table->set_orderby($request->params['orderby']); } if (isset($request->params['order'])) { $table->set_order($request->params['order']); } if (isset($table->limit)) { $this->per_page = $table->limit; } else { $this->per_page = 20; } if (isset($request->params['page']) && !is_array($request->params['page'])) { $table->set_offset($this->per_page * $request->params['page'] - $this->per_page); } if (!($find_by == NULL)) { $table->find_by($find_by); } elseif (!$request->id) { $table->find(); } else { $table->find($request->id); } if (isset($table->uri_key)) { $uri_key = $table->uri_key; } else { $uri_key = $table->primary_key; } if ($table->rowcount() > 0) { $first = true; $this->updated = timestamp(); while ($Member = $table->MoveNext()) { if (isset($db->models['entries'])) { $Entry = $Member->FirstChild('entries'); if ($Entry) { $Member->last_modified = $Entry->last_modified; $Member->etag = $Entry->etag; } } $this->members[$Member->{$uri_key}] = $Entry->last_modified; if ($first) { if (isset($Member->created) && !empty($Member->created)) { $this->updated = $Member->created; } elseif (isset($Member->modified) && !empty($Member->modified)) { $this->updated = $Member->modified; } elseif (!empty($Entry->last_modified)) { $this->updated = $Entry->last_modified; } } $first = false; } $table->rewind(); } }
function post(&$vars) { extract($vars); global $request; $modelvar = classify($request->resource); trigger_before('insert_from_post', ${$modelvar}, $request); $table = $request->resource; $content_type = 'text/html'; $rec = ${$modelvar}->base(); if (!${$modelvar}->can_create($table)) { trigger_error("Sorry, you do not have permission to " . $request->action . " " . $table, E_USER_ERROR); } $fields = ${$modelvar}->fields_from_request($request); $fieldlist = $fields[$table]; foreach ($fieldlist as $field => $type) { if (${$modelvar}->has_metadata && is_blob($table . '.' . $field)) { if (isset($_FILES[strtolower(classify($table))]['name'][$field])) { $content_type = type_of($_FILES[strtolower(classify($table))]['name'][$field]); } } $rec->set_value($field, $request->params[strtolower(classify($table))][$field]); } $rec->set_value('profile_id', get_profile_id()); $result = $rec->save_changes(); if (!$result) { trigger_error("The record could not be saved into the database.", E_USER_ERROR); } $atomentry = ${$modelvar}->set_metadata($rec, $content_type, $table, 'id'); ${$modelvar}->set_categories($rec, $request, $atomentry); if (is_upload($table, 'attachment')) { $upload_types = environment('upload_types'); if (!$upload_types) { $upload_types = array('jpg', 'jpeg', 'png', 'gif'); } $ext = extension_for(type_of($_FILES[strtolower(classify($table))]['name']['attachment'])); if (!in_array($ext, $upload_types)) { trigger_error('Sorry, this site only allows the following file types: ' . implode(',', $upload_types), E_USER_ERROR); } $url = $request->url_for(array('resource' => $table, 'id' => $rec->id)); $title = substr($rec->title, 0, 140); $over = strlen($title) + strlen($url) + 1 - 140; if ($over > 0) { $rec->set_value('title', substr($title, 0, -$over) . " " . $url); } else { $rec->set_value('title', $title . " " . $url); } $rec->save_changes(); $tmp = $_FILES[strtolower(classify($table))]['tmp_name']['attachment']; if (is_jpg($tmp)) { $thumbsize = environment('max_pixels'); $Thumbnail =& $db->model('Thumbnail'); $t = $Thumbnail->base(); $newthumb = tempnam("/tmp", "new" . $rec->id . ".jpg"); resize_jpeg($tmp, $newthumb, $thumbsize); $t->set_value('target_id', $atomentry->id); $t->save_changes(); update_uploadsfile('thumbnails', $t->id, $newthumb); $t->set_etag(); } } trigger_after('insert_from_post', ${$modelvar}, $rec); header_status('201 Created'); redirect_to($request->base); }
function set_routes($table) { trigger_before('set_routes', $this, $this); global $request; if (empty($table)) { trigger_error('no table name when creating a route in set_routes', E_USER_ERROR); } $request->connect($table, array('requirements' => array('[a-z]+'), 'resource' => $table)); if ($request->resource == $table && $request->id > 1) { $request->connect(classify($table), array('requirements' => array('[a-z]+', '[0-9]+'), 'resource' => $table, 'id' => $request->id)); } }
function breadcrumbs() { $controller = $this->params['resource']; $links = array(); $html = ""; $links[] = '<a href="' . $this->base . '">Home</a>'; if (isset($this->resource) && $this->resource != 'introspection') { if (pretty_urls()) { $links[] = '<a href="' . $this->base . '' . $this->resource . '">' . ucwords($this->resource) . '</a>'; } else { $links[] = '<a href="' . $this->base . '?' . $this->resource . '">' . ucwords($this->resource) . '</a>'; } } if ($this->id != 0 && isset($this->resource) && $this->resource != 'introspection') { $links[] = '<a href="' . $this->entry_url($this->id) . '">Entry ' . ucwords($this->id) . '</a>'; } elseif (isset($this->resource) && $this->new_url()) { $links[] = '<a href="' . $this->new_url() . '">New ' . classify($this->resource) . '</a>'; } $html = "<span>"; foreach ($links as $key => $val) { if ($key > 0) { $html .= " | "; } $html .= $val; } $html .= "</span>"; return $html; }
function aws_putfile(&$rec, $pkvalue) { global $request, $prefix; $file = $prefix . $rec->table . $pkvalue . "." . extension_for(type_of($_FILES[strtolower(classify($rec->table))]['name'][$this->file_upload[0]])); lib_include('S3'); $s3 = new S3(environment('awsAccessKey'), environment('awsSecretKey')); if (!$s3) { trigger_error('Sorry, there was a problem connecting to Amazon Web Services', E_USER_ERROR); } if (!$s3->getBucket(environment('awsBucket'))) { $result = $s3->putBucket(environment('awsBucket'), 'public-read'); if (!$result) { trigger_error('Sorry, there was a problem creating the bucket ' . environment('awsBucket') . ' at Amazon Web Services', E_USER_ERROR); } } if (file_exists($this->file_upload[1])) { if (!$s3->putObjectFile($this->file_upload[1], environment('awsBucket'), $file, 'public-read')) { trigger_error('Sorry, there was a problem uploading the file to Amazon Web Services', E_USER_ERROR); } unlink($this->file_upload[1]); } $this->file_upload = false; }