Пример #1
0
 public function create()
 {
     $userid = Auth::user()->userid;
     // return Input::get("");exit();
     $book = new Books();
     $book->title = Input::get('title');
     $book->description = Input::get('description');
     $book->category = Input::get('genre');
     $book->sub_category = "none";
     $book->author = Input::get('author');
     $book->condition = Input::get('cond');
     $book->location = Input::get('loc');
     $book->cover = Input::get('image');
     $book->snippet = "none";
     $book->language = Input::get('lang');
     $book->popularity = "none";
     $book->quantity = Input::get('quantity');
     $book->expected_price = Input::get('rate');
     $book->purpose = Input::get('purpose');
     $book->added_by = $userid;
     //The USERID
     $book->save();
     //Add Book to Personal Info of the User
     $tn = $userid . "_books";
     DB::table($tn)->insert(array('title' => Input::get('title'), 'author' => Input::get("author"), 'condition' => Input::get('cond'), 'location' => Input::get('loc'), 'language' => Input::get('lang'), 'quantity' => Input::get('quantity'), 'expected_price' => Input::get('rate'), 'avlb' => 1));
 }
Пример #2
0
 public function actionAdd()
 {
     Yii::app()->getClientScript()->registerCoreScript('jquery');
     Yii::app()->getClientScript()->registerCoreScript('jquery.ui');
     $cs = Yii::app()->clientScript;
     $cs->registerCssFile('/js/datepicker/css/' . 'datepicker.css');
     $cs->registerScriptFile('/js/' . 'books.js');
     //
     $book = new Books();
     $command = Yii::app()->db->createCommand();
     if (isset($_POST['Books'])) {
         $book->attributes = $_POST['Books'];
         if ($book->validate()) {
             $book->save();
             if (isset($_POST['add_auth']) && !empty($_POST['add_auth'])) {
                 $criteria = new CDbCriteria();
                 $criteria->compare('lastname', $_POST['add_auth']);
                 $add_author = Authors::model()->find($criteria);
                 //If author exists
                 if (!empty($add_author)) {
                     //insert link book-author to link table
                     $command->insert('lt_books_authors', array('author_id' => $add_author->id, 'book_id' => $book->id));
                 }
             }
             $this->actionIndex();
             return true;
         }
     }
     $this->render('edit', array('model' => $book));
 }
Пример #3
0
 function showBook()
 {
     $model = new Books();
     $comment_section = new CommentsController();
     $data = $model->getBookData();
     include 'view/libro/libro.php';
     $comment_section->showComments();
 }
Пример #4
0
 public function actionSearch()
 {
     $model = Books::model();
     $params = array('result' => $model->searchPhrase($_POST['search_field']));
     $this->render('search', $params);
     //echo '<pre>'; print_r($_POST); echo'</pre>';
 }
Пример #5
0
	function getOne() {
		$query = 'SELECT * FROM `genre` WHERE `name`=' . Database::escape($this->genre_name);
		$data = Database::sql2row($query);
		if (!isset($data['name']))
			return;
		$this->data['genres'][$data['id']] = array(
		    'name' => $data['name'],
		    'id' => $data['id'],
		    'id_parent' => $data['id_parent'],
		    'title' => $data['title'],
		    'books_count' => $data['books_count']
		);

		if (!$data['id_parent']) {
			$this->data['genres'][$data['id']]['subgenres'] = $this->getAll($data['id']);
			return;
		}

		$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 20';
		$bids = Database::sql2array($query, 'id_book');
		$books = Books::getByIdsLoaded(array_keys($bids));
		Books::LoadBookPersons(array_keys($bids));

		foreach ($books as $book) {
			$book = Books::getById($book->id);
			list($aid, $aname) = $book->getAuthor(1, 1, 1); // именно наш автор, если их там много
			$this->data['genres'][$data['id']]['books'][] = array('id' => $book->id,
			    'cover' => $book->getCover(),
			    'title' => $book->getTitle(true),
			    'author' => $aname,
			    'author_id' => $aid,
			    'lastSave' => $book->data['modify_time']);
		}
	}
 public function run()
 {
     DB::table('books')->delete();
     Books::create(array('bname' => 'talha', 'bauthor' => 'talha1', 'bedition' => 'Eight', 'p_url' => 'ajed5hrgt4y', 'created_at' => new DateTime(), 'updated_at' => new DateTime()));
     DB::table('books')->insert(['bname' => 'talha', 'bauthor' => 'talha2', 'bedition' => 'ten', 'p_url' => 'ajed53y56hy', 'created_at' => new DateTime(), 'updated_at' => new DateTime()]);
     DB::table('books')->insert(['bname' => 'talha', 'bauthor' => 'talha3', 'bedition' => 'nine', 'p_url' => 'ajed5hy', 'created_at' => new DateTime(), 'updated_at' => new DateTime()]);
 }
 public function actionIndex()
 {
     $book_model = Books::model();
     $authors_model = Authors::model();
     $params = array('book_model' => $book_model, 'authors_model' => $authors_model);
     $this->render('report', $params);
 }
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function show($id)
 {
     $student = Student::find($id);
     if ($student == NULL) {
         throw new Exception('Invalid Student ID');
     }
     $student->year = (int) substr($student->year, 2, 4);
     $student_category = StudentCategories::find($student->category);
     $student->category = $student_category->category;
     $student_branch = Branch::find($student->branch);
     $student->branch = $student_branch->branch;
     if ($student->rejected == 1) {
         unset($student->approved);
         unset($student->books_issued);
         $student->rejected = (bool) $student->rejected;
         return $student;
     }
     if ($student->approved == 0) {
         unset($student->rejected);
         unset($student->books_issued);
         $student->approved = (bool) $student->approved;
         return $student;
     }
     unset($student->rejected);
     unset($student->approved);
     $student_issued_books = Logs::select('book_issue_id', 'issued_at')->where('student_id', '=', $id)->orderBy('time_stamp', 'desc')->take($student->books_issued)->get();
     foreach ($student_issued_books as $issued_book) {
         $issue = Issue::find($issued_book->book_issue_id);
         $book = Books::find($issue->book_id);
         $issued_book->name = $book->title;
         $issued_book->issued_at = date('d-M', $issued_book->issued_at);
     }
     $student->issued_books = $student_issued_books;
     return $student;
 }
Пример #9
0
 static function getRoutes()
 {
     $routes = [['get:books', function () {
         return (new Books())->index();
     }], ['get:books\\/(?<id>\\d+)', function ($params) {
         return (new Books())->show($params['id']);
     }], ['post:books', function () {
         return (new Books())->store(Books::filterData($_REQUEST));
     }], ['put:books\\/(?<id>\\d+)', function ($params) {
         return (new Books())->update($params['id'], Books::filterData($_REQUEST));
     }], ['delete:books\\/(?<id>\\d+)', function ($params) {
         return (new Books())->destroy($params['id']);
     }], ['get:libs', function () {
         return (new Libraries())->index();
     }], ['get:libs\\/(?<id>\\d+)', function ($params) {
         return (new Libraries())->show($params['id']);
     }], ['post:libs', function () {
         return (new Libraries())->store(Libraries::filterData($_REQUEST));
     }], ['put:libs\\/(?<id>\\d+)', function ($params) {
         return (new Libraries())->update($params['id'], Libraries::filterData($_REQUEST));
     }], ['delete:libs\\/(?<id>\\d+)', function ($params) {
         return (new Libraries())->destroy($params['id']);
     }]];
     return $routes;
 }
 public function commitEdit()
 {
     $id = Input::get('id');
     // validate the info, create rules for the inputs
     $rules = array('title' => 'required', 'author' => 'required');
     // run the validation rules on the inputs from the form
     $validator = Validator::make(Input::all(), $rules);
     // if the validator fails, redirect back to the form
     if ($validator->fails()) {
         return Redirect::to('edit/' . $id)->withErrors($validator)->withInput();
         // send back the input (not the password) so that we can repopulate the form
     } else {
         //return 'book added';
         // create our user data for the authentication
         $bookdata = array('title' => Input::get('title'), 'author' => Input::get('author'));
         //return $id;
         // update the data
         if ($Book = Books::where('id', '=', $id)->update($bookdata)) {
             // update successful!
             return Redirect::to('books')->with('message', 'Book info updated');
         } else {
             // validation not successful, send back to form
             return Redirect::to('edit/' . $id)->with('message', 'Book info editing failed');
         }
     }
 }
Пример #11
0
 public function actionSearch()
 {
     if (!isset($_GET['val'])) {
         $_GET['val'] = NULL;
     }
     echo Books::getList(NULL, $_GET['val']);
 }
Пример #12
0
 private function getBooksFromFiltr($arg)
 {
     //прием аргументов фильтрации, снова повторюсь сори что без валидации
     $authors = $arg['authors'];
     $genre = $arg['genre'];
     $from_year = $arg['from_year'];
     $to_year = $arg['to_year'];
     //все индификаторы книг что прошли фильтр по автору и по жанрам
     $book_author = BookAuthor::model()->with('books')->findAllByAttributes($authors);
     $book_gerne = BookGenre::model()->with('books')->findAllByAttributes($genre);
     foreach ($book_author as $class) {
         $flag[$class->bid] = true;
         //методом флажок - выясню есть ли в другом масиве теже bid
     }
     foreach ($book_gerne as $class) {
         if ($flag[$class->bid]) {
             $bids[] = $class->bid;
         }
         //если была создана ячека флажка, то значит что первый фильтр bid прошел
     }
     //выборка всех книг по фильтрованым индификаторам
     $books = Books::model()->findAllByAttributes(array('bid' => $bids), 'year>=' . $from_year . ' AND year<=' . $to_year);
     //хочу свормировать красивый масив без ячеек, которые сотворил yii
     $result = array();
     $i = 0;
     foreach ($books as $book) {
         $result[$i]['authors'] = $this->getAuthorsFromBid($book->bid);
         $result[$i]['genres'] = $this->getGenresFromBid($book->bid);
         $result[$i]['book']['bid'] = $book->bid;
         $result[$i]['book']['name'] = $book->name;
         $result[$i]['book']['year'] = $book->year;
         $i = $i + 1;
     }
     return $result;
 }
Пример #13
0
 public function actionSample()
 {
     $json = file_get_contents('E:\\xampp\\htdocs\\books\\protected\\data\\data.json');
     $arr = json_decode($json, true);
     foreach ($arr["Books"] as $item) {
         $model = new Books();
         $model->book_description = $item['Description'];
         $model->book_name = $item['Title'];
         $model->book_image = $item['Image'];
         $model->book_author = 'Anonymous';
         $model->book_publisher = 'It Ebook';
         $model->book_year = 2009;
         $model->created_at = time();
         $model->updated_at = time();
         $model->status = 1;
         $model->save(FALSE);
     }
 }
 public function actionAbout($id)
 {
     $book = Books::model()->findByPk($id);
     if (!empty($book)) {
         $comments = BooksComments::model()->findAll(array('condition' => 'book_id = :bookId', 'params' => array(':bookId' => $book->id), 'order' => 'id DESC', 'limit' => '10'));
         $this->render('about', array('book' => $book, 'comments' => $comments));
     } else {
         $this->redirect(array('index/index'));
     }
 }
Пример #15
0
 public function loadModel($id = null, $new = false)
 {
     if ($this->_book === null) {
         if ($new) {
             return $this->_book = new Books();
         }
         $this->_book = Books::model()->findByPk($_GET['id']);
         if ($this->_book === null) {
             throw new CHttpException(404, 'Sorry! There is no such book.');
         }
     }
     return $this->_book;
 }
Пример #16
0
 public function index($id = NULL)
 {
     if ($id == NULL) {
         $res = array('heading' => '404', 'message' => 'no such book');
         $this->load->view('errors/html/error_404', $res);
     } else {
         $this->load->model('Books');
         $book = Books::findByIds($id);
         // $comments = Comment::findOnCond();
         // TO DO
         $data = array('book' => $book);
         $this->load->view('book_details', $data);
     }
 }
Пример #17
0
 public function getBookInfo($bookId)
 {
     if (empty($bookId)) {
         return array('result' => 'fail', 'message' => 'Не задан идентифкатор книги');
     }
     $bookInfo = Books::getBookInfo($bookId);
     if (count($bookInfo) <= 0) {
         return array('result' => 'success', 'message' => 'Книг с указанным идентификатором не найдено');
     }
     $info = array($bookInfo->getAttributes());
     $authors = array();
     foreach ($bookInfo->authors as $item) {
         $authors[] = $item->getAttributes();
     }
     $info['authors'] = $authors;
     return $info;
 }
Пример #18
0
    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);
        }
    }
Пример #19
0
 /**
  * @property  Books $book
  */
 public static function setBookRate($id, $percent)
 {
     $percent = $percent > 100 ? 100 : $percent < 0 ? 0 : $percent;
     $rate = self::model()->findByAttributes(array('book_id' => $id, 'user_id' => Yii::app()->user->id));
     if (empty($rate)) {
         $rate = new BookRate();
         $rate->book_id = $id;
         $rate->user_id = Yii::app()->user->id;
     }
     $rate->rate = $percent;
     $rate->save();
     $book = Books::model()->findByPk($id);
     if (!empty($book)) {
         $book->updateRate();
     }
     return $book->rate;
 }
Пример #20
0
 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);
     }
 }
Пример #21
0
 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;
 }
Пример #22
0
 public function index()
 {
     $this->load->model('Books');
     $books = Books::findOnCond(array(), 0);
     $results = array('one' => array(), 'two' => array(), 'three' => array());
     foreach ($books as $key => $value) {
         switch ($key % 3) {
             case 0:
                 $results['one'][] = $value;
                 break;
             case 1:
                 $results['two'][] = $value;
                 break;
             case 2:
                 $results['three'][] = $value;
                 break;
         }
     }
     $this->loadAll('index', $results);
 }
 public function index()
 {
     $logs = Logs::select('id', 'book_issue_id', 'student_id', 'issued_at')->where('return_time', '=', 0)->orderBy('issued_at', 'DESC');
     $logs = $logs->get();
     for ($i = 0; $i < count($logs); $i++) {
         $issue_id = $logs[$i]['book_issue_id'];
         $student_id = $logs[$i]['student_id'];
         // to get the name of the book from book issue id
         $issue = Issue::find($issue_id);
         $book_id = $issue->book_id;
         $book = Books::find($book_id);
         $logs[$i]['book_name'] = $book->title;
         // to get the name of the student from student id
         $student = Student::find($student_id);
         $logs[$i]['student_name'] = $student->first_name . ' ' . $student->last_name;
         // change issue date and return date in human readable format
         $logs[$i]['issued_at'] = date('d-M', $logs[$i]['issued_at']);
         $logs[$i]['return_at'] = date('d-M', $logs[$i]['issued_at'] + 1209600);
     }
     return $logs;
 }
Пример #24
0
 private function checkPdfColumns($book, CheckLinks &$check_links)
 {
     $pdfs_only_book = Books::pdfsOnlyList($book);
     $book_count = 1;
     for ($i = 0; $i < count($pdfs_only_book); $i = $i + Books::$COLUMNS_OF_PDF_IN_BOOK) {
         $index_pdf_location = $i;
         $index_pdf_pages = $i + 1;
         $index_pdf_info = $i + 2;
         $pdf_location = $pdfs_only_book[$index_pdf_location];
         if (NULL === $pdf_location) {
             break;
         }
         $this->checkPdfLink($pdf_location, "?-PDF Link {$book_count}");
         $check_links->addUrl($pdf_location);
         $pdf_pages = $pdfs_only_book[$index_pdf_pages];
         $this->checkNumber($pdf_pages, "?-PDF Page Count {$book_count}");
         if (isset($pdfs_only_book[$index_pdf_info])) {
             $pdf_info = $pdfs_only_book[$index_pdf_info];
             $this->checkCharacters($pdf_info, "?-PDF INFO {$book_count}");
         }
         ++$book_count;
     }
 }
Пример #25
0
 public function add()
 {
     $post_data = $this->input->post();
     $w_id = $post_data['w_id'];
     $this->load->model('Wishlists');
     $url_array = $this->parse_url($post_data['urls']);
     $results = array();
     foreach ($url_array as $key => $value) {
         // $start = strpos($value, 'subject') + 8;
         // $end = $start;
         // for (; is_numeric($value[$end]); $end++) {}
         // $id = substr($value, $start, $end - $start);
         $temp = [];
         preg_match('/([0-9]+)/i', $value, $temp);
         $id = $temp[0];
         $results[] = $this->get_info($id);
         $wishlist = Wishlists::findByIds($w_id);
         $wishlist->is_stocked_in = 1;
         $wishlist->save(TRUE);
     }
     $this->load->model('Books');
     Books::insert_batch($results);
 }
Пример #26
0
	function write() {
		global $current_user;
		//$this->setWriteParameter('register_module', 'result', false);

		$id = isset(Request::$post['id']) ? (int) Request::$post['id'] : false;


		if (!$id) {
			$this->newBook();
			return;
		}


		$books = Books::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', //lang_code
		    'annotation' => 'description'
		);

		Request::$post['lang_code'] = Config::$langs[Request::$post['lang_code']];
		$to_update = array();
		if (isset($_FILES['cover']) && $_FILES['cover']['tmp_name']) {
			$folder = Config::need('static_path') . '/upload/covers/' . (ceil($book->id / 5000));
			@mkdir($folder);
			chmod($folder, 755);
			$filename = $folder . '/' . $book->id . '.jpg';
			$upload = new UploadAvatar($_FILES['cover']['tmp_name'], 100, 100, "simple", $filename);
			if ($upload->out)
				$to_update['is_cover'] = 1;
			else {
				throw new Exception('cant copy file to ' . $filename, 100);
			}
		}

		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] : 'fb2';
			$filetype = $filetype == 'fb2' ? 1 : 0;
			if (!$filetype)
				throw new Exception('only fb2 allowed');
			$destinationDir = Config::need('files_path') . DIRECTORY_SEPARATOR . getBookFileDirectory($book->id, $filetype);
			@mkdir($destinationDir, 755);
			// добавляем запись в базу
			$filesize = $_FILES['file']['size'];
			$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);
			if ($id_file = 78037 || $id_file = Database::lastInsertId()) {
				$destinationFile = getBookFilePath($id_file, $book->id, $filetype, Config::need('files_path'));
				move_uploaded_file($_FILES['file']['tmp_name'], $destinationFile);
			}
			if ($filetype == 1) {
				$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) {
			if (in_array($field, array('ISBN', 'year'))) {
				$value = is_numeric($value) ? $value : 0;
			}
			$q[] = '`' . $field . '`=' . Database::escape($value) . '';
		}

		if (count($q)) {
			$query = 'UPDATE `book` SET ' . implode(',', $q) . ' WHERE `id`=' . $book->id;
			Database::query($query);
			BookLog::addLog($to_update, $book->data);
			BookLog::saveLog($book->id, BookLog::TargetType_book, $current_user->id, BiberLog::BiberLogType_bookEdit);
		}
		ob_end_clean();
		header('Location:' . Config::need('www_path') . '/b/' . $book->id);
		exit();
	}
Пример #27
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;
         }
     }
 }
Пример #28
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);
 }
Пример #29
0
 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;
 }
Пример #30
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;
 }