- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
woo-pdf-invoice-builder/trunk/woocommerce-pdf-invoice-ajax.php
r2935371 r2949518 1 1 <?php 2 2 /** 3 3 * Created by PhpStorm. 4 4 * User: Edgar 5 5 * Date: 10/10/2017 6 6 * Time: 7:50 AM 7 7 */ 8 8 9 9 10 10 use rnwcinv\compatibility\DocumentOptionsCompatibility; 11 11 use rnwcinv\htmlgenerator\FieldDTO; 12 12 use rnwcinv\htmlgenerator\fields\FieldFactory; 13 13 use rnwcinv\htmlgenerator\OrderValueRetriever; 14 14 use rnwcinv\pr\CustomField\CustomFieldBase; 15 15 use rnwcinv\pr\CustomField\CustomFieldFactory; 16 16 use rnwcinv\pr\CustomField\SimpleCustomField; 17 17 use rnwcinv\pr\CustomField\utilities\CustomFieldValueRetriever; 18 18 use rnwcinv\pr\CustomFieldV2\BasicFields\CArrayField; 19 19 use rnwcinv\pr\CustomFieldV2\BasicFields\CImageField; 20 20 use rnwcinv\pr\CustomFieldV2\BasicFields\CSimpleField; 21 21 use rnwcinv\pr\utilities\FontManager; 22 22 use rnwcinv\utilities\InvoiceInitialDataGenerator; 23 23 24 24 require_once RednaoWooCommercePDFInvoice::$DIR.'utilities/HttpPostProcessor.php'; 25 25 final class RednaoWooCommercePDFInvoiceAjax{ 26 26 public $data=null; 27 27 public $detailCatched=false; 28 28 public function __construct() 29 29 { 30 30 add_action('wp_ajax_rednao_wcpdfinv_get_field_preview',array($this,'GetFieldPreview')); 31 31 add_action('wp_ajax_rednao_wcpdfinv_get_qr_preview',array($this,'GetQrPreview')); 32 32 add_action('wp_ajax_rednao_wcpdfinv_save_custom_field',array($this,'SaveCustomField')); 33 33 add_action('wp_ajax_rednao_wcpdfinv_get_designer_preview',array($this,'GetDesignerPreview')); 34 34 add_action('wp_ajax_rednao_wcpdfinv_save',array($this,'Save')); 35 35 add_action('wp_ajax_rednao_search_invoice',array($this,'SearchInvoice')); 36 36 add_action('wp_ajax_rednao_check_if_order_is_valid',array($this,'CheckIfOrderIsValid')); 37 37 add_action('wp_ajax_rednao_wcpdfinv_generate_pdf',array($this,'CreatePDF')); 38 38 add_action('wp_ajax_rednao_update_template',array($this,'UpdateTemplate')); 39 39 add_action('wp_ajax_rednao_wcpdfinv_get_designer_export',array($this,'Export')); 40 40 add_action('wp_ajax_rednao_wcpdfinv_remind_me',array($this,'RemindMeLater')); 41 41 add_action('wp_ajax_rednao_wcpdfinv_dont_show_again',array($this,'DontShowAgain')); 42 42 add_action('wp_ajax_rednao_wcpdfinv_diagnose_error',array($this,'DiagnoseError')); 43 43 add_action('wp_ajax_rednao_wcpdfinv_get_latest_error',array($this,'GetLatestError')); 44 44 add_action('wp_ajax_rednao_wcpdfinv_dont_show_again_nl',array($this,'DontShowNewsletter')); 45 45 add_action('wp_ajax_rednao_wcpdfinv_inspect_order',array($this,'InspectOrder')); 46 46 add_action('wp_ajax_rednao_wcpdfinv_preview_custom_field',array($this,'PreviewCustomField')); 47 47 add_action('wp_ajax_rednao_wcpdfinv_get_invoice_details',array($this,'GetInvoiceDetail')); 48 48 add_action('wp_ajax_rednao_wcpdfinv_load_template',array($this,'LoadTemplate')); 49 49 add_action('wp_ajax_rednao_wcpdfinv_email_pdf',array($this,'EmailPDF')); 50 50 add_action('wp_ajax_rednao_wcpdfinv_delete_pdf',array($this,'DeletePDF')); 51 51 add_action('wp_ajax_rednao_wcpdfinv_manage_delete',array($this,'ManageDelete')); 52 52 add_action('wp_ajax_rednao_wcpdfinv_search',array($this,'Search')); 53 53 add_action('wp_ajax_rednao_wcpdfinv_manage_view',array($this,'ManageView')); 54 54 add_action('wp_ajax_rednao_wcpdfinv_download',array($this,'Download')); 55 55 add_action('wp_ajax_rednao_wcpdfinv_save_next_number',array($this,'SaveNextNumber')); 56 56 57 57 58 58 } 59 59 60 60 61 61 62 62 public function SaveNextNumber(){ 63 63 RednaoWooCommercePDFInvoice::CheckIfPDFAdmin(); 64 64 $processor=new HttpPostProcessor(); 65 65 66 66 $invoiceId=$processor->GetRequired('invoiceid'); 67 67 $nextNumber=$processor->GetRequired('number'); 68 68 69 69 update_option($invoiceId. '_rednao_pdf_invoice_number',apply_filters('wcpdfi_update_latest_invoice_number',$nextNumber,$invoiceId)); 70 70 71 71 $processor->SendSuccessMessage(); 72 72 } 73 73 74 74 public function ManageDelete(){ 75 75 RednaoWooCommercePDFInvoice::CheckIfPDFAdmin(); 76 76 $processor=new HttpPostProcessor(); 77 77 $nonce=$processor->GetRequired('Nonce'); 78 78 if(!wp_verify_nonce($nonce,'pdfi_manage_nonce')) 79 79 die('Forbidden'); 80 80 81 81 $invoiceList=$processor->GetRequired('Invoices'); 82 82 global $wpdb; 83 83 $ids=''; 84 84 $allDeleted=true; 85 85 foreach($invoiceList as $invoice) 86 86 { 87 87 $result=$wpdb->query($wpdb->prepare('delete from '.RednaoWooCommercePDFInvoice::$INVOICES_CREATED_TABLE. ' where invoice_id =%s and order_id=%s',$invoice->InvoiceId,$invoice->OrderId)); 88 88 if($result==false) 89 89 { 90 90 $allDeleted=true; 91 91 } 92 92 93 93 94 94 95 95 } 96 96 97 97 if(!$allDeleted) 98 98 { 99 99 $this->SendErrorMessage('Some items could not be deleted, please try again'); 100 100 } 101 101 102 102 $this->SendSuccessMessage('Items deleted successfully'); 103 103 } 104 104 105 105 public function Download(){ 106 106 RednaoWooCommercePDFInvoice::CheckIfPDFAdmin(); 107 107 $processor=new HttpPostProcessor(); 108 108 $nonce=$processor->GetRequired('Nonce'); 109 109 if(!wp_verify_nonce($nonce,'pdfi_manage_nonce')) 110 110 die('Forbidden'); 111 111 112 112 $invoiceList=$processor->GetRequired('Invoices'); 113 113 114 114 if(count($invoiceList)==1) 115 115 { 116 116 $orderId=$invoiceList[0]->OrderId; 117 117 $invoiceId=$invoiceList[0]->InvoiceId; 118 118 $order=wc_get_order($orderId); 119 119 if($order==false) 120 120 { 121 121 echo "Invalid Order Number"; 122 122 die(); 123 123 } 124 124 125 125 require_once 'PDFGenerator.php'; 126 126 127 127 $generator=\rnwcinv\GeneratorFactory::GetGenerator(RednaoPDFGenerator::GetPageOptionsById($invoiceId),$order); 128 128 $generator->Generate(true,true); 129 129 130 130 header("Content-type: application/pdf"); 131 131 header("Content-disposition: attachment; filename=".basename($generator->GetFileName()).'.pdf'); 132 132 header('Expires: 0'); 133 133 header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 134 134 echo $generator->GetOutput(); 135 135 136 136 die(); 137 137 }else{ 138 138 139 139 $uploadDir=wp_upload_dir(); 140 140 $path= $uploadDir['basedir'].'/sf_pdfs_bulk'; 141 141 142 142 if(!is_dir($path)) 143 143 RednaoWooCommercePDFInvoice::CreateFolder($path); 144 144 145 145 146 146 $zip=new \ZipArchive(); 147 147 $usedNames=[]; 148 148 $zip->open( $path.'documents.zip',\ZipArchive::CREATE|\ZipArchive::OVERWRITE); 149 149 foreach($invoiceList as $invoice) 150 150 { 151 151 $order=wc_get_order($invoice->OrderId); 152 152 if($order==false) 153 153 { 154 154 echo "Invalid Order Number"; 155 155 die(); 156 156 } 157 157 158 158 require_once 'PDFGenerator.php'; 159 159 160 160 $generator=\rnwcinv\GeneratorFactory::GetGenerator(RednaoPDFGenerator::GetPageOptionsById($invoice->InvoiceId),$order); 161 161 $generator->Generate(true,true); 162 162 163 163 164 164 $name=$generator->GetFileName(); 165 165 $nameToCheck=strtolower($name); 166 166 $index=1; 167 167 while(array_search($nameToCheck,$usedNames)!==false) 168 168 { 169 169 $nameToCheck=strtolower($name).'('.$index.')'; 170 170 $index++; 171 171 } 172 172 $usedNames[]=$nameToCheck; 173 173 174 174 175 175 $zip->addFromString($nameToCheck.'.pdf',$generator->GetOutput()); 176 176 } 177 177 178 178 179 179 header("Content-Type: application/zip"); 180 180 header("Content-Disposition: attachment; filename=documents.zip"); 181 181 header("Content-Length: " . filesize($path.'documents.zip')); 182 182 readfile($path.'documents.zip'); 183 183 184 184 185 185 $files = glob($path.'*'); // get all file names 186 186 foreach($files as $file){ // iterate files 187 187 if(is_file($file)) 188 188 unlink($file); // delete file 189 189 } 190 190 191 191 die(); 192 192 } 193 193 } 194 194 195 195 public function ManageView(){ 196 196 $orderId=$_GET['orderid']; 197 197 $invoiceId=$_GET['invoiceid']; 198 198 $nonce=$_GET['nonce']; 199 199 200 200 if(!wp_verify_nonce($nonce,'pdfi_manage_nonce')) 201 201 die('Forbidden'); 202 202 203 203 $orderId=$_GET['orderid']; 204 204 $order=wc_get_order($orderId); 205 205 if($order==false) 206 206 { 207 207 echo "Invalid Order Number"; 208 208 die(); 209 209 }else{ 210 210 $invoiceId=-1; 211 211 if(isset($_GET['invoiceid'])) 212 212 $invoiceId=$_GET['invoiceid']; 213 213 require_once 'PDFGenerator.php'; 214 214 215 215 $generator=\rnwcinv\GeneratorFactory::GetGenerator(RednaoPDFGenerator::GetPageOptionsById($invoiceId),$order); 216 216 $generator->GeneratePreview(true); 217 217 die(); 218 218 } 219 219 } 220 220 221 221 public function Search(){ 222 222 RednaoWooCommercePDFInvoice::CheckIfPDFAdmin(); 223 223 $processor=new HttpPostProcessor(); 224 224 $startDate=$processor->GetRequired('StartDate'); 225 225 $endDate=$processor->GetRequired('EndDate'); 226 226 $customerName=$processor->GetRequired('CustomerName'); 227 227 $invoiceNumber=$processor->GetRequired('InvoiceNumber'); 228 228 $invoiceId=$processor->GetRequired('InvoiceId'); 229 229 230 230 RednaoWooCommercePDFInvoice::CheckIfPDFAdmin(); 231 231 232 232 global $wpdb; 233 233 $where=$wpdb->prepare('invoice_id=%s',$invoiceId); 234 234 235 235 if($startDate>0) 236 236 { 237 237 $where.=$wpdb->prepare(' and date>=FROM_UNIXTIME(%d)',$startDate); 238 238 } 239 239 240 240 if($endDate>0) 241 241 { 242 242 $where.=$wpdb->prepare(' and date<=FROM_UNIXTIME(%d)',$endDate); 243 243 } 244 244 245 245 if($customerName!='') 246 246 { 247 247 $where.=' and user.display_name like \'%'.esc_sql($wpdb->esc_like($customerName)).'%\''; 248 248 } 249 249 250 250 if($invoiceNumber!='') 251 251 { 252 252 $where.=' and formatted_invoice_number like \'%'.esc_sql($wpdb->esc_like($invoiceNumber)).'%\''; 253 253 } 254 254 255 255 256 256 $results=$wpdb->get_results(" 257 257 select invoice_id InvoiceId,order_id OrderId,UNIX_TIMESTAMP(date) Date,formatted_invoice_number FormattedInvoiceNumber,post.post_status Status,meta_total.meta_value Total, 258 258 concat(coalesce(meta_firstname.meta_value,''),\" \", coalesce(meta_lastname.meta_value,''),\" (\",user.display_name,\")\") CustomerName 259 259 from ".RednaoWooCommercePDFInvoice::$INVOICES_CREATED_TABLE." created 260 260 join ".$wpdb->posts." post 261 261 on created.order_id=post.ID 262 262 left join ".$wpdb->postmeta." meta_total 263 263 on meta_total.post_id=post.ID and meta_total.meta_key='_order_total' 264 264 left join ".$wpdb->postmeta." meta_user 265 265 on post.ID=meta_user.post_id and meta_user.meta_key='_customer_user' 266 266 left join ".$wpdb->users." user 267 267 on user.ID=meta_user.meta_value 268 268 left join ".$wpdb->usermeta." meta_firstname 269 269 on user.ID=meta_firstname.user_id and meta_firstname.meta_key='billing_first_name' 270 270 left join ".$wpdb->usermeta." meta_lastname 271 271 on user.ID=meta_lastname.user_id and meta_lastname.meta_key='billing_last_name' 272 272 where 273 273 ".$where); 274 274 275 275 $processor->SendSuccessMessage($results); 276 276 277 277 278 278 279 279 } 280 280 281 281 public function DeletePDF(){ 282 282 $processor=new HttpPostProcessor(); 283 283 $OrderId=$processor->GetRequired('OrderId'); 284 284 $InvoiceId=$processor->GetRequired('InvoiceId'); 285 285 $nonce=$processor->GetRequired('Nonce'); 286 286 287 287 if(!wp_verify_nonce($nonce,'delete_'.$OrderId)) 288 288 { 289 289 $processor->SendErrorMessage('Invalid request, please refresh and try again'); 290 290 } 291 291 292 292 global $wpdb; 293 293 $wpdb->delete(RednaoWooCommercePDFInvoice::$INVOICES_CREATED_TABLE, 294 294 array( 295 295 'invoice_id'=>$InvoiceId, 296 296 'order_id'=>$OrderId 297 297 )); 298 298 299 299 $this->SendSuccessMessage(''); 300 300 301 301 } 302 302 303 303 public function LoadTemplate() 304 304 { 305 305 RednaoWooCommercePDFInvoice::CheckIfPDFAdmin(); 306 306 307 307 $processor=new HttpPostProcessor(); 308 308 $source=$processor->GetRequired('source'); 309 309 $fileName=preg_replace("/[^a-z0-9.]+/i", "",$processor->GetRequired('fileName')); 310 310 311 311 $path=RednaoWooCommercePDFInvoice::$DIR; 312 312 if($source=='pr') 313 313 $path.='pr/'; 314 314 else 315 315 $path.='js/'; 316 316 $path.='templates/'.$fileName.'.json'; 317 317 318 318 if(!file_exists($path)) 319 319 $processor->SendErrorMessage('Template does not exists!'); 320 320 $content=file_get_contents($path); 321 321 $content=json_decode($content); 322 322 323 323 $content->containerOptions=json_decode($content->containerOptions); 324 324 $content->pages=json_decode($content->pages); 325 325 if($content->pages==false) 326 326 $content->pages=[]; 327 327 328 328 $content=DocumentOptionsCompatibility::execute($content); 329 329 $processor->SendSuccessMessage($content); 330 330 } 331 331 332 332 public function EmailPDF(){ 333 333 $processor=new HttpPostProcessor(); 334 334 $To=$processor->GetRequired('To'); 335 335 $Subject=$processor->GetRequired('Subject'); 336 336 $Body=$processor->GetRequired('Body'); 337 337 $OrderId=$processor->GetRequired('OrderId'); 338 338 $InvoiceId=$processor->GetRequired('InvoiceId'); 339 339 $nonce=$processor->GetRequired('Nonce'); 340 340 $saveTemplate=$processor->GetRequired('SaveTemplate'); 341 341 // RednaoWooCommercePDFInvoice::CheckIfPDFAdmin(); 342 342 if(!wp_verify_nonce($nonce,'pdfi_manage_nonce')) 343 343 { 344 344 $processor->SendErrorMessage('Invalid request, please refresh and try again'); 345 345 } 346 346 347 347 global $wpdb; 348 348 if($saveTemplate&&RednaoWooCommercePDFInvoice::IsPR()) 349 349 { 350 350 $wpdb->update(RednaoWooCommercePDFInvoice::$INVOICE_TABLE,array( 351 351 'email_config'=>json_encode(array( 352 352 'Subject'=>$Subject, 353 353 'Body'=>$Body 354 354 )) 355 355 ),array('invoice_id'=>$InvoiceId)); 356 356 357 357 } 358 358 359 359 360 360 361 361 $order=wc_get_order($OrderId); 362 362 if($order==false) 363 363 { 364 364 $processor->SendSuccessMessage('Invalid order number'); 365 365 die(); 366 366 }else{ 367 367 require_once RednaoWooCommercePDFInvoice::$DIR. 'PDFGenerator.php'; 368 368 $options=RednaoPDFGenerator::GetPageOptionsById($InvoiceId); 369 369 //remove printer so it is not printed automatically 370 370 for($i=0;$i<count($options->extensions);$i++) 371 371 { 372 372 if($options->extensions[$i]->extensionId=='printer') 373 373 { 374 374 array_splice($options->extensions,$i,1); 375 375 } 376 376 } 377 377 $generator=\rnwcinv\GeneratorFactory::GetGenerator($options,$order); 378 378 $tmp_path = RednaoWooCommercePDFInvoice::GetSubFolderPath('attachments'); 379 379 $tempFolderToReturn=''; 380 380 while(is_dir($tempFolderToReturn=$tmp_path.'temp'.$i.'/')) 381 381 { 382 382 $i++; 383 383 } 384 384 385 385 if(!\mkdir($tempFolderToReturn)) 386 386 throw new Exception('Could not create folder '.$tempFolderToReturn); 387 387 388 388 $tmp_path=$tempFolderToReturn; 389 389 390 390 391 391 392 392 $attachments=array(); 393 393 $generator->GenerateAttachment($tmp_path,$attachments,0); 394 394 if(RednaoWooCommercePDFInvoice::IsPR()) 395 395 { 396 396 ini_set('display_errors', 0); 397 397 $tagManager=new \rnwcinv\pr\Manager\TagManager($generator->orderValueRetriever); 398 398 $Subject=$tagManager->Process($Subject); 399 399 } 400 400 401 401 $headers = array('Content-Type: text/html; charset=UTF-8'); 402 402 do_action('rnwcinv_send_pdf_email',$order->get_id(),$InvoiceId); 403 403 404 404 $emailData=(Object)[ 405 405 'Order'=>$order, 406 406 'InvoiceId'=>$InvoiceId, 407 407 'To'=>$To, 408 408 'Subject'=>$Subject, 409 409 'Body'=>$Body, 410 410 'Attachments'=>$attachments, 411 411 'Headers'=>$headers 412 412 ]; 413 413 414 414 $emailData=apply_filters('rnwcinv_before_sending_email',$emailData); 415 415 416 416 $result=wp_mail($emailData->To,$emailData->Subject,$emailData->Body,$emailData->Headers,$emailData->Attachments); 417 417 if($result==false) 418 418 $this->SendErrorMessage('The email could not be send, please try again'); 419 419 else 420 420 $processor->SendSuccessMessage(''); 421 421 die(); 422 422 } 423 423 } 424 424 425 425 public function GetInvoiceDetail(){ 426 426 $processor=new HttpPostProcessor(); 427 427 $orderNumber=$processor->GetRequired('OrderNumber'); 428 428 $invoiceId=$processor->GetRequired('InvoiceId');; 429 429 430 430 global $wpdb; 431 431 $row=$wpdb->get_row($wpdb->prepare('select invoice_number InvoiceNumber,formatted_invoice_number FormattedInvoiceNumber,unix_timestamp(date) Date from '.RednaoWooCommercePDFInvoice::$INVOICES_CREATED_TABLE. 432 432 ' where order_id=%s and invoice_id=%s',$orderNumber,$invoiceId)); 433 433 434 434 435 435 $this->SendSuccessMessage($row); 436 436 } 437 437 438 438 public function PreviewCustomField(){ 439 439 error_reporting(E_ERROR); 440 440 $processor=new HttpPostProcessor(); 441 441 $options=$processor->GetRequired('Options'); 442 442 CustomFieldValueRetriever::$order=new WC_Order($options->OrderNumber); 443 443 444 444 if($options->FieldType=='table') 445 445 { 446 446 $lineItems=CustomFieldValueRetriever::$order->get_items(); 447 447 if(count($lineItems)>0) 448 448 { 449 449 $value=reset($lineItems); 450 450 CustomFieldValueRetriever::$lineItem = $value; 451 451 } 452 452 453 453 } 454 454 455 455 if(isset($options->OrderFields)&&count($options->OrderFields)>0&&$options->OrderFields[0]->dataType=='array') 456 456 { 457 457 $orderField=$options->OrderFields[0]; 458 458 459 459 $this->SendSuccessMessage(array('html'=>(new CArrayField($orderField->fieldType,$orderField->source,$orderField->key))->GetHTML())); 460 460 } 461 461 462 462 $preview=''; 463 463 foreach($options->OrderFields as $field) 464 464 { 465 465 $subTypeData=null; 466 466 if(isset($field->subTypeData)) 467 467 $subTypeData=$field->subTypeData; 468 468 $integration=null; 469 469 if(isset($field->integration)) 470 470 $integration=$field->integration; 471 471 $preview=''; 472 472 if($field->fieldType=='rnepo') 473 473 { 474 474 $preview.=$field->html; 475 475 } 476 476 477 477 478 478 if($options->FormattingOptions->Type=='image') 479 479 { 480 480 $preview.=(new CImageField($field->fieldType,$field->source,$field->path,$integration,$subTypeData,$options->FormattingOptions->Width,$options->FormattingOptions->Height))->GetHTML().' '; 481 481 }else if($options->FormattingOptions->Type=='qrcode') 482 482 { 483 483 $preview.=(new CSimpleField($field->fieldType,$field->source,$field->path,$integration,$subTypeData))->GetStringValue().' '; 484 484 485 485 require_once RednaoWooCommercePDFInvoice::$DIR.'vendor/phpqrcode/qrlib.php'; 486 486 $svgCode = \QRcode::svg($preview,false,QR_ECLEVEL_L,3,0); 487 487 $preview= '<img src="data:image/svg+xml;base64,' . base64_encode($svgCode).'"></img>'; 488 488 489 489 490 490 } else 491 491 $preview.=(new CSimpleField($field->fieldType,$field->source,$field->path,$integration,$subTypeData))->GetHTML().' '; 492 492 } 493 493 $this->SendSuccessMessage(array('html'=>$preview)); 494 494 495 495 496 496 } 497 497 498 498 public function GetQrPreview(){ 499 499 $options=(object)$this->GetArrayValue('options'); 500 500 $field=FieldFactory::GetField($options,new OrderValueRetriever(null,null,true,null,null)); 501 501 $this->SendSuccessMessage(array('image'=>$field->GetImage())); 502 502 } 503 503 504 504 public function InspectOrder(){ 505 505 $processor=new HttpPostProcessor(); 506 506 507 507 $orderNumber=$processor->GetRequired('OrderNumber'); 508 508 $type=$processor->GetRequired('Type'); 509 509 510 510 require_once RednaoWooCommercePDFInvoice::$DIR.'utilities/WCInspector.php'; 511 511 $inspector=new WCInspector($orderNumber); 512 512 513 513 if($type=='normal') 514 514 $processor->SendSuccessMessage($inspector->InspectOrder()); 515 515 else 516 516 if($type=='row') 517 517 $processor->SendSuccessMessage($inspector->InspectPossibleRows()); 518 518 else 519 519 $processor->SendSuccessMessage($inspector->InspectOrderDetails()); 520 520 die(); 521 521 522 522 } 523 523 524 524 public function SearchInvoice(){ 525 525 $processor=new HttpPostProcessor(); 526 526 527 527 $criteria=$processor->GetRequired('SearchCriteria'); 528 528 529 529 global $wpdb; 530 530 531 531 532 532 533 533 $query = " 534 534 select wp_posts.ID OrderNumber,invoice_date_meta.meta_value Date, invoice_number_meta.meta_value InvoiceNumber 535 535 from ".$wpdb->posts." 536 536 join ".$wpdb->postmeta." invoice_date_meta 537 537 on invoice_date_meta.post_id=wp_posts.ID and invoice_date_meta.meta_key='REDNAO_WCPDFI_INVOICE_DATE' 538 538 join ".$wpdb->postmeta." invoice_number_meta 539 539 on invoice_number_meta.post_id=wp_posts.ID and invoice_number_meta.meta_key='REDNAO_WCPDFI_INVOICE_ID' 540 540 "; 541 541 542 542 if($criteria=="InvoiceNumber"){ 543 543 $query.=$wpdb->prepare(' where invoice_number_meta.meta_value=%s',$processor->GetRequired('InvoiceNumber')); 544 544 } 545 545 546 546 if($criteria=="InvoiceDate"){ 547 547 $startDate=strtotime($processor->GetRequired('StartDate')); 548 548 $endDate=strtotime($processor->GetRequired('EndDate').' +1 day'); 549 549 $query.=$wpdb->prepare(' where invoice_date_meta.meta_value between %d and %d',$startDate,$endDate); 550 550 } 551 551 552 552 if($criteria=="OrderNumber"){ 553 553 $query.=$wpdb->prepare(' where wp_posts.ID=%s',$processor->GetRequired('OrderNumber')); 554 554 } 555 555 556 556 557 557 $results=$wpdb->get_results($query,'ARRAY_A'); 558 558 559 559 foreach($results as &$result) 560 560 { 561 561 $result['Url']=wp_specialchars_decode(get_edit_post_link($result['OrderNumber'])); 562 562 $result['ViewUrl']=wp_specialchars_decode(wp_nonce_url( admin_url( "admin-ajax.php?action=rednao_wcpdfinv_generate_pdf&orderid=" . $result['OrderNumber'] ), 'rednao_wcpdfinv_generate_pdf_'.$result['OrderNumber'] )); 563 563 564 564 565 565 } 566 566 567 567 $processor->SendSuccessMessage($results); 568 568 die(); 569 569 } 570 570 571 571 public function DontShowNewsletter(){ 572 572 update_option('pdfinvoice_newsletter',2); 573 573 $this->SendSuccessMessage(true); 574 574 die(); 575 575 } 576 576 577 577 public function GetLatestError(){ 578 578 // register_shutdown_function(array($this, 'CatchShutdownHandler')); 579 579 echo get_option('PDFInvoiceErrorMessage',''); 580 580 die(); 581 581 } 582 582 583 583 public function RemindMeLater(){ 584 584 $currentStage=get_option('wopdfinv_stage',0); 585 585 update_option('wopdfinv_stage',$currentStage+1); 586 586 } 587 587 588 588 public function DontShowAgain(){ 589 589 update_option('wopdfinv_stage',4); 590 590 $this->SendSuccessMessage(''); 591 591 } 592 592 593 593 public function DiagnoseError(){ 594 594 register_shutdown_function( array($this,'ShutDownCatch')); 595 595 set_error_handler(array($this, 'CatchShutdownHandler')); 596 596 delete_option('PDFInvoiceErrorMessage'); 597 597 $invoiceId=$_POST['invoiceId']; 598 598 require_once 'PDFGenerator.php'; 599 599 if($_POST['testType']=='preview'){ 600 600 601 601 $generator=new RednaoPDFGenerator(RednaoPDFGenerator::GetPageOptionsById($invoiceId),true,null); 602 602 603 603 }else{ 604 604 $orderNumber=$_POST['orderNumber']; 605 605 $order=wc_get_order($orderNumber); 606 606 if($order==false) 607 607 { 608 608 die(); 609 609 }else{ 610 610 $generator=new RednaoPDFGenerator(RednaoPDFGenerator::GetPageOptionsById($invoiceId),false,$order); 611 611 } 612 612 613 613 } 614 614 615 615 $generator->GeneratePreview(); 616 616 die(); 617 617 } 618 618 619 619 public function ShutDownCatch(){ 620 620 if($this->detailCatched) 621 621 return; 622 622 $error = error_get_last(); 623 623 if( $error !== NULL) { 624 624 625 625 626 626 627 627 update_option('PDFInvoiceErrorMessage',json_encode(array( 628 628 "ErrorNumber"=>$error["type"], 629 629 "ErrorMessage"=>$error["message"], 630 630 "ErrorFile"=>$error["file"], 631 631 "ErrorLine"=>$error["line"], 632 632 "ErrorContext"=>"N/A", 633 633 "Detail"=>"Unknown" 634 634 635 635 ))); 636 636 } 637 637 } 638 638 639 639 public function CatchShutdownHandler($errorNumber, $errorStr,$errorFile,$errorLine){ 640 640 $this->detailCatched=true; 641 641 $debug=json_encode(debug_backtrace()); 642 642 643 643 update_option('PDFInvoiceErrorMessage',json_encode(array( 644 644 "ErrorNumber"=>$errorNumber, 645 645 "ErrorMessage"=>$errorStr, 646 646 "ErrorFile"=>$errorFile, 647 647 "ErrorLine"=>$errorLine, 648 648 "ErrorContext"=>null, 649 649 "Detail"=>$debug 650 650 651 651 ))); 652 652 } 653 653 654 654 public function SaveCustomField(){ 655 655 $id=$this->GetStringValue('id',true); 656 656 $name=$this->GetStringValue('name',true); 657 657 $code=$this->GetStringValue('code',true); 658 658 $type=$this->GetStringValue('type',true); 659 659 660 660 if(!is_super_admin()) 661 661 { 662 662 $this->SendErrorMessage('Only admins can edit custom fields'); 663 663 } 664 664 665 665 global $wpdb; 666 666 if($id==0||$id==null) 667 667 { 668 668 669 669 $result=$wpdb->insert(RednaoWooCommercePDFInvoice::$CUSTOM_FIELDS_TABLE,array( 670 670 'custom_field_name'=>$name, 671 671 'custom_field_text'=>$code, 672 672 'custom_field_type'=>$type 673 673 )); 674 674 $rowId=$wpdb->insert_id; 675 675 }else{ 676 676 $result=$wpdb->update(RednaoWooCommercePDFInvoice::$CUSTOM_FIELDS_TABLE,array( 677 677 'custom_field_name'=>$name, 678 678 'custom_field_text'=>$code, 679 679 'custom_field_type'=>$type 680 680 ),array('custom_field_id'=>$id)); 681 681 $rowId=$id; 682 682 } 683 683 684 684 if($result===false) 685 685 { 686 686 $this->SendErrorMessage('Data could not be inserted'); 687 687 } 688 688 else 689 689 { 690 690 $this->SendSuccessMessage(array('row_id' => $rowId)); 691 691 } 692 692 693 693 die(); 694 694 } 695 695 696 696 private function ProcessPostParameter() 697 697 { 698 698 if(!isset($_POST['data'])) 699 699 throw new Exception('Invalid post parameters'); 700 700 701 701 $this->data=json_decode(stripslashes($_POST['data']),true); 702 702 if($this->data==null) 703 703 throw new Exception('Invalid post parameters'); 704 704 } 705 705 706 706 public function Export(){ 707 707 global $wpdb; 708 708 if(!isset($_POST['pageId'])) 709 709 { 710 710 return; 711 711 } 712 $invoiceData=$wpdb->get_row("select extensions,conditions,attach_to,invoice_id,name,options,type,html,pages from ".RednaoWooCommercePDFInvoice::$INVOICE_TABLE." where invoice_id=". $_POST['pageId']);712 $invoiceData=$wpdb->get_row("select extensions,conditions,attach_to,invoice_id,name,options,type,html,pages from ".RednaoWooCommercePDFInvoice::$INVOICE_TABLE." where invoice_id=".intval($_POST['pageId'])); 713 713 if($invoiceData==null){ 714 714 return; 715 715 } 716 716 $invoiceData->extensions=json_decode($invoiceData->extensions); 717 717 $invoiceData->conditions=json_decode($invoiceData->conditions); 718 718 $invoiceData->attach_to=json_decode($invoiceData->attach_to); 719 719 $invoiceData->options=json_decode($invoiceData->options); 720 720 $invoiceData->pages=json_decode($invoiceData->pages); 721 721 $exporter=new \rnwcinv\ImportExport\TemplateExporter(); 722 722 $path=$exporter->Export($invoiceData); 723 723 724 724 725 725 726 726 header("Content-Type: application/zip"); 727 727 header("Content-Disposition: attachment; filename=".basename($path)); 728 728 header("Content-Length: " . filesize($path)); 729 729 readfile($path); 730 730 731 731 $exporter->Destroy(); 732 732 die(); 733 733 } 734 734 735 735 public function GetOptionalJsonValue($propertyName,$defaultValue=null) 736 736 { 737 737 if($this->data==null) 738 738 $this->ProcessPostParameter(); 739 739 740 740 if(!isset($this->data[$propertyName])) 741 741 return $defaultValue; 742 742 743 743 return json_decode($this->data[$propertyName],true); 744 744 745 745 } 746 746 747 747 748 748 749 749 750 750 public function GetJsonValue($propertyName) 751 751 { 752 752 if($this->data==null) 753 753 $this->ProcessPostParameter(); 754 754 755 755 return json_decode($this->data[$propertyName],true); 756 756 } 757 757 758 758 public function GetDesignerPreview() 759 759 { 760 760 require_once('PDFPreview.php'); 761 761 } 762 762 763 763 public function CheckIfOrderIsValid() 764 764 { 765 765 $orderId=$this->GetNumberValue('OrderNumber'); 766 766 $post=get_post($orderId); 767 767 if($post==null||$post->post_type!='shop_order') 768 768 $this->SendErrorMessage("Order Not Found"); 769 769 /*if($post->post_status!='wc-completed') 770 770 $this->SendErrorMessage('Order is not completed');*/ 771 771 $this->SendSuccessMessage('success'); 772 772 } 773 773 774 774 public function GetStringValue($propertyName,$required){ 775 775 if($this->data==null) 776 776 $this->ProcessPostParameter(); 777 777 778 778 if(!isset($this->data[$propertyName])) 779 779 if($required) 780 780 throw new Exception("Parameter not found ".$propertyName); 781 781 else 782 782 return ''; 783 783 784 784 return strval($this->data[$propertyName]); 785 785 } 786 786 787 787 public function UpdateTemplate(){ 788 788 $this->Save(); 789 789 } 790 790 791 791 public function CreatePDF(){ 792 792 793 793 if(!isset($_GET['orderid'])|| wp_verify_nonce($_GET['_wpnonce'], 'rednao_wcpdfinv_generate_pdf_'.intval($_GET['orderid']))==false){ 794 794 die('Forbidden'); 795 795 } 796 796 797 797 798 798 if(!isset($_GET['orderid'])||$_GET['orderid']=='') 799 799 { 800 800 echo "Invalid request, please try again"; 801 801 die(); 802 802 } 803 803 804 804 $actionid='View'; 805 805 if(isset($_GET['actionid'])&&($_GET['actionid']=='View'||$_GET['actionid']=='Download')) 806 806 $actionid=strval($_GET['actionid']); 807 807 808 808 $orderId=$_GET['orderid']; 809 809 810 810 $order=wc_get_order($orderId); 811 811 if($order==false) 812 812 { 813 813 echo "Invalid Order Number"; 814 814 die(); 815 815 }else{ 816 816 $invoiceId=-1; 817 817 if(isset($_GET['invoice_id'])) 818 818 $invoiceId=$_GET['invoice_id']; 819 819 require_once 'PDFGenerator.php'; 820 820 821 821 $generator=\rnwcinv\GeneratorFactory::GetGenerator(RednaoPDFGenerator::GetOptionsForOrder($order,$invoiceId),$order); 822 822 if($actionid=='View') 823 823 $generator->GeneratePreview(true); 824 824 else 825 825 { 826 826 $generator->Generate(); 827 827 header("Content-type: application/pdf"); 828 828 header("Content-disposition: attachment; filename=".basename($generator->GetFileName()).'.pdf'); 829 829 header('Expires: 0'); 830 830 header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 831 831 echo $generator->GetOutput(); 832 832 } 833 833 die(); 834 834 } 835 835 836 836 837 837 } 838 838 839 839 public function GetNumberValue($propertyName, $required=false){ 840 840 if($this->data==null) 841 841 $this->ProcessPostParameter(); 842 842 843 843 844 844 if($required&&!is_numeric($this->data[$propertyName])) 845 845 throw new Exception("Invalid numeric parameter ".$propertyName); 846 846 return intval($this->data[$propertyName]); 847 847 } 848 848 849 849 public function GetBoolValue($propertyName, $required=false){ 850 850 if($this->data==null) 851 851 $this->ProcessPostParameter(); 852 852 853 853 854 854 if($required&&!isset($this->data[$propertyName])) 855 855 throw new Exception("Invalid numeric parameter ".$propertyName); 856 856 857 857 return $this->data[$propertyName]==true; 858 858 } 859 859 860 860 public function GetArrayValue($propertyName) 861 861 { 862 862 if($this->data==null) 863 863 $this->ProcessPostParameter(); 864 864 865 865 if(!is_array($this->data[$propertyName])) 866 866 return array(); 867 867 868 868 return $this->data[$propertyName]; 869 869 870 870 } 871 871 872 872 873 873 public function GetFieldPreview(){ 874 874 $type=$this->GetStringValue('type',false); 875 875 $options=(object)$this->GetArrayValue('fieldOptions'); 876 876 877 877 /** @var FieldDTO $fieldOptions */ 878 878 $fieldOptions=new stdClass(); 879 879 $fieldOptions->type='field'; 880 880 $fieldOptions->fieldOptions=$options; 881 881 $fieldOptions->fieldOptions->fieldType=$type; 882 882 $field=FieldFactory::GetField($fieldOptions,new OrderValueRetriever(null,null,true,null,null)); 883 883 884 884 if($fieldOptions->fieldOptions->fieldType=='inv_number') 885 885 { 886 886 $additionalOptions=(object)$this->GetArrayValue('AdditionalOptions'); 887 887 $formattedNumber=(new InvoiceInitialDataGenerator())->Create(0,0,(object)$additionalOptions->Format,true,new OrderValueRetriever(null,null,true,null,null)); 888 888 $this->SendSuccessMessage($formattedNumber->FormattedInvoiceNumber); 889 889 } 890 890 $this->SendSuccessMessage($field->FormatValue($field->GetFieldValue())); 891 891 892 892 } 893 893 894 894 public function Save(){ 895 895 $pageId=$this->GetNumberValue('pageId',true); 896 896 $pageType=$this->GetNumberValue('pageType',true); 897 897 $name=$this->GetStringValue('name',true); 898 898 $containerOptions=$this->GetStringValue('containerOptions',true); 899 899 $attachTo=$this->GetStringValue('attachTo',true); 900 900 $conditionOptions=$this->GetStringValue('conditions',false); 901 901 $pages=$this->GetStringValue('pages',false); 902 902 $createWhen=$this->GetStringValue('createWhen',false); 903 903 $originalExtensions=$this->GetJsonValue('extensions'); 904 904 $myAccountDownload=$this->GetBoolValue('myAccountDownload',true); 905 905 906 906 907 907 908 908 $orderActions=$this->GetOptionalJsonValue('orderActions'); 909 909 if($orderActions!=null) 910 910 $orderActions=json_encode($orderActions); 911 911 912 912 $extensions=json_encode(apply_filters('rnpdf_invoice_process_extensions_before_save',$originalExtensions)); 913 913 914 914 global $wpdb; 915 915 $result=false; 916 916 $rowId=0; 917 917 $html=''; 918 918 if($pageId==0||$pageId==null) 919 919 { 920 920 921 921 922 922 $result=$wpdb->insert(RednaoWooCommercePDFInvoice::$INVOICE_TABLE,array( 923 923 'name'=>$name, 924 924 'options'=>$containerOptions, 925 925 'type'=>$pageType, 926 926 'options'=>$containerOptions, 927 927 'attach_to'=>$attachTo, 928 928 'extensions'=>$extensions, 929 929 'conditions'=>$conditionOptions, 930 930 'create_when'=>$createWhen, 931 931 'order_actions'=>$orderActions, 932 932 'pages'=>$pages, 933 933 'html'=>$html, 934 934 'my_account_download'=>$myAccountDownload 935 935 )); 936 936 $rowId=$wpdb->insert_id; 937 937 }else{ 938 938 $result=$wpdb->update(RednaoWooCommercePDFInvoice::$INVOICE_TABLE,array( 939 939 'name'=>$name, 940 940 'options'=>$containerOptions, 941 941 'type'=>$pageType, 942 942 'options'=>$containerOptions, 943 943 'pages'=>$pages, 944 944 'attach_to'=>$attachTo, 945 945 'order_actions'=>$orderActions, 946 946 'extensions'=>$extensions, 947 947 'create_when'=>$createWhen, 948 948 'conditions'=>$conditionOptions, 949 949 'my_account_download'=>$myAccountDownload, 950 950 'html'=>$html 951 951 ),array('invoice_id'=>$pageId)); 952 952 $rowId=$pageId; 953 953 } 954 954 955 955 do_action('rnpdf_invoice_process_extensions_after_save',array('pageId'=>$rowId,'extensions'=>$originalExtensions)); 956 956 957 957 if($result===false) 958 958 $this->SendErrorMessage('Data could not be inserted. Reason='.$wpdb->last_error); 959 959 else 960 960 { 961 961 update_option('REDNAO_PDF_INVOICE_EDITED',true); 962 962 $this->SendSuccessMessage(array('row_id' => $rowId)); 963 963 } 964 964 } 965 965 966 966 967 967 public function SendSuccessMessage($data) 968 968 { 969 969 echo json_encode(array( 970 970 'success'=>true, 971 971 'result'=>$data) 972 972 ); 973 973 die; 974 974 } 975 975 976 976 public function SendErrorMessage($errorMessage) 977 977 { 978 978 echo json_encode(array( 979 979 'success'=>false, 980 980 'errorMessage'=>$errorMessage) 981 981 ); 982 982 die; 983 983 } 984 984 985 985 986 986 987 987 988 988 } 989 989 990 990 new RednaoWooCommercePDFInvoiceAjax(); 991 991
Note: See TracChangeset
for help on using the changeset viewer.