/** * This method allows to "overloadingly" get attributes this way: * $model->parentId; instead of $model->parent_id. */ public static function properAttrName($name) { if (static::convertAttributeNames()) { $name = \Rails::services()->get('inflector')->underscore($name); } return $name; }
public static function fast_count($tags = null) { # A small sanitation $tags = preg_replace('/ +/', ' ', trim($tags)); $cache_version = (int) Rails::cache()->read('$cache_version'); $key = ['post_count' => $tags, 'v' => $cache_version]; $count = (int) Rails::cache()->fetch($key, function () use($tags) { list($sql, $params) = Post::generate_sql($tags, ['count' => true]); array_unshift($params, $sql); return Post::countBySql($params); }); return $count; # This is just too brittle, and hard to make work with other features that may # hide posts from the index. # if tags.blank? # return select_value_sql("SELECT row_count FROM table_data WHERE name = 'posts'").to_i # else # c = select_value_sql("SELECT post_count FROM tags WHERE name = ?", tags).to_i # if c == 0 # return Post.count_by_sql(Post.generate_sql(tags, :count => true)) # else # return c # end # end }
public static function errorFile() { if (!self::$save_path) { self::$save_path = Rails::root() . '/tmp'; } return self::$save_path . '/' . self::$errorFile_name; }
/** * Get the adapter for a specific connection. If the adapter doesn't * exist, it is created. If the connection config isn't found, an * exception is thrown. * * @return Adapter * @throw Exception\RuntimeException */ public function getAdapter($connectionName, array $options = []) { if (!isset($this->adapters[$connectionName])) { if (!$this->connectionExists($connectionName)) { throw new Exception\RuntimeException(sprintf('Connection doesn\'t exist: %s', $connectionName)); } $connectionConfig = $this->connections[$connectionName]; if (!isset($connectionConfig['driver'])) { throw new Exception\InvalidArgumentException('A "driver" key to be present inside the database config parameters'); } if ($connectionConfig['driver'] == 'mongo') { $connection = new MongoConnection($connectionConfig); $this->adapters[$connectionName] = $connection; } else { $driver = DriverCreator::create($connectionName, $connectionConfig); $adapterParams = ['driver' => $driver]; if (isset($options['allowProfiler']) && !$options['allowProfiler']) { $adapterParams['profiler'] = false; } $adapter = new Adapter($adapterParams); $this->adapters[$connectionName] = $adapter; $driver->getConnection()->setAdapter($adapter); if (\Rails::cli()) { $adapter->setProfiler(new \Zend\Db\Adapter\Profiler\Profiler()); } } } return $this->adapters[$connectionName]; }
public static function generateSchemaFiles() { foreach (ActiveRecord::connections() as $connectionName => $cdata) { if (!isset($cdata['username']) || !isset($cdata['password']) || !isset($cdata['database'])) { continue; } else { try { ActiveRecord::setConnection($connectionName); $connection = ActiveRecord::connection(); $dbname = $connection->selectValue("SELECT DATABASE()"); $tables = $connection->selectValues(sprintf('SHOW TABLES FROM `%s`', $dbname)); } catch (Throwable $e) { continue; } catch (\Exception $e) { continue; } if (!$tables) { throw new Exception\RuntimeException(sprintf('Couldn\'t retrieve table information for connection %s', $connectionName)); } foreach ($tables as $table_name) { $class = 'Rails\\ActiveRecord\\Adapter\\' . $connection->adapterName() . '\\Table'; $data = $class::fetchSchema($connection, $table_name); $path = \Rails::root() . '/db/table_schema/' . $connection->name(); if (!is_dir($path)) { mkdir($path, 0777, true); } $file = $path . '/' . $table_name . '.php'; $contents = "<?php\nreturn "; $contents .= var_export($data, true); $contents .= "\n;"; file_put_contents($file, $contents); } } } }
/** * Overriding Versioning's delete_history because it's a special case with * pools posts. */ protected function delete_history() { $ids = self::connection()->selectValues("SELECT DISTINCT history_id FROM history_changes WHERE table_name = 'pools_posts' AND remote_id = ?", $this->id); Rails::log('IDS: ', $ids); $sql = "DELETE FROM histories WHERE id IN (?)"; self::connection()->executeSql($sql, $ids); }
public function createFile() { $inflector = \Rails::services()->get('inflector'); $this->migrationClassName = $inflector->camelize($this->fileName); $this->fileName = gmdate('YmdHis') . '_' . $this->fileName; parent::createFile(); }
public function tempfile_prefix() { if (!$this->tempfile_prefix) { $this->tempfile_prefix = \Rails::publicPath() . '/data/temp-' . uniqid('tfp_'); } return $this->tempfile_prefix; }
public function __construct() { $method = \Rails::application()->dispatcher()->request()->method(); if ($method != 'GET' && $method != 'POST') { $params = file_get_contents('php://input'); $decoded = []; if (!empty($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] == "application/json") { $decoded = json_decode($params, true); if ($decoded === null) { $decoded = []; $this->_json_params_error = json_last_error(); } } else { parse_str($params, $decoded); } if ($method == 'DELETE') { $this->deleteVars = $decoded; } elseif ($method == 'PUT') { $this->putVars = $decoded; } elseif ($method == 'PATCH') { $this->patchVars = $decoded; } else { $this->other_params = $decoded; } } $this->_import_files(); // vpe($this->files); }
public static function tableName() { $cn = str_replace('\\', '_', get_called_class()); $inf = \Rails::services()->get('inflector'); $tableName = $inf->underscore($inf->pluralize($cn)); return static::tableNamePrefix() . $tableName . static::tableNameSuffix(); }
public function get_translated_formatted_body($target_lang, array $source_langs) { $source_lang_list = implode(',', $source_langs); $key = "comment:" . $this->id . ":" . strtotime($this->updated_at) . ":" . $target_lang . ":" . $source_lang_list; return Rails::cache()->fetch($key, function () use($target_lang, $source_langs) { return $this->get_translated_formatted_body_uncached($target_lang, $source_langs); }); }
private function defaultParams() { $defaults = \Rails::application()->config()->cookies->toArray(); if (!$defaults['path']) { $defaults['path'] = \Rails::application()->router()->basePath() . '/'; } return $defaults; }
protected function _create_dirs($dir) { $dirs = array_filter(explode('/', str_replace(Rails::root(), '', pathinfo($dir, PATHINFO_DIRNAME)))); $dir = Rails::root() . '/'; foreach ($dirs as $d) { $dir .= $d . '/'; !is_dir($dir) && mkdir($dir); } }
public function _render_view() { # Include helpers. ActionView\ViewHelpers::load(); $layout = !empty($this->_params['layout']) ? $this->_params['layout'] : false; $this->_template = new ActionView\Template(['lambda' => $this->_params['lambda']], ['layout' => $layout]); $this->_template->setLocals(\Rails::application()->controller()->locals()); $this->_template->renderContent(); }
public static function new_deleted_posts($user) { if ($user->is_anonymous()) { return 0; } return Rails::cache()->fetch('deleted_posts:' . $user->id . ':' . $user->last_deleted_post_seen_at, ['expires_in' => '1 minute'], function () use($user) { return self::connection()->selectValue("SELECT COUNT(*) FROM flagged_post_details fpd JOIN posts p ON (p.id = fpd.post_id) " . "WHERE p.status = 'deleted' AND p.user_id = ? AND fpd.user_id <> ? AND fpd.created_at > ?", $user->id, $user->id, $user->last_deleted_post_seen_at); }); }
public function master_class() { if ($this->table_name == 'pools_posts') { $class_name = 'PoolPost'; } else { $class_name = Rails::services()->get('inflector')->classify($this->table_name); } return $class_name; }
public function linkTo($link, $url_params, array $attrs = array()) { if ($url_params == 'root') { return $this->base()->linkTo($link, $url_params, $attrs); } else { $base_path = Rails::application()->router()->basePath(); $attrs['href'] = $base_path . '/' . Rails::application()->config()->rails_panel_path . '/' . substr($url_params, 1); return $this->contentTag('a', $link, $attrs); } }
public function _render_view() { # Include helpers. ActionView\ViewHelpers::load(); $layout = !empty($this->_params['layout']) ? $this->_params['layout'] : false; # Create a template so we can call render_inline; $this->_template = new ActionView\Template(['inline' => $this->_params['code']], ['layout' => $layout]); $this->_template->setLocals(\Rails::application()->controller()->vars()); $this->_template->renderContent(); }
public function run() { Rails::systemExit()->register(function () { if (!$this->finished) { $this->active = false; $this->data->success = false; $this->data->error = "Couldn't finish successfuly"; $this->save(); } }); # Ugly: set the current user ID to the one set in the batch, so history entries # will be created as that user. // $old_thread_user = Thread::current["danbooru-user"]; // $old_thread_user_id = Thread::current["danbooru-user_id"]; // $old_ip_addr = Thread::current["danbooru-ip_addr"]; // Thread::current["danbooru-user"] = User::find_by_id(self.user_id) // Thread::current["danbooru-user_id"] = $this->user_id // Thread::current["danbooru-ip_addr"] = $this->ip $this->active = true; $this->save(); $post = Post::create(['source' => $this->url, 'tags' => $this->tags, 'updater_user_id' => $this->user_id, 'updater_ip_addr' => $this->ip, 'user_id' => $this->user_id, 'ip_addr' => $this->ip, 'status' => "active"]); if ($post->errors()->blank()) { if (CONFIG()->dupe_check_on_upload && $post->image() && !$post->parent_id) { $options = ['services' => SimilarImages::get_services("local"), 'type' => 'post', 'source' => $post]; $res = SimilarImages::similar_images($options); if (!empty($res['posts'])) { $post->tags = $post->tags() . " possible_duplicate"; $post->save(); } } $this->data->success = true; $this->data->post_id = $post->id; } elseif ($post->errors()->on('md5')) { // $p = $post->errors(); $p = Post::where(['md5' => $post->md5])->first(); $this->data->success = false; $this->data->error = "Post already exists"; $this->data->post_id = $p->id; } else { // p $post.errors $this->data->success = false; $this->data->error = $post->errors()->fullMessages(", "); } if ($this->data->success) { $this->status = 'finished'; } else { $this->status = 'error'; } $this->active = false; $this->save(); $this->finished = true; // Thread::current["danbooru-user"] = old_thread_user // Thread::current["danbooru-user_id"] = old_thread_user_id // Thread::current["danbooru-ip_addr"] = old_ip_addr }
private static function loadLocales() { $i18n = \Rails::services()->get('i18n'); $locale = $i18n->locale(); if ($locale == 'es') { $file = __DIR__ . '/locales/' . $locale . '.yml'; } else { $file = __DIR__ . '/locales/en.yml'; } $i18n->loadLocale($file); }
private function buildRequestInfo() { if (\Rails::application()->dispatcher() && ($request = \Rails::application()->dispatcher()->request())) { $info = '[' . $request->remoteIp() . '] ' . $request->method() . ' ' . $request->fullPath(); } elseif (\Rails::cli()) { $info = '[cli]'; } else { $info = ''; } return $info; }
public function getUnderscored($className) { if (!isset($this->propsByClassUnderscored[$className])) { $attrsNames = []; foreach ($this->get($className) as $attrName => $value) { $underscoredName = \Rails::getService('inflector')->underscore($attrName)->toString(); $attrsNames[$underscoredName] = $value; } # TODO: cache accordingly. $this->propsByClassUnderscored[$className] = $attrsNames; } return $this->propsByClassUnderscored[$className]; }
public function submit($value = null, array $options = []) { if (!$value) { $inflector = \Rails::services()->get('inflector'); $prettyClassName = $inflector->humanize($inflector->underscore(get_class($this->model))); if ($this->model->isNewRecord()) { $value = 'Create ' . $prettyClassName; } else { $value = 'Update ' . $prettyClassName; } } return $this->helper->tag('input', array_merge($options, ['value' => $value, 'type' => 'submit'])); }
/** * Returns the asset path (i.e., the URL) for a file. * If the digest option is true, the path to the compiled file * (with fingerprint) will be returned, if found. Otherwise, $file * will just be appended to the assets path. * Note that $file could include path relative to assets path, if necessary, * like $this->assetPath('jquery-ui/loading.gif'); */ protected function assetPath($file, array $options = []) { if (!isset($options['digest'])) { $options['digest'] = true; } if ($options['digest']) { if ($path = \Rails::assets()->findCompiledFile($file)) { return $path; } } $root = \Rails::application()->router()->rootPath(); if ($root == '/') { $root = ''; } return $root . \Rails::assets()->prefix() . '/' . $file; }
public function setProperties() { $this->migrationTemplate = 'migration.php'; $fileName = $this->arg('name'); $inflector = \Rails::getService('inflector'); $this->migrationClassName = $inflector->camelize($fileName); switch (true) { // case (preg_match('/^(add|remove)_.*_(?:to|from)_(.*)/', $fileName, $m)): // $this->migrationAction = $m[1]; // $this->tableName = $inflector->pluralize($m[2]); // break; // case (is_int(strpos($fileName, 'join_table'))): // break; case strpos($fileName, 'create_') === 0: $this->tableName = substr($fileName, 7); $this->migrationTemplate = 'create_table_migration.php'; break; } }
public function build_query() { $params = $this->params; if (empty($params['foreign_key'])) { $inflector = \Rails::services()->get('inflector'); $cn = get_class($this->parent_model); $params['foreign_key'] = $inflector->singularize($cn::tableName()) . '_id'; } $query = new Relation($params['class_name'], $params['class_name']::tableName()); $query->where('`' . $params['foreign_key'] . "` = ?", $this->parent_model->id); # params[0], if present, it's an anonymous function to customize the relation. # The function is binded to the relation object. if (isset($this->params[0])) { $lambda = array_shift($this->params); $lambda = $lambda->bindTo($query); $lambda(); } $this->query = $query; }
public function assetPath($source, array $options = []) { if (strpos($source, '/') !== 0 && strpos($source, 'http') !== 0) { if (!isset($options['digest'])) { $options['digest'] = true; } if (\Rails::config()->assets->enabled) { if (\Rails::config()->serve_static_assets && $options['digest']) { if ($url = \Rails::assets()->findCompiledFile($source)) { return $url; } } if ($file = \Rails::assets()->findFile($source)) { return $file->url(); } } return \Rails::application()->router()->rootPath() . $source; } else { return $source; } }
public static function parse($str) { $state = ['newline']; $result = ''; # Normalize newlines. $str = trim($str); $str = preg_replace(['/(\\r\\n?)/', '/\\n{3,}/', '/ *\\n */'], ["\n", "\n\n", "\n"], $str); $str = htmlentities($str); # Keep newline, use carriage return for split. $str = str_replace("\n", "\n\r", $str); $data = explode("\r", $str); # Parse header and list first, line by line. foreach ($data as $d) { $result .= self::parseline($d, $state); } # Parse inline tags as a whole. $result = self::parseinline($result); # htmLawed ensures valid html output. require_once Rails::root() . '/vendor/htmLawed/htmLawed.php'; return htmLawed($result); }
public static function process_all() { foreach (self::all() as $tag_subscription) { if ($tag_subscription->user->is_privileged_or_higher()) { try { self::transaction(function () use($tag_subscription) { $tags = preg_split('/\\s+/', $tag_subscription->tag_query); $post_ids = []; foreach ($tags as $tag) { $post_ids = array_merge($post_ids, Post::find_by_tags($tag, ['limit' => ceil(CONFIG()->tag_subscription_post_limit / 3), 'select' => 'p.id', 'order' => 'p.id desc'])->getAttributes('id')); } sort($post_ids); $tag_subscription->updateAttribute('cached_post_ids', join(',', array_unique(array_slice(array_reverse($post_ids), 0, CONFIG()->tag_subscription_post_limit)))); }); } catch (Exception $e) { # fail silently Rails::log()->exception($e); } sleep(1); } } }
public function _render_view() { # Include helpers. ActionView\ViewHelpers::load(); $layout = !empty($this->_params['layout']) ? $this->_params['layout'] : false; $partial = $this->_params['partial']; $locals = (array) \Rails::application()->controller()->locals(); $this->_template = new ActionView\Template(['lambda' => function () use($partial, $locals) { echo $this->partial($partial, $locals); }], ['layout' => $layout]); // $this->_template->setLocals(); $this->_template->renderContent(); // $params = [$this->_params['partial']]; // if (isset($this->_params['locals'])) // $params = array_merge($params, [$this->_params['locals']]); # Include helpers. // ActionView\ViewHelpers::load(); # Create a template so we can call render_partial. # This shouldn't be done this way. // $template = new ActionView\Template([]); // vpe($this); // $this->_body = call_user_func_array([$template, 'renderContent'], $params); }