private function getOrm($seg) { if (!count($seg)) { throw new \Exception('Query is invalid.'); } $seg = Arrays::first($seg); $table = isAke($seg, 'table', false); if (!$table) { throw new \Exception('Query is invalid.'); } if (fnmatch('*.*', $table)) { list($database, $table) = explode('.', $table); } else { $database = SITE_NAME; } return jdb($database, $table); }
public static function autoload($className) { $found = false; foreach (static::$_paths as $ns => $path) { $file = $path . preg_replace('#\\\\|_(?!.+\\\\)#', DS, str_replace($ns, '', $className)) . '.php'; if (is_readable($file)) { require_once $file; static::$_classes[$className] = true; $found = true; break; } } if (fnmatch('Thin\\\\Db*', $className) && !class_exists($className)) { $db = Inflector::uncamelize(str_replace(['Thin\\Db', 'Thin\\Db\\'], '', $className)); if (fnmatch('*_*', $db)) { list($database, $table) = explode('_', $db, 2); } else { $database = SITE_NAME; $table = $db; } jdb($database, $table); $found = true; } }
public static function populateTable($table, $database = null) { $db = jdb($database, $table); $mongo = static::instance($db); $database = is_null($database) ? SITE_NAME : $database; $rows = glob(Config::get('directory.store', STORAGE_PATH) . DS . 'dbjson' . DS . $database . '_' . APPLICATION_ENV . DS . $table . DS . '*.row'); if (count($rows)) { foreach ($rows as $row) { $mongo->read($mongo->extractId($row)); } } }
private function related(Container $obj) { $fields = array_keys($obj->assoc()); foreach ($fields as $field) { if (endsWith($field, '_id')) { if (is_string($field)) { $value = $obj->{$field}; if (!is_callable($value)) { $fk = repl('_id', '', $field); $ns = $this->db; $cb = function () use($value, $fk, $ns) { $db = jdb($ns, $fk); return $db->find($value); }; $obj->event($fk, $cb); $setter = lcfirst(Inflector::camelize("link_{$fk}")); $cb = function (Container $fkObject) use($obj, $field, $fk) { $obj->{$field} = $fkObject->getId(); $newCb = function () use($fkObject) { return $fkObject; }; $obj->event($fk, $newCb); return $obj; }; $obj->event($setter, $cb); } } } } return $obj; }
public function __get($key) { $array = isset($this->values) ? $this->values : []; if (count($array)) { foreach ($array as $k => $v) { if (!Arrays::in($k, $this->_fields)) { $this->_fields[] = $k; } $this->{$k} = $v; } } if (isset($this->{$key})) { if (isset($this->thin_type)) { $type = $this->thin_type; Data::getModel($this->thin_type); $settings = Arrays::exists($type, Data::$_settings) ? Data::$_settings[$type] : []; if (Arrays::exists('relationships', $settings)) { if (Arrays::exists($key, $settings['relationships']) && 's' != $key[strlen($key) - 1]) { return Data::getById($key, $this->{$key}); } if (Arrays::exists($key, $settings['relationships']) && 's' == $key[strlen($key) - 1]) { return Data::query(substr($key, 0, -1), "{$type} = " . $this->id); } } } return $this->{$key}; } if (isset($this->_token) && isset($this->values)) { $keyJson = sha1('touch' . $this->_token); $dbjson = isAke($this->values, $keyJson, false); if (false !== $dbjson) { $keyT = sha1('db' . $this->_token); $cb = isAke($this->values, $keyT, false); if (false !== $cb) { $db = call_user_func_array($cb, []); $fields = $db->fields(); if (Arrays::in($key, $fields)) { return null; } $tab = str_split($key); $many = false; if (Arrays::last($tab) == 's') { array_pop($tab); $table = implode('', $tab); $many = true; } else { $table = $func; } $object = true; $model = jdb($db->db, $table); return true === $many ? $model->where($db->table . '_id = ' . $this->id)->exec($object) : $model->where($db->table . '_id = ' . $this->id)->first($object); } } } return null; }
public function makeSearch() { $fieldsSettings = jdb('system', 'datafieldssettings')->where("table = " . $this->model->table)->where('database = ' . $this->model->db)->where('user_id = ' . auth()->user()->getId())->exec(); $userSettings = []; if (count($fieldsSettings)) { foreach ($fieldsSettings as $fieldSettings) { foreach ($fieldSettings as $k => $v) { if (strstr($k, 'is_')) { $userSettings[$fieldSettings['field']][$k] = 1 == $v ? true : false; } } } } $fields = $this->fields(); $fieldInfos = isAke($this->config, 'fields'); $where = isAke($_REQUEST, 'crud_where', session('dataTableCrud::' . $this->model->table)->getWhere()); $search = '<div class="row"><div class="col-md-10">' . NL; $queriesRecorded = jdb('system', 'dataquery')->where('user_id = ' . auth()->user()->getId())->where('table = ' . $this->model->table)->where('database = ' . $this->model->db)->exec(); if (count($queriesRecorded)) { $search .= '<div><a rel="tooltip" href="' . urlAction('saveddataqueries') . '/table/' . $this->model->table . '/database/' . $this->model->db . '" title="Accéder aux recherches enregistrées" class="btn btn-primary"><i class="fa fa-database"></i> <i class="fa fa-search"></i></a></div><br />'; } if (!empty($where)) { $queryRecorded = jdb('system', 'dataquery')->where('user_id = ' . auth()->user()->getId())->where('table = ' . $this->model->table)->where('database = ' . $this->model->db)->where('clause = ' . base64_encode($where))->first(true); $whereReadable = $this->readableQuery($where); $search .= '<span class="badge badge-lg alert-success">Recherche en cours : ' . $whereReadable . '</span>'; $exists = !is_null($queryRecorded); if (!$exists) { $search .= ' <a rel="tooltip" title="Sauvegarder cette recherche" class="btn btn-primary" href="' . urlAction('savedataquery') . '/table/' . $this->model->table . '/database/' . $this->model->db . '/query/' . base64_encode($where) . '"><i class="fa fa-save"></i></a> '; } $search .= ' <a class="btn btn-warning" href="#" onclick="document.location.href = \'' . urlAction('list') . '/table/' . $this->model->table . '/database/' . $this->model->db . '/kill/1\'"><i class="fa fa-trash-o icon-white"></i> Supprimer cette recherche</a> '; } $search .= '<button id="newCrudSearch" type="button" class="btn btn-info" onclick="$(\'#crudSearchDiv\').slideDown();$(\'#newCrudSearch\').hide();$(\'#hideCrudSearch\').show();"><i class="fa fa-search fa-white"></i> Effectuer une nouvelle recherche</button>'; $search .= ' <button id="hideCrudSearch" type="button" style="display: none;" class="btn btn-danger" onclick="$(\'#crudSearchDiv\').slideUp();$(\'#newCrudSearch\').show();$(\'#hideCrudSearch\').hide();"><i class="fa fa-power-off fa-white"></i> Masquer la recherche</button>'; $search .= '<fieldset id="crudSearchDiv" style="display: none;">' . NL; $search .= '<hr />' . NL; $i = 0; $fieldsJs = []; $js = '<script type="text/javascript">' . NL; $searchFields = ['created_at' => 'Date de création', 'updated_at' => 'Date de mise à jour']; foreach ($searchFields as $field => $label) { $fieldsJs[] = "'{$field}'"; $search .= '<div class="control-group">' . NL; $search .= '<label class="control-label">' . \Thin\Html\Helper::display($label) . '</label>' . NL; $search .= '<div class="controls" id="crudControl_' . $i . '">' . NL; $search .= '<select id="crudSearchOperator_' . $i . '"> <option value="=">=</option> <option value="<"><</option> <option value=">">></option> <option value="<=">≤</option> <option value=">=">≥</option> </select>' . NL; if ($field == 'id') { $search .= '<input pattern="\\\\d*" style="width: 150px;" type="text" id="crudSearchValue_' . $i . '" value="" />'; } elseif ($field == 'created_at' || $field == 'updated_at') { $search .= '<input class="crudDate" data-date-clear-btn="true" data-date-format="dd/mm/yyyy" style="width: 150px;" type="text" id="crudSearchValue_' . $i . '" value="" />'; } $search .= ' <span class="btn btn-success" href="#" onclick="addRowSearch(\'' . $field . '\', ' . $i . '); return false;"><i class="fa fa-plus"></i></span>'; $search .= '</div>' . NL; $search .= '</div><hr>' . NL; $i++; } foreach ($fields as $field) { $userInfos = isAke($userSettings, $field, []); $fieldSettings = isAke($fieldInfos, $field); $searchable = isAke($userInfos, 'is_searchable', isAke($fieldSettings, 'is_listable', true)); $label = isAke($fieldSettings, 'label', ucfirst($field)); $type = isAke($fieldSettings, 'type', 'text'); $closure = isAke($fieldSettings, 'content_search', false); if (true === $searchable) { $fieldsJs[] = "'{$field}'"; $search .= '<div class="control-group">' . NL; $search .= '<label class="control-label">' . \Thin\Html\Helper::display($label) . '</label>' . NL; $search .= '<div class="controls" id="crudControl_' . $i . '">' . NL; $search .= '<select id="crudSearchOperator_' . $i . '"> <option value="=">=</option> <option value="LIKE">Contient</option> <option value="NOT LIKE">Ne contient pas</option> <option value="START">Commence par</option> <option value="END">Finit par</option> <option value="<"><</option> <option value=">">></option> <option value="<=">≤</option> <option value=">=">≥</option> </select>' . NL; if (!$closure) { $search .= '<input style="width: 150px;" type="text" id="crudSearchValue_' . $i . '" value="" />'; } else { if (is_callable($closure)) { $customSearch = call_user_func_array($closure, array('crudSearchValue_' . $i)); $search .= $customSearch; } else { $search .= '<input style="150px;" type="text" id="crudSearchValue_' . $i . '" value="" />'; } } $search .= ' <span class="btn btn-success" href="#" onclick="addRowSearch(\'' . $field . '\', ' . $i . '); return false;"><i class="fa fa-plus"></i></span>'; $search .= '</div>' . NL; $search .= '</div>' . NL; $i++; } } $js .= 'var searchFields = [' . implode(', ', $fieldsJs) . ']; var numFieldsSearch = ' . ($i - 1) . ';'; $js .= '</script>' . NL; $search .= '<div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-primary" name="Rechercher" onclick="makeCrudSearch();">Rechercher</button> </div> </div>' . NL; $search .= '</fieldset>' . NL; $search .= '</div><div class="col-md-2 clear"></div>' . NL . $js . NL; return $search . '</div></div><div class="wrapper">'; }
public function permissions($role = null) { $db = jdb(Config::get('bundle.auth.database', 'auth'), Config::get('bundle.auth.table.rolepermission', 'rolepermission')); if (is_null($role)) { return $db->fetch()->exec(true); } else { if ($role instanceof Container) { return $db->where(['role_id', '=', $role->id])->exec(true); } elseif (filter_var($role, FILTER_VALIDATE_INT) !== false) { return $db->where(['role_id', '=', $role])->exec(true); } else { throw new Exception("Role has a wrong format."); } } }
public static function tables() { set_time_limit(0); $dbt = jdb('system', 'jma_table'); $dirs = glob(self::dirStore() . DS . 'dbjson' . DS . '*' . APPLICATION_ENV . '*'); $rows = []; if (!empty($dirs)) { foreach ($dirs as $dir) { $tmp = glob($dir . DS . '*'); $rows = array_merge($rows, $tmp); } } $tables = []; if (!empty($rows)) { foreach ($rows as $row) { $tab = explode(DS, $row); $index = Arrays::last($tab); $ns = str_replace('_' . APPLICATION_ENV, '', $tab[count($tab) - 2]); if (!fnmatch('jma_*', $index)) { $t = $dbt->name($index)->ns($ns)->first(true); if (is_null($t)) { $tables[$index]['ns'] = $ns; $data = jdb($ns, $index)->fetch()->exec(); if (!empty($data)) { $first = Arrays::first($data); $fields = array_keys($first); $tables[$index]['fields'] = $fields; } else { $tables[$index]['fields'] = []; } } } } } foreach ($tables as $t => $i) { self::structure($i['ns'], $t, $i['fields']); } return $tables; }
public static function delete($key) { $row = jdb('system', 'cache')->where('key = ' . $key)->first(true); if ($row) { $row->delete(); return true; } return false; }
public function listing() { $fields = $this->fields(); $fieldInfos = isAke($this->config, 'fields'); $defaultOrder = isAke($this->config, 'default_order', $this->model->pk()); $defaultDir = isAke($this->config, 'default_order_direction', 'ASC'); $limit = isAke($this->config, 'items_by_page', Config::get('crud.items.number', 25)); $many = isAke($this->config, 'many'); $where = isAke($_REQUEST, 'crud_where', null); $page = isAke($_REQUEST, 'crud_page', 1); $order = isAke($_REQUEST, 'crud_order', $defaultOrder); $orderDirection = isAke($_REQUEST, 'crud_order_direction', $defaultDir); $export = isAke($_REQUEST, 'crud_type_export', false); $export = !strlen($export) ? false : $export; $offset = $page * $limit - $limit; $whereData = ''; if (!empty($where)) { $whereData = $this->parseQuery($where); } $db = call_user_func_array(array('\\Dbjson\\Dbjson', 'instance'), array($this->model->db, $this->model->table)); if (strstr($whereData, ' && ')) { $wheres = explode(' && ', $whereData); foreach ($wheres as $tmpWhere) { $db = $this->model->where($tmpWhere); } } else { if (strlen($whereData)) { $db = $this->model->where($whereData); } else { $db = $this->model->fetch(); } } $results = $db->order($order, $orderDirection)->exec(); if (count($results) < 1) { if (strlen($where)) { return '<div class="alert alert-danger col-md-4 col-md-pull-4 col-md-push-4">La requête ne remonte aucun résultat.</div>'; } else { return '<div class="alert alert-info col-md-4 col-md-pull-4 col-md-push-4">Aucune donnée à afficher..</div>'; } } if (false !== $export) { return $this->export($export, $results); } $total = count($results); $last = ceil($total / $limit); $paginator = new Paginator($results, $page, $total, $limit, $last); $data = $paginator->getItemsByPage(); $pagination = $paginator->links(); $pagination = '<div class="row"> <div class="col-md-12"> ' . $pagination . ' </div> </div>'; $html = $pagination . '<div class="row"><div class="col-md-12"><form action="/crud/json/list/table/' . $this->model->table . '" id="listForm" method="post"> <input type="hidden" name="crud_page" id="crud_page" value="' . $page . '" /><input type="hidden" name="crud_order" id="crud_order" value="' . $order . '" /><input type="hidden" name="crud_order_direction" id="crud_order_direction" value="' . $orderDirection . '" /><input type="hidden" id="crud_where" name="crud_where" value="' . \Thin\Crud::checkEmpty('crud_where') . '" /><input type="hidden" id="crud_type_export" name="crud_type_export" value="" /> <table style="clear: both;" class="table table-striped tablesorter table-bordered table-condensed table-hover"> <thead> <tr>'; foreach ($fields as $field) { $fieldSettings = isAke($fieldInfos, $field); $label = isAke($fieldSettings, 'label', ucfirst($field)); $listable = isAke($fieldSettings, 'is_listable', true); $sortable = isAke($fieldSettings, 'is_sortable', true); if (!$listable || $field == $this->model->pk()) { continue; } if (!$sortable) { $html .= '<th>' . \Thin\Html\Helper::display($label) . '</th>'; } else { if ($field == $order) { $directionJs = 'ASC' == $orderDirection ? 'DESC' : 'ASC'; $js = 'orderGoPage(\'' . $field . '\', \'' . $directionJs . '\');'; $html .= '<th><div onclick="' . $js . '" class="text-left field-sorting ' . Inflector::lower($orderDirection) . '" rel="' . $field . '">' . \Thin\Html\Helper::display($label) . '</div></th>'; } else { $js = 'orderGoPage(\'' . $field . '\', \'ASC\');'; $html .= '<th><div onclick="' . $js . '" class="text-left field-sorting" rel="' . $field . '">' . \Thin\Html\Helper::display($label) . '</div></th>'; } } } if (count($many)) { $html .= '<th>Rel.</th>'; } $html .= '<th style="text-align: center;">Action</th> </tr> </thead> <tbody>'; foreach ($data as $item) { $id = isAke($item, $this->model->pk(), null); $html .= '<tr ondblclick="document.location.href = \'/crud/json/update/table/' . $this->model->table . '/id/' . $id . '\';">'; foreach ($fields as $field) { $fieldSettings = isAke($fieldInfos, $field); $listable = isAke($fieldSettings, 'is_listable', true); if (!$listable || $field == $this->model->pk()) { continue; } $value = isAke($item, $field, null); $closure = isAke($fieldSettings, 'content_view', false); if (false === $closure || !is_callable($closure)) { $continue = true; if (ake('form_type', $fieldSettings)) { if ($fieldSettings['form_type'] == 'image' && strlen($value)) { $html .= '<td><img src="' . $value . '" style="max-width: 200px;" /></td>'; $continue = false; } if ($fieldSettings['form_type'] == 'email' && strlen($value)) { $html .= '<td><a href="mailto:' . $value . '">' . \Thin\Html\Helper::display($this->truncate($value)) . '</a></td>'; $continue = false; } if ($fieldSettings['form_type'] == 'file' && strlen($value)) { $html .= '<td><a class="btn btn-small btn-success" href="' . $value . '"><i class="fa fa-download"></i></td>'; $continue = false; } } if (true === $continue) { if ('email' == $field) { $html .= '<td><a href="mailto:' . $value . '">' . \Thin\Html\Helper::display($this->truncate($value)) . '</a></td>'; } else { $html .= '<td>' . \Thin\Html\Helper::display($this->truncate($value)) . '</td>'; } } } else { $value = call_user_func_array($closure, array($item)); $html .= '<td>' . \Thin\Html\Helper::display($value) . '</td>'; } } if (count($many)) { $html .= '<td><ul class="list-inline">'; foreach ($many as $rel) { $foreignCrud = new self(jdb($this->model->db, $rel)); $nameRel = isAke($foreignCrud->config(), 'plural', $rel . 's'); $html .= '<li><a class="btn btn-primary" target="_blank" href="/crud/json/many/table/' . $rel . '/foreign/' . $this->model->table . '_id/id/' . $id . '"><i class="fa fa-chain"></i> ' . $nameRel . '</a></li>'; } $html .= '</ul></td>'; } $html .= $this->options($id); $html .= '</tr>'; } $html .= '</tbody> </table></form>' . $pagination . '</div></div>'; return $html; }
public function search($query, $comparison = 'like') { $ageChange = $this->model->cache()->get(sha1(jdb($this->model->db, $this->model->table)->dir)); $keyCache = 'cache::index::' . $this->model->db . '_' . APPLICATION_ENV . '::' . $this->model->table . '::' . sha1(serialize($this->fields)) . '::' . sha1($query . $comparison); $keyCacheData = $keyCache . '::data'; $keyCacheAge = $keyCache . '::age'; $age = $this->model->cache()->get($keyCacheAge); if (!strlen($age) || $age < $ageChange) { $keys = $this->keys($query); $collection = []; $tuples = []; if (count($keys)) { foreach ($this->fields as $field) { $rows = $this->model->cache()->keys('indexes::' . $this->model->db . '_' . APPLICATION_ENV . '::' . $this->model->table . '::*'); if (count($rows)) { foreach ($rows as $row) { list($rowDummy, $rowDb, $rowTable, $rowValue) = explode('::', $row, 3); $subRows = $this->model->cache()->hgetall($row); if (count($subRows)) { foreach ($subRows as $index => $val) { list($ind, $rowField) = explode('::', $index, 2); if ($rowField == $field) { $dbRow = jdb($this->model->db, $this->model->table)->find($ind, false); if ($dbRow) { $compare = isAke($dbRow, $field, false); if (false !== $compare) { foreach ($keys as $compareKey) { if ('like' === $comparison) { $check = fnmatch("*{$compareKey}*", $rowValue); } elseif ('strict' == $comparison) { $check = sha1($compareKey) == sha1($rowValue); } elseif ('phonetic' == $comparison) { $phonetic = Phonetic::instance(); $similarity = $phonetic->similarity($rowValue, $compareKey); $check = $similarity <= $phonetic->getTolerance(); } if (true === $check && !Arrays::in($ind, $tuples)) { array_push($collection, $dbRow); array_push($tuples, $ind); break; } } } } } } } } } } } $this->model->cache()->set($keyCacheData, serialize($collection)); $this->model->cache()->set($keyCacheAge, time()); } else { $collection = unserialize($this->model->cache()->get($keyCacheData)); } return new Collection($collection); }
public static function populateHash() { set_time_limit(0); $files = []; $dbs = glob(STORAGE_PATH . DS . 'dbjson' . DS . '*'); foreach ($dbs as $db) { $tables = glob($db . DS . '*'); foreach ($tables as $table) { $rows = glob($table . DS . '*.row'); foreach ($rows as $row) { array_push($files, $row); } } } foreach ($files as $file) { $tab = explode(DS, $file); $db = str_replace('_' . APPLICATION_ENV, '', $tab[count($tab) - 3]); $table = $tab[count($tab) - 2]; $instance = new self(jdb($db, $table)); $newFile = $instance->hashFile($file); File::move($file, $newFile); } }
public static function generate($database, $model, $fields = [], $overwrite = false) { $file = APPLICATION_PATH . DS . 'models' . DS . 'CrudJson' . DS . ucfirst(Inflector::camelize($database)) . DS . ucfirst(Inflector::camelize($model)) . '.php'; if (!is_dir(APPLICATION_PATH . DS . 'models' . DS . 'CrudJson' . DS . ucfirst(Inflector::camelize($database)))) { File::mkdir(APPLICATION_PATH . DS . 'models' . DS . 'CrudJson' . DS . ucfirst(Inflector::camelize($database))); } if (!File::exists($file) || $overwrite) { $db = jdb($database, $model); $crud = Crud::instance($db); File::delete($file); $tplModel = File::read(__DIR__ . DS . 'Model.tpl'); $tplField = File::read(__DIR__ . DS . 'Field.tpl'); $fields = empty($fields) ? $crud->fields() : $fields; $singular = ucfirst($model); $plural = $singular . 's'; $default_order = $crud->pk(); $tplModel = str_replace(['##singular##', '##plural##', '##default_order##', '##foreigns##', '##uniques##', '##soft_delete##', '##before_create##', '##after_create##', '##before_update##', '##after_update##', '##before_read##', '##after_read##', '##before_delete##', '##after_delete##', '##before_list##', '##after_list##'], [$singular, $plural, $default_order, '[]', '[]', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false'], $tplModel); $fieldsSection = ''; foreach ($fields as $field) { if ($field != $crud->pk()) { $label = substr($field, -3) == '_id' ? ucfirst(str_replace('_id', '', $field)) : ucfirst(Inflector::camelize($field)); $fieldsSection .= str_replace(['##field##', '##form_type##', '##helper##', '##required##', '##form_plus##', '##length##', '##is_listable##', '##is_exportable##', '##is_searchable##', '##is_sortable##', '##is_readable##', '##is_creatable##', '##is_updatable##', '##is_deletable##', '##content_view##', '##content_list##', '##content_search##', '##content_create##', '##label##'], [$field, 'text', 'false', 'true', 'false', 'false', 'true', 'true', 'true', 'true', 'true', 'true', 'true', 'true', 'false', 'false', 'false', 'false', $label], $tplField); } } $tplModel = str_replace('##fields##', $fieldsSection, $tplModel); File::put($file, $tplModel); } }
public function docdeleteAction() { $id = request()->getId(); if (!is_null($id)) { $db = jdb('auth', 'doc'); $row = $db->find($id); if ($row) { $file = $row->getUrl(); $file = repl(URLSITE, '', $file); $file = realpath(APPLICATION_PATH . '/../public/' . $file); File::delete($file); $row->delete(); } $this->forward('doclist'); } else { $this->forward('home'); } }
function orm($db = null, $table = null) { $db = is_null($db) ? 'system' : $db; $table = is_null($table) ? 'system' : $table; return jdb($db, $table); }