File: /home/assibfaf/public_html/prox-modules/prepapers/prepapers.php
<?php
use Proxim\Application;
use Proxim\Configuration;
use Proxim\Database\DbQuery;
use Proxim\Hook;
use Proxim\Module\Module;
use Proxim\Pager;
use Proxim\Preference\Discipline;
use Proxim\Preference\PaperFormat;
use Proxim\Preference\PaperType;
use Proxim\Presenter\Object\ObjectPresenter;
use Proxim\Site\Site;
use Proxim\Tools;
use Proxim\Util\ArrayUtils;
use Proxim\Util\Formatting;
use Proxim\Util\StringUtils;
use Proxim\Validate;
define('CURRENT_PWP_MODULE_DIR', realpath(dirname(__FILE__)));
require_once(CURRENT_PWP_MODULE_DIR . '/classes/PrePaper/PrePaper.php');
require_once(CURRENT_PWP_MODULE_DIR . '/classes/PrePaper/PrePaperFile.php');
require_once(CURRENT_PWP_MODULE_DIR . '/classes/PrePaper/PrePaperPreview.php');
require_once(CURRENT_PWP_MODULE_DIR . '/classes/PrePaper/PrePaperPayment.php');
require_once(CURRENT_PWP_MODULE_DIR . '/classes/Presenter/PrePaperLazyArray.php');
require_once(CURRENT_PWP_MODULE_DIR . '/classes/Presenter/PrePaperPresenter.php');
class PrePapers extends Module
{
const SELL_PREWRITTEN_PAPERS = 'SELL_PREWRITTEN_PAPERS';
const CHANGEFREQ = 'weekly';
const PRIORITY = 1;
public function __construct()
{
$this->name = 'prepapers';
$this->icon = 'fa fa-book';
$this->version = '1.0.0';
$this->prox_versions_compliancy = array('min' => '1.0.0', 'max' => Application::VERSION);
$this->author = 'Davison Pro';
$this->bootstrap = true;
parent::__construct();
$this->displayName = 'Pre Written Papers';
$this->description = 'Sell your Pre Written Papers all from one place';
}
public function assignVairiables() {
global $globals;
$smarty = $this->smarty;
$academicLevels = array();
$objectPresenter = new ObjectPresenter();
$disciplineGroups = Discipline::getDisciplinesByGroup();
$paperFormats = PaperFormat::getPaperFormats();
$paperTypesPreferences = PaperType::getPaperTypes();
$paperTypes = array();
foreach($paperTypesPreferences as $paperType) {
$paperType = new PaperType( $paperType['paper_type_id'] );
if(Validate::isLoadedObject($paperType)) {
$paperTypes[] = $objectPresenter->present($paperType);
}
}
foreach ( $globals['academicLevels'] as $academicLevelId => $academicLevel ) {
$academicLevel['id'] = $academicLevelId;
$academicLevels[] = $academicLevel;
}
$smarty->assign([
'academicLevels' => $academicLevels,
'paperTypes' => $paperTypes,
'paperFormats' => $paperFormats,
'disciplineGroups' => $disciplineGroups,
]);
}
public function listPapers() {
$app = $this->application;
$smarty = $this->smarty;
$user = $app->container->user;
$params = $app->request->get();
$is_search = ArrayUtils::has($params, 'search') ? true : false;
$selected_page = ArrayUtils::has($params, 'page') ? (int) ArrayUtils::get($params, 'page') : 1;
$prepaper_id = ArrayUtils::has($params, 'prepaper_id');
$corslevel = ArrayUtils::has($params, 'corslevel');
$discipline_ids = ArrayUtils::has($params, 'discipline_ids');
$title = ArrayUtils::has($params, 'title');
$sql = new DbQuery();
$sql->select('p.prepaper_id');
$sql->from('prepaper', 'p');
if ($is_search) {
if ($prepaper_id) {
$sql->where('p.prepaper_id LIKE \'%' . pSQL($prepaper_id) . '%\'');
}
if($corslevel > 0 ) {
$sql->where( 'p.academic_level_id = ' . (int) $corslevel );
}
if(is_array($discipline_ids) && !empty($discipline_ids)) {
$disciplineQ = implode(',', $discipline_ids);
$sql->where( "p.topic_category_id IN ($disciplineQ)" );
}
if ($title) {
$sql->where('p.title LIKE \'%' . pSQL($title) . '%\'');
}
}
$sql->orderBy('p.prepaper_id DESC');
$result = Db::getInstance(PROX_USE_SQL_SLAVE)->executeS($sql);
$total_prepapers = count($result);
$prepapers = array();
if( $total_prepapers > 0) {
$params['total_items'] = $total_prepapers;
$params['selected_page'] = $selected_page;
$params['items_per_page'] = Configuration::get('MAX_RESULTS', null, 10)*2;
$params['url'] = $app->base_uri ."/prepapers?page=%s";
$pager = new Pager( $params );
$limit_query = $pager->getLimitSql();
$result = Db::getInstance(PROX_USE_SQL_SLAVE)->executeS($sql . $limit_query);
$prepaperPresenter = new PrePaperPresenter();
foreach( $result as $prepaper ) {
$prepaper = new PrePaper( (int) $prepaper['prepaper_id'] );
if( Validate::isLoadedObject($prepaper) ) {
$prepapers[] = $prepaperPresenter->present( $prepaper );
}
}
$smarty->assign([
'pager' => $pager->getPager()
]);
}
$smarty->assign([
'view' => 'prepapers',
'sub_view' => 'listPapers',
'prepapers' => $prepapers,
'is_search' => $is_search
]);
return $this->showTemplate('prepapers');
}
public function addNew() {
$app = $this->application;
$smarty = $this->smarty;
$this->assignVairiables();
$smarty->assign([
'view' => 'prepapers',
'sub_view' => 'addPaper'
]);
return $this->showTemplate('prepapers');
}
public function viewPaper() {
$app = $this->application;
$user = $app->container->user;
$smarty = $this->smarty;
$paperId = $app->request->get('paperId');
$prepaper = new PrePaper( (int) $paperId );
if(!Validate::isLoadedObject($prepaper)) {
$app->setTemplate('404');
$app->display();
}
$this->assignVairiables();
$prepaperPresenter = new PrePaperPresenter();
$smarty->assign([
'view' => 'prepapers',
'sub_view' => 'viewPaper',
'prepaper' => $prepaperPresenter->present($prepaper)
]);
return $this->showTemplate('prepapers');
}
public function apiAddNewPaper() {
$app = $this->application;
$payload = $app->request->post();
$user = $app->container->user;
$new_prepaper = true;
if(ArrayUtils::has($payload, 'prepaper_id')) {
$prepaper_id = ArrayUtils::get($payload, 'prepaper_id');
$prepaper = new PrePaper( (int) $prepaper_id );
if(!Validate::isLoadedObject($prepaper)) {
return $app->sendResponse([
'error' => true,
'message' => "This prepaper does not exist"
]);
}
$new_prepaper = false;
} else {
$prepaper = new PrePaper();
}
$title = ArrayUtils::get($payload, 'title');
if (!$title) {
return $app->sendResponse([
"error" => true,
"message" => "Enter the title for your prepaper"
]);
}
$question = ArrayUtils::get($payload, 'question');
if(!$question) {
return $app->sendResponse([
"error" => true,
"message" => "Enter the question of this prepaper"
]);
}
$price = ArrayUtils::get($payload, 'price');
if (!$price) {
return $app->sendResponse([
"error" => true,
"message" => "Enter the price for your prepaper"
]);
}
/** Pages / Charts / Slides */
$words = (int) ArrayUtils::get($payload, 'words');
$pages = (int) ArrayUtils::get($payload, 'pages');
$charts = (int) ArrayUtils::get($payload, 'charts');
$slides = (int) ArrayUtils::get($payload, 'slides');
$sources = (int) ArrayUtils::get($payload, 'sources');
// @todo both pages, charts, and slides can't be zero
if ( $pages == 0 && $slides == 0 && $charts == 0) {
return $app->sendResponse([
"error" => true,
"message" => "You need to add at least 1 page or 1 slide or 1 chart"
]);
}
/** Spacing */
$spacing = ArrayUtils::get($payload, 'spacing');
if ( !$spacing || !in_array($spacing, array(PrePaper::SPACING_SINGLE, PrePaper::SPACING_DOUBLE)) ) {
return $app->sendResponse([
"error" => true,
"message" => "Select the spacing for this prepaper"
]);
}
/** Topic category */
$topic_cat_id = (int) ArrayUtils::get($payload, 'topicCatId');
$discipline = new Discipline( $topic_cat_id );
if(Validate::isLoadedObject($discipline)) {
$topic_cat_option = ArrayUtils::get($payload, 'topcatOption', $discipline->title);
$isComplexAssignment = $discipline->is_complex_assignment;
}
/** Paper Type */
$paper_type_id = (int) ArrayUtils::get($payload, 'paperTypeId');
$paperType = new PaperType( $paper_type_id );
if(Validate::isLoadedObject($paperType)) {
$paper_type_option = ArrayUtils::get($payload, 'paperTypeOption', $paperType->title);
}
/** Paper Format */
$paper_format_id = (int) ArrayUtils::get($payload, 'paperFormat');
$paperFormat = new PaperFormat( $paper_format_id );
if(Validate::isLoadedObject($paperFormat)) {
$paper_format_option = $paperFormat->title;
$paper_format_option = ArrayUtils::get($payload, 'paperFormatOption', $paperFormat->title);
}
$academic_level_id = ArrayUtils::get($payload, 'academicLevelId');
$slug = ArrayUtils::get($payload, 'slug');
if($slug) {
$prepaper->slug = Formatting::sanitize_title_with_dashes( $slug , null, 'save');
} else {
$prepaper->slug = Formatting::sanitize_title_with_dashes($title , null, 'save');
}
$slugExists = (new PrePaper())->getBySlug( $prepaper->slug, true );
if(Validate::isLoadedObject($slugExists)) {
$prepaper->slug = $prepaper->slug . '-' . Tools::randomGen(5, 'NUMERIC');
}
$prepaper->title = $title;
$prepaper->question = $question;
$prepaper->academic_level_id = $academic_level_id;
$prepaper->paper_type_id = $paper_type_id;
$prepaper->paper_type_option = $paper_type_option;
$prepaper->topic_category_id = $topic_cat_id;
$prepaper->topic_category_option = $topic_cat_option;
$prepaper->is_complex_assignment = $isComplexAssignment;
$prepaper->paper_format_id = $paper_format_id;
$prepaper->paper_format_option = $paper_format_option;
$prepaper->sources = $sources;
$prepaper->words = $words;
$prepaper->pages = $pages;
$prepaper->charts = $charts;
$prepaper->slides = $slides;
$prepaper->spacing = $spacing;
$prepaper->price = (float) $price;
if($new_prepaper) {
$prepaper->add();
return $app->sendResponse([
'callback' => 'window.location.href="/prepapers/viewPaper?paperId='.$prepaper->id.'";'
]);
} else {
$prepaper->update();
return $app->sendResponse([
'success' => true,
'message' => 'PrePaper info has been updated'
]);
}
}
public function hookActionAfterFileUpload($payload) {
$handle = ArrayUtils::get($payload, 'handle');
$id = ArrayUtils::get($payload, 'id');
$file = ArrayUtils::get($payload, 'file');
switch($handle) {
case 'prepaper':
$prepaper = new PrePaper( (int) $id);
if(Validate::isLoadedObject($prepaper)) {
$prepaperFile = new PrePaperFile();
$prepaperFile->prepaper_id = $prepaper->id;
$prepaperFile->name = $file['name'];
$prepaperFile->size = $file['size'];
$prepaperFile->source = $file['source'];
$prepaperFile->extension = $file['extension'];
$prepaperFile->add();
}
break;
case 'prepaper-preview':
$prepaper = new PrePaper( (int) $id );
if(Validate::isLoadedObject($prepaper)) {
$prepaperPreview = new PrePaperPreview();
$prepaperPreview->prepaper_id = $prepaper->id;
$prepaperPreview->name = $file['name'];
$prepaperPreview->size = $file['size'];
$prepaperPreview->source = $file['source_name'];
$prepaperPreview->extension = $file['extension'];
$prepaperPreview->add();
}
break;
}
}
public function hookActionBeforeAdminDelete( $params ) {
$app = $this->application;
$id = ArrayUtils::get($params, 'id');
$handle = ArrayUtils::get($params, 'handle');
switch($handle) {
case "prepaper":
$prepaper = new PrePaper( (int) $id );
if(Validate::isLoadedObject($prepaper)) {
$prepaper->delete();
}
break;
case "prepaper-file":
$prepaperFile = new PrePaperFile( (int) $id );
if(Validate::isLoadedObject($prepaperFile)) {
$prepaperFile->delete();
}
break;
case 'prepaper-preview':
$prepaperPreview = new PrePaperPreview( (int) $id );
if(Validate::isLoadedObject($prepaperPreview)) {
$prepaperPreview->delete();
}
break;
}
}
public function hookActionAfterSiteSettingsGeneralUpdate( $params ) {
$site_id = ArrayUtils::get($params, 'site_id');
$payload = ArrayUtils::get($params, 'payload');
$site = new Site( (int) $site_id );
if(Validate::isLoadedObject($site)) {
Configuration::updateValue(self::SELL_PREWRITTEN_PAPERS, ArrayUtils::has($payload, 'sellPrewrittenPapers') ? true : false, false, $site->id);
}
}
public function downloadPaper() {
$app = $this->application;
$user = $app->container->user;
$smarty = $this->smarty;
$fileId = $app->request->get('fileId');
$prepaperFile = new PrePaperFile( (int) $fileId );
if(!Validate::isLoadedObject($prepaperFile)) {
$app->setTemplate('404');
$app->display();
}
$file_path = PROX_DIR_UPLOADS . $prepaperFile->source;
$downloadFileName = $prepaperFile->name;
if($prepaperFile->extension && StringUtils::endsWith($downloadFileName, $prepaperFile->extension)) {
$downloadFileName .= "." . $prepaperFile->extension;
}
$downloadFile = @fopen($file_path,"rb");
if (!$downloadFile) {
$app->setTemplate('404');
$app->display();
}
$downloadFileName = $prepaperFile->name;
if($prepaperFile->extension && !StringUtils::endsWith($downloadFileName, $prepaperFile->extension)) {
$downloadFileName .= "." . $prepaperFile->extension;
}
$downloadFileSize = filesize($file_path);
$mime_types = array(
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"docx" => "application/msword",
"jpg" => "image/jpg",
"php" => "text/plain",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"pdf" => "application/pdf",
"txt" => "text/plain",
"html"=> "text/html",
"png" => "image/png",
"jpeg"=> "image/jpg",
"js" => "application/x-javascript"
);
if( array_key_exists($prepaperFile->extension, $mime_types) ) {
$mime_type = $mime_types[$prepaperFile->extension];
} else {
$mime_type = "application/force-download";
}
@ob_end_clean();
if( ini_get('zlib.output_compression') ) {
ini_set('zlib.output_compression', 'Off');
}
header('Pragma: public');
header("Expires: 0");
header('Connection: Keep-Alive');
header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0");
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$downloadFileName.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
if( isset($_SERVER['HTTP_RANGE']) ) {
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$downloadFileSize-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$downloadFileSize");
} else {
$new_length = $downloadFileSize;
header("Content-Length: " . $downloadFileSize);
}
$chunksize = 1*(1024*1024);
$bytes_sent = 0;
if(isset($_SERVER['HTTP_RANGE'])) {
fseek($downloadFile, $range);
}
while(
!feof($downloadFile) &&
(!connection_aborted()) &&
($bytes_sent < $new_length)
) {
$buffer = fread($downloadFile, $chunksize);
echo($buffer);
flush();
$bytes_sent += strlen($buffer);
}
@fclose($downloadFile);
return;
}
}