factory() public static method

The class name should be supplied as a string, and the class should already have been loaded by PHP (or a suitable autoloader should exist). This method actually returns a wrapped ORM object which allows a database query to be built. The wrapped ORM object is responsible for returning instances of the correct class when its find_one or find_many methods are called.
public static factory ( string $class_name, null | string $connection_name = null ) : ORMWrapper
$class_name string
$connection_name null | string
return ORMWrapper
Example #1
0
 public function getHome($request, $response, $args)
 {
     $template = $this->twig->loadTemplate('index.twig');
     $posts = \Model::factory('App\\Models\\Post')->find_many();
     $response->setContent($template->render(['posts' => $posts]));
     return $response;
 }
Example #2
0
 /**
  * 显示日志详细
  * 
  * @param $blog_id 日志编号
  */
 public function action_show($blog_id)
 {
     $model = Model::factory('blog');
     $view = View::factory('pages/blog/show.php');
     $view->blog_info = $model->get_blog_info($blog_id);
     $this->template->content = $view;
 }
Example #3
0
 public function action_index()
 {
     if (!Auth::instance()->logged_in() && isset($_POST['login'])) {
         $user = ORM::factory('User');
         $status = Auth::instance()->login($_POST['username'], $_POST['password'], true);
         if ($status) {
             HTTP::redirect('/');
         }
     }
     if (Auth::instance()->logged_in() && isset($_POST['logout'])) {
         Auth::instance()->logout();
     }
     if (!Auth::instance()->logged_in()) {
         Guestid::factory()->get_id();
     }
     $templateData['title'] = 'Главная.';
     $templateData['description'] = '';
     $template = View::factory('template')->set('templateData', $templateData);
     $content = View::factory("catalog");
     $content->get = $_GET;
     $content->shopArr = Model::factory('Shop')->getShop();
     $root_page = "index";
     $template->root_page = $root_page;
     $template->content = $content;
     $this->response->body($template);
 }
Example #4
0
 public function action_post()
 {
     $username = $this->request->post('username');
     $password = $this->request->post('password');
     $captcha = $this->request->post('captcha');
     if ($username and $password) {
         //if(Captcha::valid($captcha)) {
         $passport = $this->getpassport($username, $password);
         if (!is_object($passport)) {
             if ($passport == -1) {
                 $DATA['msg'] = "对不起,你使用的用户名尚未注册!";
             } elseif ($passport == -2) {
                 $DATA['msg'] = "对不起,密码错误,请重新输入。";
             } elseif ($passport == -3) {
                 $DATA['msg'] = "账号已经冻结客服";
             } elseif ($passport == -5) {
                 $DATA['msg'] = "登陆次数过多,请联系客服";
             } else {
                 $DATA['msg'] = '登录失败,请确认用户名或者邮箱正确!';
             }
         } else {
             $user_id = $passport->uid;
             $user = $this->login($user_id);
             Model::factory('Sys')->updateLoginData($user, 3);
             return $this->redirect(ROOTURL . '/admin/main/index');
         }
         //} else {
         //	$DATA['msg'] = '登陆失败,验证码错误!';
         //}
     } else {
         $DATA['msg'] = '用户名或者Email错误!';
     }
     echo View::factory('admin/login/index', $DATA);
 }
Example #5
0
 public function set_projects()
 {
     // cache
     $key = $this->_user_id . '::project_list';
     $data = $this->cache->get($key);
     if (!$data) {
         $project_table = Model::factory('project');
         $tmp = $project_table->select_all_user_projects($this->_user_id);
         $data['_projects'] = array();
         // if there are projects
         if ($tmp->current()) {
             // build the select drop down
             foreach ($tmp as $tmp2) {
                 $data['_projects'][$tmp2->id] = $tmp2->name;
             }
         }
         // set cache for 24 hours
         $this->cache->set($key, $data, NULL, 86400);
     }
     // set the currently selected project_id if it is not set
     if (!isset($_SESSION['project_id_current']) || !isset($data['_projects'][$_SESSION['project_id_current']])) {
         // set it to the first project id in the list
         foreach ($data['_projects'] as $k => $v) {
             $_SESSION['project_id_current'] = $k;
             break;
         }
     }
     // set current project id
     $data['_project_id_selected'] = $_SESSION['project_id_current'];
     $this->_project_id_selected = $data['_project_id_selected'];
     // bind the data the template
     $this->template->bind('data', $data);
 }
Example #6
0
 public function action_allposts()
 {
     $post_model = Model::factory('Post');
     $post_model->query_posts();
     $view = View::factory('site')->set('posts', $post_model->posts);
     $this->response->body($view);
 }
Example #7
0
 public function __construct(Request $request, Response $response)
 {
     parent::__construct($request, $response);
     $this->contentModel = Model::factory('Content');
     $this->newsModel = Model::factory('News');
     $this->template = $this->contentModel->getTemplate();
 }
Example #8
0
 public function insert($file, array $callback, $scan_info)
 {
     $class = $callback[0];
     $method = $callback[1];
     $class = Model::factory($class);
     $this->_handle = fopen($file, 'r');
     $headers = fgetcsv($this->_handle, $file);
     $scan_data = array();
     $file = new SplFileObject($file);
     $file->setFlags(SplFileObject::SKIP_EMPTY);
     $file->setFlags(SplFileObject::READ_AHEAD);
     $file->setFlags(SplFileObject::READ_CSV);
     $file->setCsvControl(",", '"', "\"");
     $c = 0;
     foreach ($file as $row) {
         $c++;
         if (count($row) === count($headers)) {
             $scan_data[] = array_combine($headers, $row);
             $row = array();
         }
         if ($c % $this->insert_threshold == 0) {
             Logger::msg('info', array('message' => 'flushing ' . $this->insert_threshold . ' rows', "class" => $callback[0], "method" => $callback[1], 'rows_inserted' => $c));
             Logger::msg('info', array('memory_usage' => $this->file_size(memory_get_usage())));
             $flush = $class->{$method}($scan_data, $scan_info);
             $scan_data = array();
         }
     }
     $flush = $class->{$method}($scan_data, $scan_info);
     $scan_data = array();
     Logger::msg('info', array('memory_usage' => $this->file_size(memory_get_usage())));
     return $c;
 }
 public function mainView($file, $data)
 {
     $role_id = $this->isAdmin();
     if ($role_id < 1) {
         return $this->redirect('admin/login/index');
     }
     $functions = Model::factory('Sys')->userFunction($role_id);
     $menus = array();
     $market = false;
     foreach ($functions as $func) {
         $menus[$func->app_id]['title'] = $func->app_name;
         $menus[$func->app_id]['code'] = $func->app_ename;
         $menus[$func->app_id]['img'] = $func->app_img;
         if ($func->func_ename == 'PersonalSetting') {
             $market = true;
         }
         $menus[$func->app_id]['children'][$func->func_id]['title'] = $func->func_name;
         $menus[$func->app_id]['children'][$func->func_id]['code'] = $func->func_ename;
         $menus[$func->app_id]['children'][$func->func_id]['url'] = $func->func_url;
         $menus[$func->app_id]['children'][$func->func_id]['img'] = $func->func_img;
     }
     $data['admin_menus'] = $menus;
     $data['main_content'] = View::factory($file, $data);
     $data['market'] = $market;
     echo View::factory('admin/main', $data);
 }
Example #10
0
 public function create_new($post, $discussion_id, $reply_comment_id = NULL)
 {
     $comment = NULL;
     if (isset($post['text']) && isset($discussion_id)) {
         $user = Auth::instance()->get_user();
         $comment = Model::factory('Comment');
         $values = array();
         $values["text"] = $post['text'];
         $values["discussion_id"] = $discussion_id;
         if ($user) {
             $values["user_id"] = $user->id;
         } else {
             if ($post['author_visitor'] != "") {
                 $values["author_visitor"] = $post['author_visitor'];
             }
         }
         $values["reply_comment_id"] = $reply_comment_id;
         $comment->values($values, array_keys($values));
         try {
             $comment->save();
             Notifications::factory()->new_comment($comment->reload());
         } catch (ORM_Validation_Exception $e) {
             $errors = $e->errors('models');
         }
     }
     return $comment;
 }
Example #11
0
File: SEO.php Project: andygoo/cms
 public static function getSeriesPinyin()
 {
     $redis = Cache::instance('redis');
     $cache_key = '_ALL_SERIES_PINYIN_';
     $data = $redis->get($cache_key);
     if (empty($data)) {
         $m_brand = Model::factory('auto_series');
         $data = $m_brand->getAll('', 'id,pinyin')->as_array();
         $data = array_column($data, 'pinyin', 'id');
         $data = array_map(function ($v) {
             return preg_replace('/[^0-9a-z]/', '', strtolower($v));
         }, $data);
         $tmp = array();
         foreach ($data as $id => $pinyin) {
             if (isset($tmp[$pinyin])) {
                 $tmp[$pinyin] += 1;
                 $data[$id] = $pinyin . $tmp[$pinyin];
             } else {
                 $tmp[$pinyin] = 1;
             }
         }
         $redis->setex($cache_key, 86400, json_encode($data));
     } else {
         $data = json_decode($data, true);
     }
     return $data;
 }
Example #12
0
 static function saveTree($meanings, $lexem)
 {
     $seenMeaningIds = array();
     // Keep track of the previous meaning ID at each level. This allows us to populate the parentId field
     $meaningStack = array();
     $displayOrder = 1;
     foreach ($meanings as $tuple) {
         $m = $tuple->id ? self::get_by_id($tuple->id) : Model::factory('Meaning')->create();
         $m->parentId = $tuple->level ? $meaningStack[$tuple->level - 1] : 0;
         $m->displayOrder = $displayOrder++;
         $m->breadcrumb = $tuple->breadcrumb;
         $m->userId = session_getUserId();
         $m->lexemId = $lexem->id;
         $m->internalRep = $tuple->internalRep;
         $m->htmlRep = AdminStringUtil::htmlize($m->internalRep, 0);
         $m->internalComment = $tuple->internalComment;
         $m->htmlComment = AdminStringUtil::htmlize($m->internalComment, 0);
         $m->save();
         $meaningStack[$tuple->level] = $m->id;
         $sourceIds = StringUtil::explode(',', $tuple->sourceIds);
         MeaningSource::updateList(array('meaningId' => $m->id), 'sourceId', $sourceIds);
         $meaningTagIds = StringUtil::explode(',', $tuple->meaningTagIds);
         MeaningTagMap::updateList(array('meaningId' => $m->id), 'meaningTagId', $meaningTagIds);
         foreach ($tuple->relationIds as $type => $lexemIdString) {
             if ($type) {
                 $lexemIds = StringUtil::explode(',', $lexemIdString);
                 Relation::updateList(array('meaningId' => $m->id, 'type' => $type), 'lexemId', $lexemIds);
             }
         }
         $seenMeaningIds[] = $m->id;
     }
     self::deleteNotInSet($seenMeaningIds, $lexem->id);
 }
Example #13
0
 /**
  * 角色列表
  */
 public function action_list()
 {
     $total = Model::factory('Role')->countRoles()->getArray();
     $pagination = Pagination::factory($total);
     $roles = Model::factory('Role')->getRolesByLimit($pagination->offset(), $pagination->number())->getObject();
     $this->_default->content = View::factory('role/list')->set('roles', $roles)->set('pagination', $pagination);
 }
Example #14
0
 public function postPostNew($request, $response, $args)
 {
     if (!$this->app->auth()->isLoggedIn()) {
         $response = new \RedirectResponse('/unauthorised');
         return $response;
     }
     $template = $this->twig->loadTemplate('post/new.twig');
     $validator = new \Valitron\Validator(array('title' => $this->app->input()->post('title'), 'body' => $this->app->input()->post('body'), 'status' => $this->app->input()->post('status')));
     $validator->rule('required', ['title', 'body', 'status']);
     $validator->rule('integer', ['status']);
     if ($validator->validate()) {
         $post = \Model::factory('App\\Models\\Post')->create();
         $post->title = $this->app->input()->post('title');
         $post->body = $this->app->input()->post('body');
         $post->created_at = date('Y-m-d H:i:s');
         $post->updated_at = date('Y-m-d H:i:s');
         $post->status = $this->app->input()->post('status');
         if ($post->save()) {
             $response = new RedirectResponse('/');
             return $response;
         } else {
             $response->setContent($template->render(['errors' => [['Unable to create post']], 'input' => $this->app->input()->all('post')]));
             return $response;
         }
     } else {
         $response->setContent($template->render(['errors' => $validator->errors(), 'input' => $this->app->input()->all('post')]));
         return $response;
     }
 }
Example #15
0
    public function indexAction()
    {
        $this->_resource->addJs('/js/lib/jquery.js', 1);
        Model::factory('Medialib')->includeScripts();
        $this->_resource->addJs('/js/app/system/designer/lang/' . $this->_config->get('lang') . '.js', 1);
        $this->_resource->addCss('/js/app/system/designer/style.css');
        $this->_resource->addCss('/js/lib/CodeMirror/lib/codemirror.css');
        $this->_resource->addCss('/js/lib/CodeMirror/lib/util/dialog.css');
        $this->_resource->addCss('/js/lib/CodeMirror/lib/util/simple-hint.css');
        $this->_resource->addCss('/js/lib/CodeMirror/theme/eclipse.css');
        $dbConfigs = array();
        foreach ($this->_configMain->get('db_configs') as $k => $v) {
            $dbConfigs[] = array('id' => $k, 'title' => $this->_lang->get($v['title']));
        }
        $componentTemplates = Config::factory(Config::File_Array, $this->_configMain['configs'] . 'designer_templates.php')->__toArray();
        $this->_resource->addInlineJs('
		      var dbConfigsList = ' . json_encode($dbConfigs) . ';    
		      var componentTemplates = ' . json_encode(array_values($componentTemplates)) . ';  
		');
        $count = 4;
        foreach (self::$_externalScripts as $path) {
            $this->_resource->addJs($path, $count);
            $count++;
        }
        if (!$this->_config->get('development')) {
            $this->_resource->addJs($this->_config->get('compiled_js') . '?v=' . $this->_version, $count);
        } else {
            foreach (self::$_scripts as $path) {
                $this->_resource->addJs($path, $count);
                $count++;
            }
        }
    }
Example #16
0
 /**
  * @todo add assertations
  */
 public function testGetListVc()
 {
     $pageModel = Model::factory('Page');
     $page = $this->createPage();
     $items = $pageModel->getListVc(array(), array('code' => $page->get('code')), false, array('id', 'code'));
     $this->assertEquals($page->get('code'), $items[0]['code']);
 }
Example #17
0
File: Mysql.php Project: ofeige/opf
 public function handle(Event $event)
 {
     $context = $event->getContext();
     $user = \Model::factory($this->modelName)->where('email', $context[AuthEventHandler::authName])->find_one();
     $user->set_expr('lastlogin', 'NOW()');
     $user->save();
 }
Example #18
0
 public function testGetTable()
 {
     $cfg = Db_Object_Config::getInstance('Page');
     $prefix = Model::factory('page')->getDbPrefix();
     $this->assertEquals($cfg->getTable(false), $cfg->get('table'));
     $this->assertEquals($cfg->getTable(), $prefix . $cfg->get('table'));
 }
Example #19
0
File: jx.php Project: jonlb/JxCMS
 /**
  * Logs a user in.
  *
  * @param   string   username
  * @param   string   password
  * @param   boolean  enable auto-login
  * @return  boolean
  */
 public function _login($user, $password, $remember)
 {
     // Make sure we have a user object
     //Jx_Debug::dump($user,'User passed in');
     $user = $this->_get_object($user);
     //Jx_Debug::dump(null,'In _login');
     //Jx_Debug::dump($user->password,'User password after getting object');
     //Jx_Debug::dump($password,'Password passed in');
     // If the passwords match, perform a login
     if (Jx_Acl::check_for_cap('allow_login', $user) and $user->password === $password) {
         if ($remember === TRUE) {
             // Create a new autologin token
             $token = Model::factory('user_token');
             // Set token data
             $token->user = $user->id;
             $token->expires = time() + $this->_config['lifetime'];
             $token->create();
             // Set the autologin Cookie
             Cookie::set('authautologin', $token->token, $this->_config['lifetime']);
         }
         // Finish the login
         //Jx_Debug::dump(null, 'finishing login');
         $this->complete_login($user);
         return TRUE;
     }
     // Login failed
     return FALSE;
 }
Example #20
0
 /**
  * start login
  */
 public function action_login()
 {
     $username = Arr::get($_POST, 'username', '');
     $password = Arr::get($_POST, 'password', '');
     if (!$username || !$password) {
         return Prompt::warningView('用户名密码不能为空', 'author');
     }
     try {
         $account = Model::factory('Account')->getAccountByName($username)->getArray();
         if (!$account[0]) {
             //日志
             return Prompt::errorView('用户名不存在', 'author');
         }
     } catch (Exception $e) {
         //日志
         echo $e->getMessage();
         exit;
         return Prompt::errorView('登录失败', 'author');
     }
     if ($account[0]['password'] && $account[0]['password'] === md5($password)) {
         //保存 seesion 信息
         Session::instance()->set('author', $account[0]);
         return Controller::redirect('/');
     } else {
         return Prompt::errorView('登录失败', 'author');
     }
 }
Example #21
0
 /**
  * Get Pages tree
  * @return array
  */
 public function getTreeList(array $fields, $author = false, $publisher = false)
 {
     /*
      * Add the required fields to the list
      */
     $fields = array_unique(array_merge(array('id', 'parent_id', 'order_no', 'code', 'menu_title', 'is_fixed'), $fields));
     $data = $this->getListVc(array('sort' => 'order_no', 'dir' => 'ASC'), false, false, $fields, $author, $publisher);
     if (empty($data)) {
         return array();
     }
     $ids = Utils::fetchCol('id', $data);
     $vc = Model::factory('Vc');
     $maxRevisions = $vc->getLastVersion('page', $ids);
     foreach ($data as $k => &$v) {
         if (isset($maxRevisions[$v['id']])) {
             $v['last_version'] = $maxRevisions[$v['id']];
         } else {
             $v['last_version'] = 0;
         }
     }
     unset($v);
     if (empty($data)) {
         return array();
     }
     $tree = new Tree();
     foreach ($data as $value) {
         if (!$value['parent_id']) {
             $value['parent_id'] = 0;
         }
         $tree->addItem($value['id'], $value['parent_id'], $value, $value['order_no']);
     }
     return $this->_fillChilds($tree, 0);
 }
 public function getPostView($request, $response, $args)
 {
     $template = $this->twig->loadTemplate('post/view.twig');
     $post = \Model::factory('\\App\\Models\\Post')->find_one($args['id']);
     $response->setContent($template->render(['post' => $post]));
     return $response;
 }
Example #23
0
 public function action_addpost()
 {
     if (!Auth::instance()->logged_in()) {
         $this->request->redirect("admin");
     }
     $news = Model::factory("post");
     $this->template->scripts = array('/js/admin/post.js');
     if (!empty($_POST)) {
         // сохранение поста
         $post['dates'] = $_POST['d']['date'];
         $post['language'] = "ru";
         $post['publ'] = $_POST['d']['publ'];
         $post['name'] = $_POST['d']['name'];
         $post['title'] = $_POST['d']['title'];
         $post['keywords'] = $_POST['d']['keys'];
         $post['description'] = $_POST['d']['description'];
         $post['anons'] = $_POST['d']['anons'];
         $post['content'] = $_POST['d']['content'];
         $post['image'] = $_POST['d']['image'];
         $res = $news->saveNewPost($post);
         //if($res){
         $this->request->redirect("adminPost");
         //}
         $this->template->content = View::factory('admin/post/edit.tpl', array("post" => $post));
     }
     $this->template->content = View::factory('admin/post/edit.tpl');
 }
Example #24
0
function fetchNextRow($row)
{
    global $lexemDbResult;
    global $sourceMap;
    global $currentLexem;
    $def = Model::factory('Definition')->create($row);
    $def->internalRep = AdminStringUtil::xmlizeRequired($def->internalRep);
    if (hasFlag('d')) {
        $def->internalRep = AdminStringUtil::xmlizeOptional($def->internalRep);
    }
    $lexemNames = array();
    $lexemLatinNames = array();
    while (merge_compare($def, $currentLexem) < 0) {
        $currentLexem = $lexemDbResult->fetch();
    }
    while (merge_compare($def, $currentLexem) == 0) {
        $lexemNames[] = $currentLexem[1];
        $lexemLatinNames[] = StringUtil::unicodeToLatin($currentLexem[1]);
        $currentLexem = $lexemDbResult->fetch();
    }
    SmartyWrap::assign('def', $def);
    SmartyWrap::assign('lexemNames', $lexemNames);
    SmartyWrap::assign('lexemLatinNames', $lexemLatinNames);
    SmartyWrap::assign('source', $sourceMap[$def->sourceId]);
    SmartyWrap::assign('user', userCache_get($def->userId));
}
Example #25
0
 public function action_update()
 {
     $this->template = View::factory('return');
     $user = Model::factory('user');
     $return = $user->hardcore_data($_GET['uid']);
     $this->template->return = json_encode($return);
 }
Example #26
0
 /**
  * Get object history
  */
 public function listAction()
 {
     $object = Request::post('object', 'string', false);
     if (!$object) {
         Response::jsonSuccess(array());
     }
     $pager = Request::post('pager', 'array', array());
     $filter = Request::post('filter', 'array', array());
     if (!isset($filter['record_id']) || empty($filter['record_id'])) {
         Response::jsonSuccess(array());
     }
     try {
         $o = new Db_Object($object);
     } catch (Exception $e) {
         Response::jsonSuccess(array());
     }
     $filter['table_name'] = $o->getTable();
     $history = Model::factory('Historylog');
     $data = $history->getListVc($pager, $filter, false, array('date', 'type', 'id'), 'user_name');
     if (!empty($data)) {
         foreach ($data as $k => &$v) {
             if (isset(Model_Historylog::$actions[$v['type']])) {
                 $v['type'] = Model_Historylog::$actions[$v['type']];
             }
         }
         unset($v);
     }
     Response::jsonSuccess($data, array('count' => $history->getCount($filter)));
 }
Example #27
0
 public static function searchNGram($cuv)
 {
     $leng = mb_strlen($cuv);
     $hash = NGram::searchLexemIds($cuv);
     if (empty($hash)) {
         return array();
     }
     arsort($hash);
     $max = current($hash);
     $lexIds = array_keys($hash, $max);
     $results = array();
     foreach ($lexIds as $id) {
         $lexem = Model::factory('Lexem')->where('id', $id)->where_gte('charLength', $leng - self::$LENGTH_DIF)->where_lte('charLength', $leng + self::$LENGTH_DIF)->find_one();
         if ($lexem) {
             $results[] = $lexem;
             if (count($results) == self::$MAX_RESULTS) {
                 break;
             }
         }
     }
     // Sort the lexems by their Levenshtein distance from $cuv
     $distances = array();
     foreach ($results as $lexem) {
         $distances[] = Levenshtein::dist($cuv, $lexem->formNoAccent);
     }
     array_multisort($distances, $results);
     return $results;
 }
Example #28
0
function session_login($user, $openidData)
{
    if (!$user) {
        $user = Model::factory('User')->create();
    }
    if (!$user->identity) {
        $user->identity = $openidData['identity'];
    }
    if (!$user->openidConnectSub && isset($openidData['sub'])) {
        $user->openidConnectSub = $openidData['sub'];
    }
    if (!$user->nick && isset($openidData['nickname'])) {
        $user->nick = $openidData['nickname'];
    }
    if (isset($openidData['fullname'])) {
        $user->name = $openidData['fullname'];
    }
    if (isset($openidData['email'])) {
        $user->email = $openidData['email'];
    }
    $user->password = null;
    // no longer necessary after the first OpenID login
    $user->save();
    session_setVariable('user', $user);
    $cookie = Model::factory('Cookie')->create();
    $cookie->userId = $user->id;
    $cookie->cookieString = util_randomCapitalLetterString(12);
    $cookie->save();
    setcookie("prefs[lll]", $cookie->cookieString, time() + ONE_MONTH_IN_SECONDS, '/');
    log_userLog('Logged in, IP=' . $_SERVER['REMOTE_ADDR']);
    util_redirect(util_getWwwRoot());
}
Example #29
0
 /**
  * 账号列表
  */
 public function action_list()
 {
     $total = Model::factory('Account')->countAccounts()->getArray();
     $pagination = Pagination::factory($total);
     $accounts = Model::factory('Account')->getAccountsByLimit($pagination->offset(), $pagination->number())->getObject();
     $this->_default->content = View::factory('account/list')->set('accounts', $accounts)->set('pagination', $pagination);
 }
Example #30
0
 public function get_all($uids, $pid, $fields)
 {
     $uids = $this->prepare_param($uids, array('Valid', 'numeric'));
     $fields = $this->prepare_param($fields);
     $pages = DB::select('id', 'parent_id', 'slug', 'title')->select_array($this->filtered_fields($fields))->from($this->_table_name);
     if (!empty($uids)) {
         $pages->where('id', 'in', $uids);
     }
     if (!empty($pid)) {
         $pages->where('parent_id', '=', (int) $pid);
     }
     $pages = $pages->execute()->as_array('id');
     if (in_array('parts', $fields)) {
         $parts = Model::factory('api_page_part')->get(array_keys($pages), array_merge($fields, array('page_id')));
         if (is_array($parts)) {
             foreach ($parts as $part) {
                 if (isset($pages[$part['page_id']])) {
                     $pages[$part['page_id']]['parts'][$part['id']] = $part;
                     unset($pages[$part['page_id']]['parts'][$part['id']]['page_id']);
                 }
             }
         }
     }
     return $this->create_tree($pages, $fields);
 }