예제 #1
0
파일: Ocr.php 프로젝트: rasstroen/metro
    public static function setStatus($id_user, $id_book, $status, $state)
    {
        global $current_user;
        $book = Books::getInstance()->getByIdLoaded($id_book);
        /* @var $book Book */
        if ($book->getQuality() >= BOOK::BOOK_QUALITY_BEST) {
            throw new Exception('book quality is best, you cant fix states');
        }
        if (!isset(self::$statuses[$status])) {
            throw new Exception('no status #' . $status);
        }
        if (!isset(self::$states[$state])) {
            throw new Exception('no status #' . $state);
        }
        $can_comment = false;
        if ($state > 0) {
            $query = 'SELECT `time` FROM `ocr` WHERE  `id_book`=' . $id_book . ' AND `id_user`=' . $id_user . ' AND `status`=' . $status . ' AND `state`=' . $state;
            $last_time = Database::sql2single($query);
            if (time() - $last_time > 24 * 60 * 60) {
                $can_comment = true;
            }
        }
        if ($state == 0 && $status !== 0) {
            // delete
            $query = 'DELETE FROM `ocr` WHERE  `id_book`=' . $id_book . ' AND `id_user`=' . $id_user . ' AND `status`=' . $status . '';
        } else {
            // upsert
            $query = 'INSERT INTO `ocr` SET `id_book`=' . $id_book . ', `id_user`=' . $id_user . ', `status`=' . $status . ',`state`=' . $state . ',`time`=' . time() . '
			ON DUPLICATE KEY UPDATE
			`time`=' . time() . ', `state`=' . $state;
        }
        if (!Database::query($query, false)) {
            throw new Exception('Duplicating #book ' . $id_book . ' #status' . $status . ' #state' . $state);
        }
        if ($state == 0) {
            $comment = 'User ' . $current_user->id . ' drop status ' . $status . ' state ' . $state . ' user_id ' . $id_user;
        } else {
            $comment = 'User ' . $current_user->id . ' set status ' . $status . ' state ' . $state . ' user_id ' . $id_user;
        }
        $comUser = Users::getById($id_user);
        /* @var $comUser User */
        if ($can_comment && ($part = self::getMessagePart($status, $state))) {
            $comment = mb_strtolower($part, 'UTF-8') . ' книгу';
            MongoDatabase::addSimpleComment(BiberLog::TargetType_book, $id_book, $id_user, $comment);
        }
    }
예제 #2
0
파일: Notify.php 프로젝트: rasstroen/metro
 public static function notifyGenreNewBook($id_genre, $id_book)
 {
     global $current_user;
     $query = 'SELECT `id_user` FROM `genre_subscribers` WHERE `id_genre`=' . (int) $id_genre;
     $user_ids = array_keys(Database::sql2array($query, 'id_user'));
     if (isset($user_ids[$current_user->id])) {
         unset($user_ids[$current_user->id]);
     }
     if (count($user_ids)) {
         $genre = Database::sql2single('SELECT `title` FROM `genre` WHERE `id`=' . $id_genre);
         $book = Books::getInstance()->getByIdLoaded($id_book);
         /* @var $person Person */
         $subject = 'Добавлена книга в жанре ' . $genre;
         /* @var $book Book */
         $message = 'Книга <a href="/b/' . $book->id . '">' . $book->getTitle(1) . '</a> добавлена';
         self::send($user_ids, $subject, $message, UserNotify::UN_G_NEW_GENRES);
     }
 }
예제 #3
0
파일: Books.php 프로젝트: rasstroen/metro
 public function _after_idsToData($data)
 {
     $aids = array();
     foreach ($data['books'] as $bookid => $d) {
         $book = Books::getInstance()->getByIdLoaded($bookid);
         $aid = $book->getAuthorId();
         if ($aid) {
             $aids[$aid] = $aid;
         }
     }
     if (count($aids)) {
         $persons = Persons::getInstance()->getByIdsLoaded($aids);
         foreach ($persons as $person) {
             $data['authors'][] = $person->getListData();
         }
     } else {
         $data['authors'] = array();
     }
     return $data;
 }
예제 #4
0
    function addLoved()
    {
        global $current_user;
        $event = new Event();
        /* @var $current_user CurrentUser */
        if (!$current_user->authorized) {
            $this->error('Auth');
            return;
        }
        $item_type = isset($_POST['item_type']) ? $_POST['item_type'] : false;
        $item_id = isset($_POST['item_id']) ? (int) $_POST['item_id'] : false;
        if (!$item_type || !$item_id) {
            $this->error('item_id or item_type missed');
            return;
        }
        if (!isset(Config::$loved_types[$item_type])) {
            $this->error('illegal item_type#' . $item_type);
            return;
        }
        $query = 'INSERT INTO `users_loved` SET `id_target`=' . $item_id . ',`target_type`=' . Config::$loved_types[$item_type] . ',`id_user`=' . $current_user->id;
        if (Database::query($query, false)) {
            $this->data['success'] = 1;
            $this->data['item_id'] = $item_id;
            $this->data['in_loved'] = 1;
            $event->event_LovedAdd($current_user->id, $item_id, $item_type);
            $event->push();
            if ($item_type == 'book') {
                $time = time();
                // inserting a new mark
                $query = 'INSERT INTO `book_rate` SET `id_book`=' . $item_id . ',`id_user`=' . $current_user->id . ',`rate`=5,`time`=' . $time . ' ON DUPLICATE KEY UPDATE
				`rate`=5 ,`time`=' . $time . ',`with_review`=0';
                Database::query($query);
                //recalculating rate
                $query = 'SELECT COUNT(1) as cnt, SUM(`rate`) as rate FROM `book_rate` WHERE `id_book`=' . $item_id;
                $res = Database::sql2row($query);
                $book_mark = round($res['rate'] / $res['cnt'] * 10);
                $book = Books::getInstance()->getById($item_id);
                /* @var $book Book */
                $book->updateLovedCount();
                $query = 'UPDATE `book` SET `mark`=' . $book_mark . ' WHERE `id`=' . $item_id;
                Database::query($query);
            }
            return;
        } else {
            $query = 'DELETE FROM `users_loved` WHERE `id_target`=' . $item_id . ' AND `target_type`=' . Config::$loved_types[$item_type] . ' AND `id_user`=' . $current_user->id;
            if (Database::query($query, false)) {
                $this->data['success'] = 1;
                $this->data['item_id'] = $item_id;
                $this->data['in_loved'] = 0;
                if ($item_type == 'book') {
                    $book = Books::getInstance()->getById($item_id);
                    /* @var $book Book */
                    $book->updateLovedCount();
                }
                return;
            } else {
                $this->data['success'] = 0;
            }
        }
    }
예제 #5
0
 function getBookContributionComments()
 {
     global $current_user;
     /* @var $current_user CurrentUser */
     $id_book = isset($this->params['book_id']) ? (int) $this->params['book_id'] : false;
     if (!$id_book) {
         return;
     }
     $book = Books::getInstance()->getByIdLoaded($id_book);
     /* @var $book Book */
     if (!$book->exists) {
         throw new Exception('book #' . $book->id . ' not exists');
     }
     $cond = new Conditions();
     $per_page = 0;
     if (isset($this->params['per_page'])) {
         $per_page = (int) $this->params['per_page'];
     }
     $per_page = $per_page > 0 ? $per_page : 20;
     $pagingName = isset($this->params['paging_parameter_name']) ? $this->params['paging_parameter_name'] : 'p';
     $cond->setPaging(1000, $per_page, $pagingName);
     $limit = $cond->getMongoLimit();
     list($comments, $count) = MongoDatabase::getBookComments($id_book, $per_page, $limit);
     $uids = array();
     $comments['comments'] = isset($comments['comments']) ? $comments['comments'] : array();
     foreach ($comments['comments'] as &$comment) {
         $comment['commenter_id'] = $comment['user_id'];
         $comment['type'] = 'book';
         $comment['time'] = date('Y/m/d H:i:s', $comment['time']);
         $uids[$comment['user_id']] = $comment['user_id'];
     }
     $cond = new Conditions();
     $cond->setPaging($count, $per_page, $pagingName);
     $this->data['conditions'] = $cond->getConditions();
     $this->data['comments'] = isset($comments['comments']) ? $comments['comments'] : array();
     $this->data['comments']['title'] = 'Обсуждение книги «' . $book->getTitle(true) . '»';
     $this->data['comments']['count'] = $count;
     $this->data['users'] = $this->getCommentsUsers($uids);
 }
예제 #6
0
 function getStatBooks($ids, $opts = array(), $limit = false)
 {
     $person_id = isset($opts['person_id']) ? $opts['person_id'] : false;
     $books = Books::getInstance()->getInstance()->getByIdsLoaded($ids);
     Books::getInstance()->getInstance()->LoadBookPersons($ids);
     $out = array();
     $aids = array();
     /* @var $book Book */
     $i = 0;
     if (is_array($books)) {
         foreach ($books as &$book) {
             if ($limit && ++$i > $limit) {
                 return $out;
             }
             $tmp = $book->getListData();
             list($author_id, $name) = $book->getAuthor();
             if ($author_id) {
                 $aids[$author_id] = $author_id;
             }
             $tmp['path'] = Config::need('www_path') . '/admin/books/' . $book->id;
             $out[] = $tmp;
         }
     }
     return array($out, $aids);
 }
예제 #7
0
 function getOne($for_editing = false)
 {
     if ($this->genre_id) {
         $query = 'SELECT * FROM `genre` WHERE `id`=' . Database::escape($this->genre_id);
     } else {
         $query = 'SELECT * FROM `genre` WHERE `name`=' . Database::escape($this->genre_name);
     }
     $data = Database::sql2row($query);
     if (!isset($data['name'])) {
         return;
     }
     $this->data['genre'] = array('name' => $data['name'], 'id' => $data['id'], 'id_parent' => $data['id_parent'], 'title' => $data['title'], 'description' => $data['description'], 'books_count' => $data['books_count'], 'path' => Config::need('www_path') . '/genres/' . $data['id'], 'path_edit' => Config::need('www_path') . '/genres/' . $data['id'] . '/edit');
     Request::pass('genre-title', $data['title']);
     if (!$data['id_parent']) {
         $this->data['genre']['subgenres'] = $this->getAll($data['id']);
         return;
     }
     if (!$for_editing) {
         $query = 'SELECT COUNT(1) FROM `book_genre` BG JOIN `book` B ON B.id = BG.id_book WHERE BG.id_genre = ' . $data['id'] . '';
         $count = Database::sql2single($query);
         $cond = new Conditions();
         $cond->setPaging($count, 20);
         $limit = $cond->getLimit();
         $this->data['conditions'] = $cond->getConditions();
         $query = 'SELECT `id_book` FROM `book_genre` BG JOIN `book` B ON B.id = BG.id_book WHERE BG.id_genre = ' . $data['id'] . ' ORDER BY B.mark DESC LIMIT ' . $limit;
         $bids = Database::sql2array($query, 'id_book');
         $books = Books::getInstance()->getByIdsLoaded(array_keys($bids));
         Books::getInstance()->LoadBookPersons(array_keys($bids));
         $aids = array();
         foreach ($books as $book) {
             $book = Books::getInstance()->getById($book->id);
             list($aid, $aname) = $book->getAuthor(1, 1, 1);
             // именно наш автор, если их там много
             $this->data['genre']['books'][$book->id] = $book->getListData();
             $aids[$aid] = $aid;
         }
         if (count($aids)) {
             $persons = Persons::getInstance()->getByIdsLoaded($aids);
             foreach ($persons as $person) {
                 $this->data['genre']['authors'][] = $person->getListData();
             }
         }
         $this->data['parent'] = array();
         if ($data['id_parent']) {
             $data = Database::sql2row('SELECT * FROM `genre` WHERE `id`=' . Database::escape($data['id_parent']));
             $this->data['genre']['parent'][] = array('name' => $data['name'], 'id' => $data['id'], 'id_parent' => $data['id_parent'], 'title' => $data['title'], 'description' => $data['description'], 'books_count' => $data['books_count'], 'path' => Config::need('www_path') . '/genres/' . $data['id'], 'path_edit' => Config::need('www_path') . '/genres/' . $data['id'] . '/edit');
         }
     }
 }
예제 #8
0
 function getContributionBooks($ids)
 {
     $person_id = isset($opts['person_id']) ? $opts['person_id'] : false;
     $books = Books::getInstance()->getInstance()->getByIdsLoaded($ids);
     Books::getInstance()->getInstance()->LoadBookPersons($ids);
     $out = array();
     $aids = array();
     /* @var $book Book */
     if (is_array($books)) {
         foreach ($books as $book) {
             $out[] = $book->getListData();
             list($author_id, $name) = $book->getAuthor();
             if ($author_id) {
                 $aids[$author_id] = $author_id;
             }
         }
     }
     return array($out, $aids);
 }
예제 #9
0
 function generateData()
 {
     global $current_user;
     /* @var $current_user CurrentUser */
     if (!$current_user->authorized) {
         throw new Exception('Auth required');
     }
     $current_user->can_throw('books_download');
     $filetype = Request::get(0);
     list($id_file, $id_book) = explode('_', Request::get(1));
     $can_load = $current_user->canBookDownload($id_book, $id_file);
     if ($can_load !== true) {
         if ($can_load[1]) {
             throw new Exception('You cant download this book - limit of a ' . $can_load[1] . ' books in day exceed');
         } else {
             throw new Exception('Please prolong your subscription, сучечка!');
         }
     }
     $book = Books::getInstance()->getByIdLoaded($id_book);
     /* @var $book Book */
     if (!$book->loaded) {
         throw new Exception('Book doesn\'t exists');
     }
     if (!$filetype || !$id_file || !$id_book) {
         throw new Exception('Wrong download url');
     }
     $realPath = getBookFilePath($id_file, $id_book, $filetype, Config::need('files_path'));
     global $dev_mode;
     if (!is_readable($realPath)) {
         if ($dev_mode) {
             throw new Exception('Sorry, file ' . $realPath . ' doesn\'t exists');
         } else {
             throw new Exception('Sorry, file  doesn\'t exists');
         }
     }
     $current_user->onBookDownload($book->id);
     $current_user->save();
     if (Request::get('html') !== false) {
         // downloading generated html
         $book->getHTMLDownload();
         $realPath = getBookFilePathFB2HtmlDownload($id_file, $id_book, $filetype, Config::need('files_path'));
         $filetype = 4;
     }
     @ob_end_clean();
     $ft = Config::need('filetypes');
     $book->setReaded();
     if (Config::need('smart_download')) {
         header("Content-Type: application/force-download");
         header("Content-Type: application/octet-stream");
         header("Content-Type: application/download");
         header("Content-Description: File Transfer");
         header('Content-Disposition: attachment; filename="' . $book->getTitle(1) . '.' . $ft[$filetype]);
         header("X-Accel-Redirect: " . str_replace('/w/ru.jnpe.ls2/core', '', $realPath));
         exit;
     }
     //
     header('Content-Disposition: attachment; filename="' . $book->getTitle(1) . '.' . $ft[$filetype]);
     header("Content-Type: application/force-download");
     header("Content-Type: application/octet-stream");
     header("Content-Type: application/download");
     header("Content-Description: File Transfer");
     readfile($realPath);
     exit;
 }
예제 #10
0
파일: Search.php 프로젝트: rasstroen/metro
 public function updateBooksFull($bids)
 {
     $documents = array();
     Books::$books_instance = false;
     // cached books?
     Persons::$persons_instance = false;
     // cached persons?
     $books = Books::getInstance()->getByIdsLoaded($bids);
     $time = time();
     foreach ($books as $book) {
         /* @var $book Book */
         $d = $this->prepareBookFull($book);
         if ($d) {
             $documents[] = $d;
         }
     }
     $books = self::$books;
     /* @var $books Apache_Solr_Service */
     // удаляем из индекса
     $books->deleteByMultipleIds($bids);
     // добавляем в индекс
     $books->addDocuments($documents);
     // коммитим изменения
     $books->commit();
     // оптимизируем поисковую базу
     $books->optimize();
 }
예제 #11
0
 function getEventsBooks($ids, $opts = array(), $limit = false)
 {
     $person_id = isset($opts['person_id']) ? $opts['person_id'] : false;
     $books = Books::getInstance()->getByIdsLoaded($ids);
     Books::getInstance()->LoadBookPersons($ids);
     $out = array();
     $aids = array();
     /* @var $book Book */
     $i = 0;
     if (is_array($books)) {
         foreach ($books as $book) {
             if ($limit && ++$i > $limit) {
                 return $out;
             }
             $out[] = $book->getListData();
             list($author_id, $name) = $book->getAuthor();
             if ($author_id) {
                 $aids[$author_id] = $author_id;
             }
         }
     }
     return array($out, $aids);
 }
예제 #12
0
 function _glue()
 {
     global $current_user;
     $current_user->can_throw('books_edit');
     $id1 = isset(Request::$post['serie1_id']) ? (int) Request::$post['serie1_id'] : false;
     $id2 = isset(Request::$post['serie2_id']) ? (int) Request::$post['serie2_id'] : false;
     $is_1_main = isset(Request::$post['is_main']) ? true : false;
     if ($is_1_main) {
         $main_sid = $id1;
         $slave_sid = $id2;
     } else {
         $main_sid = $id2;
         $slave_sid = $id1;
     }
     if (!$main_sid || !$slave_sid) {
         throw new Exception('illegal ids');
     }
     $query = 'SELECT * FROM `series` WHERE `id` IN (' . $id1 . ',' . $id2 . ')';
     $series = Database::sql2array($query, 'id');
     if (count($series) != 2) {
         throw new Exception('illegal series');
     }
     if ($series[$main_sid]['is_s_duplicate']) {
         throw new Exception($main_sid . ' is duplicate of ' . $series[$main_sid]['is_s_duplicate']);
     }
     Database::query('START TRANSACTION');
     // set new parent_id for all subseries for slave
     $query = 'SELECT `id` FROM `series` WHERE `id_parent`=' . $slave_sid;
     $changed_parents = Database::sql2array($query, 'id');
     if (count($changed_parents)) {
         $query = 'UPDATE `series` SET `id_parent`=' . $main_sid . ' WHERE `id` IN (' . array_keys($changed_parents) . ')';
         Database::query($query);
     }
     // set new serie_id for all books for slave
     $query = 'SELECT `id_book` FROM `book_series` WHERE `id_series`=' . $slave_sid;
     $books = Database::sql2array($query, 'id_book');
     $query = 'UPDATE `book_series` SET `id_series`=' . $main_sid . ' WHERE `id_series`=' . $slave_sid;
     Database::query($query);
     // slave serie got is_s_duplicate flag
     $query = 'UPDATE `series` SET `is_s_duplicate`=' . $main_sid . ' WHERE `id`=' . $slave_sid;
     Database::query($query);
     // for main and slave serie - set new books count
     /* @todo */
     // writing logs
     // for each book - set new serie
     SerieLog::addGlueLog($main_sid, $slave_sid, array_keys($books), array_keys($changed_parents));
     $id_log = SerieLog::saveLog($slave_sid, BookLog::TargetType_serie, $current_user->id, BiberLog::BiberLogType_serieGlue, $copy = false);
     SerieLog::saveLogLink($id_log, $main_sid, BookLog::TargetType_serie, $current_user->id, BiberLog::BiberLogType_serieGlue, $copy = 1);
     // for subseries
     if ($books) {
         Books::getInstance()->getByIdsLoaded(array_keys($books));
         foreach ($books as $bid => $data) {
             SerieLog::saveLogLink($id_log, $bid, BookLog::TargetType_book, $current_user->id, BiberLog::BiberLogType_serieGlue, $copy = 1);
         }
     }
     // for slave serie subseries - set new parent_id
     if ($changed_parents) {
         foreach ($changed_parents as $sid => $data) {
             SerieLog::saveLogLink($id_log, $sid, BookLog::TargetType_serie, $current_user->id, BiberLog::BiberLogType_serieGlue, $copy = 1);
         }
     }
     $current_user->gainActionPoints(BiberLog::$actionTypes[BiberLog::BiberLogType_serieGlue], $main_sid, BiberLog::TargetType_serie);
     Database::query('COMMIT');
     ob_end_clean();
     $search = Search::getInstance();
     /* @var $search Search */
     $search->setSerieToFullUpdate($slave_sid);
     $search->setSerieToFullUpdate($main_sid);
     header('Location:' . Config::need('www_path') . '/s/' . $main_sid);
     exit;
 }
예제 #13
0
 private static function undo_repeat_bookNew($logdata)
 {
     $data = unserialize($logdata['data']);
     $query = 'UPDATE `book` SET `is_deleted`=0 WHERE `id`=' . $data['id_book'];
     Database::query($query);
     self::undo_repeat_bookEdit($logdata);
     Books::getInstance()->dropCache($data['id_book']);
 }
예제 #14
0
    function write()
    {
        global $current_user;
        $points_gained = false;
        /* @var $current_user CurrentUser */
        Database::query('START TRANSACTION');
        $current_user->can_throw('books_edit');
        if (!isset(Request::$post['lang_code']) || !Request::$post['lang_code']) {
            throw new Exception('field missed #lang_code');
        }
        $id = isset(Request::$post['id']) ? (int) Request::$post['id'] : false;
        if (Request::post('isbn')) {
            Request::$post['isbn'] = extractISBN(Request::$post['isbn']);
        }
        if (!$id) {
            $this->newBook();
            return;
        }
        $books = Books::getInstance()->getByIdsLoaded(array($id));
        $book = is_array($books) ? $books[$id] : false;
        if (!$book) {
            return;
        }
        /* @var $book Book */
        $fields = array('title' => 'title', 'subtitle' => 'subtitle', 'isbn' => 'ISBN', 'year' => 'year', 'lang_code' => 'id_lang', 'annotation' => 'description', 'rightholder' => 'id_rightholder');
        Request::$post['lang_code'] = Config::$langs[Request::$post['lang_code']];
        Request::$post['annotation'] = trim(prepare_review(Request::$post['annotation'], false, '<img>'));
        Request::$post['title'] = trim(prepare_review(Request::$post['title'], ''));
        Request::$post['year'] = (int) Request::$post['year'];
        $magazineData = array();
        if ($book->data['book_type'] == Book::BOOK_TYPE_MAGAZINE) {
            $magazineData = Database::sql2row('SELECT * FROM `magazines` M LEFT JOIN book_magazines BM ON BM.id_magazine=M.id WHERE BM.id_book=' . $book->id);
            $book->data['n'] = max(0, $magazineData['n']);
            $book->data['year'] = $magazineData['year'];
            Request::$post['n'] = isset(Request::$post['n']) && Request::$post['n'] ? Request::$post['n'] : $magazineData['n'];
        }
        $to_update_m = array();
        $to_update = array();
        if (isset(Request::$post['quality'])) {
            if ($book->data['quality'] != (int) Request::$post['quality']) {
                $to_update['quality'] = (int) Request::$post['quality'];
            }
        }
        if (isset(Request::$post['n'])) {
            if (isset($book->data['n']) && $book->data['n'] != (int) Request::$post['n']) {
                $to_update_m['n'] = (int) Request::$post['n'];
                Request::$post['title'] = $magazineData['title'];
                Request::$post['subtitle'] = '№ ' . $to_update_m['n'] . ' за ' . Request::$post['year'] . ' год';
            }
            if (isset($book->data['year']) && $book->data['year'] != (int) Request::$post['year']) {
                $to_update_m['n'] = (int) Request::$post['n'];
                Request::$post['title'] = $magazineData['title'];
                Request::$post['subtitle'] = '№ ' . $to_update_m['n'] . ' за ' . Request::$post['year'] . ' год';
            }
        }
        if (isset($_FILES['cover']) && $_FILES['cover']['tmp_name']) {
            $folder = Config::need('static_path') . '/upload/covers/' . ceil($book->id / 5000);
            @mkdir($folder);
            // inserting new cover
            $query = 'INSERT INTO `book_covers` SET `id_book`=' . $book->id;
            Database::query($query);
            $cover_id = Database::lastInsertId();
            // generating file names
            $filename_normal = $folder . '/default_' . $book->id . '_' . $cover_id . '.jpg';
            $filename_small = $folder . '/small_' . $book->id . '_' . $cover_id . '.jpg';
            $filename_big = $folder . '/big_' . $book->id . '_' . $cover_id . '.jpg';
            $filename_orig = $folder . '/orig_' . $book->id . '_' . $cover_id . '.jpg';
            $to_update['is_cover'] = $cover_id;
            $thumb = new Thumb();
            $thumb->createThumbnails($_FILES['cover']['tmp_name'], array($filename_small, $filename_normal, $filename_big, $filename_orig), self::$cover_sizes);
            if ($book->data['is_cover']) {
                $current_user->gainActionPoints('books_edit_cover', $book->id, BiberLog::TargetType_book);
            } else {
                $current_user->gainActionPoints('books_add_cover', $book->id, BiberLog::TargetType_book);
            }
            $points_gained = true;
        }
        // file loading
        if (isset($_FILES['file']) && isset($_FILES['file']['tmp_name']) && $_FILES['file']['tmp_name']) {
            $filetype_ = explode('.', $_FILES['file']['name']);
            $filetype_ = isset($filetype_[count($filetype_) - 1]) ? $filetype_[count($filetype_) - 1] : '';
            $fts = Config::need('filetypes');
            $filetype = false;
            foreach ($fts as $ftid => $ftname) {
                if ($ftname == $filetype_) {
                    $filetype = $ftid;
                }
            }
            if (!$filetype) {
                throw new Exception('wrong filetype:' . $filetype_);
            }
            $destinationDir = Config::need('files_path') . DIRECTORY_SEPARATOR . getBookFileDirectory($book->id, $filetype);
            @mkdir($destinationDir, 0755);
            // добавляем запись в базу
            $filesize = $_FILES['file']['size'];
            $query = 'SELECT * FROM `book_files` WHERE `id_book`=' . $book->id;
            $files = Database::sql2array($query, 'filetype');
            // replacing file
            if (isset($files[$filetype])) {
                $old_id_file = $files[$filetype]['id'];
                $old_id_file_author = $files[$filetype]['id_file_author'];
                $old_filesize = $files[$filetype]['filesize'];
                $query = 'DELETE FROM `book_files` WHERE `id`=' . $old_id_file;
                Database::query($query);
                $query = 'INSERT IGNORE INTO `book_files` SET
				`id_book`=' . $book->id . ',
				`filetype`=' . $filetype . ',
				`id_file_author`=' . $current_user->id . ',
				`modify_time`=' . time() . ',
				`filesize`=' . $filesize;
                Database::query($query);
                $id_file = Database::lastInsertId();
                BookLog::addLog(array('id_file' => $id_file, 'filetype' => $filetype, 'id_file_author' => $current_user->id, 'filesize' => $filesize), array('id_file' => $old_id_file, 'filetype' => 0, 'id_file_author' => $old_id_file_author, 'filesize' => $old_filesize), $book->id);
                Database::query($query);
                $current_user->gainActionPoints('books_edit_file', $book->id, BiberLog::TargetType_book);
            } else {
                $query = 'INSERT INTO `book_files` SET
				`id_book`=' . $book->id . ',
				`filetype`=' . $filetype . ',
				`id_file_author`=' . $current_user->id . ',
				`modify_time`=' . time() . ',
				`filesize`=' . $filesize;
                Database::query($query);
                $id_file = Database::lastInsertId();
                BookLog::addLog(array('id_file' => $id_file, 'filetype' => $filetype, 'id_file_author' => $current_user->id, 'filesize' => $filesize), array('id_file' => 0, 'filetype' => 0, 'id_file_author' => 0, 'filesize' => 0), $book->id);
                $current_user->gainActionPoints('books_add_file', $book->id, BiberLog::TargetType_book);
            }
            if ($id_file) {
                $points_gained = true;
                if (!$book->data['id_main_file'] || isset($files[$filetype])) {
                    $to_update['id_main_file'] = $id_file;
                }
                $destinationFile = getBookFilePath($id_file, $book->id, $filetype, Config::need('files_path'));
                if (!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFile)) {
                    throw new Exception('Cant save file to ' . $destinationFile);
                }
                // event for new File
                $event = new Event();
                $event->event_BooksAddFile($current_user->id, $book->id);
                $event->push();
                if ($filetype == 1) {
                    // FB2
                    $parser = new FB2Parser($destinationFile);
                    $parser->parseDescription();
                    $toc = $parser->getTOCHTML();
                    Request::$post['annotation'] = $parser->getProperty('annotation');
                    Request::$post['title'] = $parser->getProperty('book-title');
                    $to_update['table_of_contents'] = $toc;
                }
            }
        }
        foreach ($fields as $field => $bookfield) {
            if (!isset(Request::$post[$field])) {
                throw new Exception('field missed #[' . $field . ']');
            }
            if ($book->data[$bookfield] != Request::$post[$field]) {
                $to_update[$bookfield] = Request::$post[$field];
            }
        }
        $q = array();
        foreach ($to_update as $field => &$value) {
            $q[] = '`' . $field . '`=' . Database::escape($value) . '';
        }
        $push_event = true;
        if (count($q)) {
            if (count($to_update) == 1) {
                foreach ($to_update as $kk => $vv) {
                    if ($kk == 'id_main_file') {
                        $push_event = false;
                    }
                }
            }
            $query = 'UPDATE `book` SET ' . implode(',', $q) . ' WHERE `id`=' . $book->id;
            Database::query($query);
            if (count($to_update_m)) {
                $to_update['n'] = $to_update_m['n'];
            }
            BookLog::addLog($to_update, $book->data, $book->id);
            foreach ($to_update as $f => $v) {
                $book->data[$f] = $v;
            }
            $search = Search::getInstance();
            /* @var $search Search */
            $search->updateBook($book);
            if ($push_event) {
                $event = new Event();
                $event->event_BooksEdit($current_user->id, $book->id);
                $event->push();
            }
            if (!$points_gained) {
                $current_user->gainActionPoints('books_edit', $book->id, BiberLog::TargetType_book);
            }
        }
        BookLog::saveLog($book->id, BookLog::TargetType_book, $current_user->id, BiberLog::BiberLogType_bookEdit);
        Books::getInstance()->dropCache($book->id);
        if (count($to_update_m)) {
            if ($to_update_m['n'] && $book->data['book_type'] == Book::BOOK_TYPE_MAGAZINE) {
                Database::query('UPDATE `book_magazines` SET `n`=' . $to_update_m['n'] . ',`year`=' . (int) $book->data['year'] . ' WHERE `id_book`=' . $book->id);
            }
        }
        ob_end_clean();
        header('Location:' . Config::need('www_path') . '/b/' . $book->id);
        Database::query('COMMIT');
        exit;
    }
예제 #15
0
 function getLogBooks($ids, $opts = array(), $limit = false)
 {
     $person_id = isset($opts['person_id']) ? $opts['person_id'] : false;
     $books = Books::getInstance()->getByIdsLoaded($ids);
     Books::getInstance()->LoadBookPersons($ids);
     $out = array();
     /* @var $book Book */
     $i = 0;
     if (is_array($books)) {
         foreach ($books as $book) {
             if ($limit && ++$i > $limit) {
                 return $out;
             }
             $out[] = $book->getListData();
         }
     }
     return $out;
 }
예제 #16
0
 function getOneFull()
 {
     if (!$this->series_id) {
         return;
     }
     $series = Database::sql2array('SELECT id,title,position,books_count,id_parent,description FROM `series` WHERE `id`=' . $this->series_id . ' OR `id_parent`=' . $this->series_id, 'id');
     $parent_id = $series[$this->series_id]['id_parent'];
     if ($parent_id) {
         $parentInfo = Database::sql2array('SELECT id,title,position,books_count,id_parent FROM `series` WHERE `id`=' . $parent_id, 'id');
     } else {
         $parentInfo = array();
     }
     $series_books = Database::sql2array('SELECT * FROM `book_series` WHERE id_series IN (' . implode(',', array_keys($series)) . ') AND `is_deleted`=0');
     $bid = array();
     $cnt = array();
     $series_books_p = array();
     foreach ($series_books as $sb) {
         $cnt[$sb['id_series']] = isset($cnt[$sb['id_series']]) ? $cnt[$sb['id_series']] + 1 : 1;
         $series_books_p[$sb['id_series']][] = $sb;
         $bid[$sb['id_book']] = $sb['id_book'];
     }
     $aids = array();
     if (count($bid)) {
         Books::getInstance()->getByIdsLoaded($bid);
         Books::getInstance()->LoadBookPersons($bid);
     }
     foreach ($series_books_p as &$sb) {
         foreach ($sb as &$bookrow) {
             $book = Books::getInstance()->getById($bookrow['id_book']);
             list($aid, $aname) = $book->getAuthor(1, 1, 1);
             // именно наш автор, если их там много
             $bookrow = $book->getListData();
             $aids[$aid] = $aid;
         }
     }
     if (count($aids)) {
         $persons = Persons::getInstance()->getByIdsLoaded($aids);
         foreach ($persons as $person) {
             $this->data['authors'][] = $person->getListData();
         }
     }
     $this->data['serie']['series'] = array();
     $this->data['serie'] = $series[$this->series_id];
     $this->data['serie']['books'] = isset($series_books_p[$this->series_id]) ? $series_books_p[$this->series_id] : array();
     $this->data['serie']['books']['count'] = isset($cnt[$this->series_id]) ? $cnt[$this->series_id] : 0;
     foreach ($series as $id => $ser) {
         if ($ser['id'] == $this->series_id) {
             unset($this->data['serie']['books_count']);
             continue;
         } else {
             $ser['path'] = Config::need('www_path') . '/series/' . $ser['id'];
             $this->data['serie']['series'][$id] = $ser;
             $this->data['serie']['series'][$id]['books'] = isset($series_books_p[$id]) ? $series_books_p[$id] : array();
             $this->data['serie']['series'][$id]['books']['count'] = $ser['books_count'];
             unset($this->data['serie']['series'][$id]['books_count']);
         }
     }
     $this->data['serie']['parent'] = $parentInfo;
 }
예제 #17
0
 function add_relation()
 {
     global $current_user;
     $this->ca();
     $id1 = isset($_POST['id']) ? (int) $_POST['id'] : false;
     $id2 = isset($_POST['book_id']) ? (int) $_POST['book_id'] : false;
     $relation_type = isset($_POST['relation_type']) ? (int) $_POST['relation_type'] : false;
     $book1 = Books::getInstance()->getByIdLoaded($id1);
     $book2 = Books::getInstance()->getByIdLoaded($id2);
     /* @var $book2 Book */
     if (!$book2->loaded || !$book1->loaded) {
         $this->data['error'] = 'Нет такой книги';
         return false;
     }
     if (!$id1 || !$id2 || !$relation_type) {
         throw new Exception('id or item_id or relation_type missed');
     }
     if (BookRelations::addRelation($id1, $id2, $relation_type)) {
         $this->data['success'] = 1;
         $this->data['item_id'] = $id2;
         $this->data['relation_type'] = BookRelations::$relation_types[$relation_type];
         /* @var $book2 Book */
         $this->data['title'] = $book2->getTitle();
     } else {
         $this->data['success'] = 0;
         $this->data['error'] = 'ошибочка: ' . BookRelations::getLastError();
     }
     $search = Search::getInstance();
     /* @var $search Search */
     $search->updateBook(new Book($id1));
     $search->updateBook(new Book($id2));
 }
예제 #18
0
 private static function setEdition($id1, $id2)
 {
     global $current_user;
     $type = self::RELATION_TYPE_EDITION;
     try {
         $book1 = Books::getInstance()->getByIdLoaded($id1);
         $book2 = Books::getInstance()->getByIdLoaded($id2);
         /* @var $book1 Book */
         /* @var $book2 Book */
         if ($book2->getLangId() != Config::$langs['ru']) {
             //if ($book1->getLangId() != $book2->getLangId()) {
             $type = self::RELATION_TYPE_TRANSLATE;
         }
         Database::query('START TRANSACTION');
         if ($id1 == $id2) {
             self::setError('Онанизмъ!');
             return false;
         }
         if ($book1->getBasketId() && $book1->getBasketId() == $book2->getBasketId()) {
             self::setError('Книги уже связаны!');
             return false;
         }
         // смотрим книги.
         $basket_id = max($book1->getBasketId(), $book2->getBasketId());
         $basket_old = 0;
         if (!$basket_id) {
             $query = 'INSERT INTO `basket` SET `time`=' . time();
             Database::query($query);
             $basket_id = Database::lastInsertId();
         }
         $to_change = array();
         $to_old = array();
         if ($basket_id == $book1->getBasketId()) {
             if ($book2->getBasketId()) {
                 $basket_old = $book2->getBasketId();
                 // из 2 корзины всё в первую
                 $query = 'SELECT * FROM `book_basket` WHERE `id_basket`=' . $book2->getBasketId();
                 $relations = Database::sql2array($query);
                 foreach ($relations as $relation) {
                     $to_change[$relation['id_book']] = $relation['id_book'];
                 }
                 $query = 'SELECT * FROM `book_basket` WHERE `id_basket`=' . $book1->getBasketId();
                 $relations = Database::sql2array($query);
                 foreach ($relations as $relation) {
                     $to_old[$relation['id_book']] = $relation['id_book'];
                 }
                 $query = 'UPDATE `book_basket` SET `id_basket`=' . $basket_id . ' WHERE `id_basket`=' . $book2->getBasketId();
                 Database::query($query);
                 $query = 'UPDATE `book` SET `id_basket`=' . $basket_id . ' WHERE `id_basket`=' . $book2->getBasketId();
                 Database::query($query);
             } else {
                 $query = 'SELECT * FROM `book_basket` WHERE `id_basket`=' . $book1->getBasketId();
                 $relations = Database::sql2array($query);
                 foreach ($relations as $relation) {
                     $to_old[$relation['id_book']] = $relation['id_book'];
                 }
             }
         } else {
             if ($basket_id == $book2->getBasketId()) {
                 if ($book1->getBasketId()) {
                     $basket_old = $book1->getBasketId();
                     // из 1 корзины всё во вторую
                     $query = 'SELECT * FROM `book_basket` WHERE `id_basket`=' . $book1->getBasketId();
                     $relations = Database::sql2array($query);
                     foreach ($relations as $relation) {
                         $to_change[$relation['id_book']] = $relation['id_book'];
                     }
                     $query = 'SELECT * FROM `book_basket` WHERE `id_basket`=' . $book2->getBasketId();
                     $relations = Database::sql2array($query);
                     foreach ($relations as $relation) {
                         $to_old[$relation['id_book']] = $relation['id_book'];
                     }
                     $query = 'UPDATE `book_basket` SET `id_basket`=' . $basket_id . ' WHERE `id_basket`=' . $book1->getBasketId();
                     Database::query($query);
                     $query = 'UPDATE `book` SET `id_basket`=' . $basket_id . ' WHERE `id_basket`=' . $book1->getBasketId();
                     Database::query($query);
                 } else {
                     $query = 'SELECT * FROM `book_basket` WHERE `id_basket`=' . $book2->getBasketId();
                     $relations = Database::sql2array($query);
                     foreach ($relations as $relation) {
                         $to_old[$relation['id_book']] = $relation['id_book'];
                     }
                 }
             }
         }
         // 2 книги в корзинку
         if ($book1->getBasketId() != $basket_id) {
             $to_change[$book1->id] = $book1->id;
             //$to_old[$book2->id] = $book2->id;
         }
         if ($book2->getBasketId() != $basket_id) {
             $to_change[$book2->id] = $book2->id;
             //$to_old[$book1->id] = $book1->id;
         }
         $query = 'UPDATE `book` SET `id_basket`=' . $basket_id . ' WHERE `id` IN (' . $book1->id . ',' . $book2->id . ')';
         Database::query($query);
         // сохраняем в лог создание релейшна для книг, у которых поменялся id_basket
         if (count($to_change)) {
             $now = array('id_basket' => $basket_id, 'new_relations' => $to_change, 'old_relations' => $to_old);
             $was = array('id_basket' => $basket_old, 'new_relations' => array(), 'old_relations' => array());
             BookLog::addLog($now, $was, $book1->id);
             $ids = array_merge($to_change, $to_old);
             BookLog::saveLog($ids, BookLog::TargetType_book, $current_user->id, BiberLog::BiberLogType_bookAddRelation);
         }
         foreach ($ids as $id) {
             Books::getInstance()->dropCache($id);
         }
         $query = 'REPLACE INTO `book_basket`(`id_book`,`id_basket`) VALUES (' . $book1->id . ',' . $basket_id . '),(' . $book2->id . ',' . $basket_id . ')';
         Database::query($query);
         Database::query('COMMIT');
     } catch (Exception $e) {
         self::setError($e->getMessage());
         return false;
     }
     return true;
 }
예제 #19
0
파일: Book.php 프로젝트: rasstroen/metro
 function _show()
 {
     $out = array();
     if ($this->loadForFullView()) {
         if ($redirect_to = $this->getDuplicateId()) {
             $book2 = Books::getInstance()->getByIdLoaded($redirect_to);
             if ($book2->loaded) {
                 @ob_end_clean();
                 header('Location: ' . $this->getUrl($redirect = true) . '?redirect=b_' . $this->id);
                 exit;
             }
         }
         $out['id'] = $this->id;
         $langId = $this->data['id_lang'];
         foreach (Config::$langs as $code => $id_lang) {
             if ($id_lang == $langId) {
                 $langCode = $code;
             }
         }
         $out['quality'] = $this->getQuality();
         $out['lang_code'] = $langCode;
         $out['lang_title'] = Config::$langRus[$langCode];
         $out['lang_id'] = $langId;
         $out['download_count'] = $this->data['download_count'];
         $title = $this->getTitle();
         $out['title'] = $title['title'];
         $out['subtitle'] = $title['subtitle'];
         $out['loved_count'] = $this->getLovedCount();
         $out['public'] = $this->isPublic();
         $out['qualities'] = array(0 => array('id' => 0, 'title' => 'не оценен'), 1 => array('id' => 1, 'title' => 'ужасно'), 2 => array('id' => 2, 'title' => 'плохо'), 3 => array('id' => 3, 'title' => 'средне'), 4 => array('id' => 4, 'title' => 'хорошо'), 5 => array('id' => 5, 'title' => 'идеально'));
         $persons = $this->getPersons();
         uasort($persons, 'sort_by_role');
         foreach ($persons as $data) {
             $tmp_person = Persons::getInstance()->getById($data['id'], $data);
             if ($tmp_person->id) {
                 $out['authors'][$data['id']] = $tmp_person->getListData();
                 $out['authors'][$data['id']]['role'] = $data['role'];
                 $out['authors'][$data['id']]['roleName'] = $data['roleName'];
             }
         }
         $out['genres'] = $this->getGenres();
         $out['series'] = $this->getSeries();
         $out['isbn'] = $this->getISBN();
         $out['rightsholder'] = $this->getRightsholder();
         $out['annotation'] = $this->getChunkedAnnotation();
         $out['cover'] = $this->getCover();
         $out['files'] = $this->getFiles(true);
         $out['mark'] = $this->getMarkNumber();
         $out['mark_percents'] = $this->getMarkPercents();
         $out['mark_number'] = $this->getMarkRoundNumber();
         $out['path'] = $this->getUrl();
         $out['path_read'] = $this->getUrlRead();
         $out['lastSave'] = $this->data['modify_time'];
         $out['id_rightholder'] = $this->data['id_rightholder'];
         $out['path_admin'] = Config::need('www_path') . '/admin/books/' . $this->id;
         $out['year'] = (int) $this->data['year'] ? (int) $this->data['year'] : '';
         $out['book_type'] = Book::$book_types[$this->data['book_type']];
         if ($this->data['book_type'] == Book::BOOK_TYPE_MAGAZINE) {
             $out['magazine'] = Database::sql2row('SELECT * FROM `magazines` WHERE `id`=' . $this->getMagazineId());
             $out['magazine']['path'] = isset($out['magazine']['id']) ? Config::need('www_path') . '/m/' . $out['magazine']['id'] : '';
             $out['n'] = Database::sql2single('SELECT `n` FROM `book_magazines` WHERE `id_book`=' . $this->id);
         }
     } else {
         throw new Exception('no book #' . $id . ' in database');
     }
     return $out;
 }
예제 #20
0
 function setCollectionClass()
 {
     $this->Collection = Books::getInstance();
 }
예제 #21
0
 public static function buildPageTitlePart($var)
 {
     $x = explode(':', $var[1]);
     $name = false;
     if (count($x) == 3) {
         list($name, $paramtype, $paramvalue) = $x;
     }
     if (count($x) == 2) {
         list($name, $paramvalue) = $x;
         $paramtype = 'raw_get';
     }
     if ($name) {
         $val = self::parseParams($paramtype, $paramvalue);
         switch ($name) {
             case 'profile-nickname':
                 $user = Users::getByIdsLoaded(array((int) $val));
                 $user = isset($user[$val]) ? $user[$val] : false;
                 /* @var $user User */
                 if ($user) {
                     return $user->getNickName();
                 }
                 break;
             case 'book-title':
                 $book = Books::getInstance()->getByIdLoaded((int) $val);
                 /* @var $book Book */
                 return $book->getTitle(1);
                 break;
             case 'person-title':
                 $person = Persons::getInstance()->getById((int) $val);
                 /* @var $person Person */
                 return $person->getName();
                 break;
             case 'genre-title':
                 return Request::pass('genre-title');
                 break;
             case 'forum-title':
                 $t = Request::pass('forum-title');
                 if (!$t) {
                     $t = Database::sql2single('SELECT name FROM `term_data` WHERE `tid`=' . (int) $val);
                 }
                 return $t;
                 break;
             case 'post-subject':
                 return Request::pass('post-subject');
                 break;
             case 'theme-title':
                 return Request::pass('theme-title');
                 break;
             case 'serie-title':
                 $t = Request::pass('serie-title');
                 if (!$t) {
                     $t = Database::sql2single('SELECT `title` FROM `series` WHERE `id`=' . (int) $val);
                 }
                 return $t;
                 break;
             case 'shelf-name':
                 if ($val == 'loved') {
                     return 'Любимые книги';
                 }
                 if (isset(Config::$shelfIdByNames[$val])) {
                     return isset(Config::$shelves[Config::$shelfIdByNames[$val]]) ? Config::$shelves[Config::$shelfIdByNames[$val]] : $val;
                 }
                 break;
             case 'magazine-title':
                 $query = 'SELECT `title` FROM `magazines` WHERE `id`=' . (int) $val;
                 return Database::sql2single($query);
                 break;
             case 'thread-subject':
                 $query = 'SELECT `subject` FROM `users_messages` WHERE `id`=' . (int) $val;
                 return Database::sql2single($query);
                 break;
             case 'get':
                 return $val;
                 break;
             default:
                 throw new Exception('Cant process title part "' . $var[1] . '"');
                 break;
         }
     }
 }
예제 #22
0
    /**
     * сохраняем факт скачивания книги 
     * @param type $variables 
     */
    public function saveUserDownloads($user_id, $book_id, $time = false)
    {
        Database::query('START TRANSACTION');
        // for user
        $period = 24 * 60 * 60;
        // каждый день
        $time_normalized = $time ? $time : floor(time() / $period) * $period;
        // а не качал ли эту книгу юзер уже?
        $query = 'SELECT COUNT(1) FROM  `stat_user_download` WHERE 
			`id_user`=' . $user_id . ' AND
			`id_book`=' . $book_id . ' AND
			`time`>=' . $time_normalized . '';
        $cnt = Database::sql2single($query);
        if ($cnt) {
            // already have
            return;
        }
        $query = 'INSERT IGNORE INTO `stat_user_download` SET 
			`id_user`=' . $user_id . ', 
			`id_book`=' . $book_id . ',
			`time`=' . $time_normalized;
        Database::query($query);
        // for book stat
        $query = 'INSERT INTO `stat_book_download` SET 
			`id_book`=' . $book_id . ',
			`count` = 1,
			`time`=' . $time_normalized . ' ON DUPLICATE KEY UPDATE
			`count` = `count`+1';
        Database::query($query);
        // updating book download_count
        $query = 'UPDATE `book` SET `download_count`=`download_count`+1 WHERE `id`=' . $book_id;
        Database::query($query);
        // genres
        $book = Books::getInstance()->getByIdLoaded($book_id);
        /* @var $book Book */
        $genres = $book->getGenres();
        if (count($genres)) {
            foreach ($genres as $gid => $data) {
                $query = 'INSERT INTO `stat_genre_download` SET 
					`id_genre`=' . $gid . ',
					`count`=1,
					`time`=' . $time_normalized . ' ON DUPLICATE KEY UPDATE
					`count` = `count`+1';
                Database::query($query);
            }
        }
        // authors
        $authors = $book->getAuthors();
        if (count($authors)) {
            foreach ($authors as $id => $data) {
                $query = 'INSERT INTO `stat_author_download` SET 
					`id_author`=' . $data['id'] . ',
					`count`=1,
					`time`=' . $time_normalized . ' ON DUPLICATE KEY UPDATE
					`count` = `count`+1';
                Database::query($query);
            }
        }
        Database::query('COMMIT');
    }