Plugin Directory


Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • woo-pdf-invoice-builder/trunk/woocommerce-pdf-invoice-ajax.php

    r2935371 r2949518  
    11<?php
    22/**
    33 * Created by PhpStorm.
    44 * User: Edgar
    55 * Date: 10/10/2017
    66 * Time: 7:50 AM
    77 */
    88
    99
    1010use rnwcinv\compatibility\DocumentOptionsCompatibility;
    1111use rnwcinv\htmlgenerator\FieldDTO;
    1212use rnwcinv\htmlgenerator\fields\FieldFactory;
    1313use rnwcinv\htmlgenerator\OrderValueRetriever;
    1414use rnwcinv\pr\CustomField\CustomFieldBase;
    1515use rnwcinv\pr\CustomField\CustomFieldFactory;
    1616use rnwcinv\pr\CustomField\SimpleCustomField;
    1717use rnwcinv\pr\CustomField\utilities\CustomFieldValueRetriever;
    1818use rnwcinv\pr\CustomFieldV2\BasicFields\CArrayField;
    1919use rnwcinv\pr\CustomFieldV2\BasicFields\CImageField;
    2020use rnwcinv\pr\CustomFieldV2\BasicFields\CSimpleField;
    2121use rnwcinv\pr\utilities\FontManager;
    2222use rnwcinv\utilities\InvoiceInitialDataGenerator;
    2323
    2424require_once RednaoWooCommercePDFInvoice::$DIR.'utilities/HttpPostProcessor.php';
    2525final class RednaoWooCommercePDFInvoiceAjax{
    2626    public $data=null;
    2727    public $detailCatched=false;
    2828    public function __construct()
    2929    {
    3030        add_action('wp_ajax_rednao_wcpdfinv_get_field_preview',array($this,'GetFieldPreview'));
    3131        add_action('wp_ajax_rednao_wcpdfinv_get_qr_preview',array($this,'GetQrPreview'));
    3232        add_action('wp_ajax_rednao_wcpdfinv_save_custom_field',array($this,'SaveCustomField'));
    3333        add_action('wp_ajax_rednao_wcpdfinv_get_designer_preview',array($this,'GetDesignerPreview'));
    3434        add_action('wp_ajax_rednao_wcpdfinv_save',array($this,'Save'));
    3535        add_action('wp_ajax_rednao_search_invoice',array($this,'SearchInvoice'));
    3636        add_action('wp_ajax_rednao_check_if_order_is_valid',array($this,'CheckIfOrderIsValid'));
    3737        add_action('wp_ajax_rednao_wcpdfinv_generate_pdf',array($this,'CreatePDF'));
    3838        add_action('wp_ajax_rednao_update_template',array($this,'UpdateTemplate'));
    3939        add_action('wp_ajax_rednao_wcpdfinv_get_designer_export',array($this,'Export'));
    4040        add_action('wp_ajax_rednao_wcpdfinv_remind_me',array($this,'RemindMeLater'));
    4141        add_action('wp_ajax_rednao_wcpdfinv_dont_show_again',array($this,'DontShowAgain'));
    4242        add_action('wp_ajax_rednao_wcpdfinv_diagnose_error',array($this,'DiagnoseError'));
    4343        add_action('wp_ajax_rednao_wcpdfinv_get_latest_error',array($this,'GetLatestError'));
    4444        add_action('wp_ajax_rednao_wcpdfinv_dont_show_again_nl',array($this,'DontShowNewsletter'));
    4545        add_action('wp_ajax_rednao_wcpdfinv_inspect_order',array($this,'InspectOrder'));
    4646        add_action('wp_ajax_rednao_wcpdfinv_preview_custom_field',array($this,'PreviewCustomField'));
    4747        add_action('wp_ajax_rednao_wcpdfinv_get_invoice_details',array($this,'GetInvoiceDetail'));
    4848        add_action('wp_ajax_rednao_wcpdfinv_load_template',array($this,'LoadTemplate'));
    4949        add_action('wp_ajax_rednao_wcpdfinv_email_pdf',array($this,'EmailPDF'));
    5050        add_action('wp_ajax_rednao_wcpdfinv_delete_pdf',array($this,'DeletePDF'));
    5151        add_action('wp_ajax_rednao_wcpdfinv_manage_delete',array($this,'ManageDelete'));
    5252        add_action('wp_ajax_rednao_wcpdfinv_search',array($this,'Search'));
    5353        add_action('wp_ajax_rednao_wcpdfinv_manage_view',array($this,'ManageView'));
    5454        add_action('wp_ajax_rednao_wcpdfinv_download',array($this,'Download'));
    5555        add_action('wp_ajax_rednao_wcpdfinv_save_next_number',array($this,'SaveNextNumber'));
    5656
    5757
    5858    }
    5959
    6060
    6161
    6262    public function  SaveNextNumber(){
    6363        RednaoWooCommercePDFInvoice::CheckIfPDFAdmin();
    6464        $processor=new HttpPostProcessor();
    6565
    6666        $invoiceId=$processor->GetRequired('invoiceid');
    6767        $nextNumber=$processor->GetRequired('number');
    6868
    6969        update_option($invoiceId. '_rednao_pdf_invoice_number',apply_filters('wcpdfi_update_latest_invoice_number',$nextNumber,$invoiceId));
    7070
    7171        $processor->SendSuccessMessage();
    7272    }
    7373
    7474    public function ManageDelete(){
    7575        RednaoWooCommercePDFInvoice::CheckIfPDFAdmin();
    7676        $processor=new HttpPostProcessor();
    7777        $nonce=$processor->GetRequired('Nonce');
    7878        if(!wp_verify_nonce($nonce,'pdfi_manage_nonce'))
    7979            die('Forbidden');
    8080
    8181        $invoiceList=$processor->GetRequired('Invoices');
    8282        global $wpdb;
    8383        $ids='';
    8484        $allDeleted=true;
    8585        foreach($invoiceList as $invoice)
    8686        {
    8787            $result=$wpdb->query($wpdb->prepare('delete from '.RednaoWooCommercePDFInvoice::$INVOICES_CREATED_TABLE. ' where invoice_id =%s and order_id=%s',$invoice->InvoiceId,$invoice->OrderId));
    8888            if($result==false)
    8989            {
    9090                $allDeleted=true;
    9191            }
    9292
    9393
    9494
    9595        }
    9696
    9797        if(!$allDeleted)
    9898        {
    9999            $this->SendErrorMessage('Some items could not be deleted, please try again');
    100100        }
    101101
    102102        $this->SendSuccessMessage('Items deleted successfully');
    103103    }
    104104
    105105    public function Download(){
    106106        RednaoWooCommercePDFInvoice::CheckIfPDFAdmin();
    107107        $processor=new HttpPostProcessor();
    108108        $nonce=$processor->GetRequired('Nonce');
    109109        if(!wp_verify_nonce($nonce,'pdfi_manage_nonce'))
    110110            die('Forbidden');
    111111
    112112        $invoiceList=$processor->GetRequired('Invoices');
    113113
    114114        if(count($invoiceList)==1)
    115115        {
    116116            $orderId=$invoiceList[0]->OrderId;
    117117            $invoiceId=$invoiceList[0]->InvoiceId;
    118118            $order=wc_get_order($orderId);
    119119            if($order==false)
    120120            {
    121121                echo "Invalid Order Number";
    122122                die();
    123123            }
    124124
    125125            require_once 'PDFGenerator.php';
    126126
    127127            $generator=\rnwcinv\GeneratorFactory::GetGenerator(RednaoPDFGenerator::GetPageOptionsById($invoiceId),$order);
    128128            $generator->Generate(true,true);
    129129
    130130            header("Content-type: application/pdf");
    131131            header("Content-disposition: attachment; filename=".basename($generator->GetFileName()).'.pdf');
    132132            header('Expires: 0');
    133133            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    134134            echo $generator->GetOutput();
    135135
    136136            die();
    137137        }else{
    138138
    139139            $uploadDir=wp_upload_dir();
    140140            $path= $uploadDir['basedir'].'/sf_pdfs_bulk';
    141141
    142142            if(!is_dir($path))
    143143                RednaoWooCommercePDFInvoice::CreateFolder($path);
    144144
    145145
    146146            $zip=new \ZipArchive();
    147147            $usedNames=[];
    148148            $zip->open( $path.'documents.zip',\ZipArchive::CREATE|\ZipArchive::OVERWRITE);
    149149            foreach($invoiceList as $invoice)
    150150            {
    151151                $order=wc_get_order($invoice->OrderId);
    152152                if($order==false)
    153153                {
    154154                    echo "Invalid Order Number";
    155155                    die();
    156156                }
    157157
    158158                require_once 'PDFGenerator.php';
    159159
    160160                $generator=\rnwcinv\GeneratorFactory::GetGenerator(RednaoPDFGenerator::GetPageOptionsById($invoice->InvoiceId),$order);
    161161                $generator->Generate(true,true);
    162162
    163163
    164164                $name=$generator->GetFileName();
    165165                $nameToCheck=strtolower($name);
    166166                $index=1;
    167167                while(array_search($nameToCheck,$usedNames)!==false)
    168168                {
    169169                    $nameToCheck=strtolower($name).'('.$index.')';
    170170                    $index++;
    171171                }
    172172                $usedNames[]=$nameToCheck;
    173173
    174174
    175175                $zip->addFromString($nameToCheck.'.pdf',$generator->GetOutput());
    176176            }
    177177
    178178
    179179            header("Content-Type: application/zip");
    180180            header("Content-Disposition: attachment; filename=documents.zip");
    181181            header("Content-Length: " . filesize($path.'documents.zip'));
    182182            readfile($path.'documents.zip');
    183183
    184184
    185185            $files = glob($path.'*'); // get all file names
    186186            foreach($files as $file){ // iterate files
    187187                if(is_file($file))
    188188                    unlink($file); // delete file
    189189            }
    190190
    191191            die();
    192192        }
    193193    }
    194194
    195195    public function ManageView(){
    196196        $orderId=$_GET['orderid'];
    197197        $invoiceId=$_GET['invoiceid'];
    198198        $nonce=$_GET['nonce'];
    199199
    200200        if(!wp_verify_nonce($nonce,'pdfi_manage_nonce'))
    201201            die('Forbidden');
    202202
    203203        $orderId=$_GET['orderid'];
    204204        $order=wc_get_order($orderId);
    205205        if($order==false)
    206206        {
    207207            echo "Invalid Order Number";
    208208            die();
    209209        }else{
    210210            $invoiceId=-1;
    211211            if(isset($_GET['invoiceid']))
    212212                $invoiceId=$_GET['invoiceid'];
    213213            require_once 'PDFGenerator.php';
    214214
    215215            $generator=\rnwcinv\GeneratorFactory::GetGenerator(RednaoPDFGenerator::GetPageOptionsById($invoiceId),$order);
    216216            $generator->GeneratePreview(true);
    217217            die();
    218218        }
    219219    }
    220220
    221221    public function Search(){
    222222        RednaoWooCommercePDFInvoice::CheckIfPDFAdmin();
    223223        $processor=new HttpPostProcessor();
    224224        $startDate=$processor->GetRequired('StartDate');
    225225        $endDate=$processor->GetRequired('EndDate');
    226226        $customerName=$processor->GetRequired('CustomerName');
    227227        $invoiceNumber=$processor->GetRequired('InvoiceNumber');
    228228        $invoiceId=$processor->GetRequired('InvoiceId');
    229229
    230230        RednaoWooCommercePDFInvoice::CheckIfPDFAdmin();
    231231
    232232        global $wpdb;
    233233        $where=$wpdb->prepare('invoice_id=%s',$invoiceId);
    234234
    235235        if($startDate>0)
    236236        {
    237237            $where.=$wpdb->prepare(' and date>=FROM_UNIXTIME(%d)',$startDate);
    238238        }
    239239
    240240        if($endDate>0)
    241241        {
    242242            $where.=$wpdb->prepare(' and date<=FROM_UNIXTIME(%d)',$endDate);
    243243        }
    244244
    245245        if($customerName!='')
    246246        {
    247247            $where.=' and user.display_name like \'%'.esc_sql($wpdb->esc_like($customerName)).'%\'';
    248248        }
    249249
    250250        if($invoiceNumber!='')
    251251        {
    252252            $where.=' and formatted_invoice_number like \'%'.esc_sql($wpdb->esc_like($invoiceNumber)).'%\'';
    253253        }
    254254
    255255
    256256        $results=$wpdb->get_results("
    257257            select invoice_id InvoiceId,order_id OrderId,UNIX_TIMESTAMP(date) Date,formatted_invoice_number FormattedInvoiceNumber,post.post_status Status,meta_total.meta_value Total,
    258258            concat(coalesce(meta_firstname.meta_value,''),\" \", coalesce(meta_lastname.meta_value,''),\" (\",user.display_name,\")\")  CustomerName
    259259            from ".RednaoWooCommercePDFInvoice::$INVOICES_CREATED_TABLE." created
    260260            join ".$wpdb->posts." post
    261261            on created.order_id=post.ID
    262262            left join ".$wpdb->postmeta." meta_total
    263263            on meta_total.post_id=post.ID and meta_total.meta_key='_order_total'
    264264            left join ".$wpdb->postmeta." meta_user
    265265            on post.ID=meta_user.post_id and meta_user.meta_key='_customer_user'
    266266            left join ".$wpdb->users." user
    267267            on user.ID=meta_user.meta_value
    268268            left join ".$wpdb->usermeta." meta_firstname
    269269            on user.ID=meta_firstname.user_id and meta_firstname.meta_key='billing_first_name'
    270270            left join ".$wpdb->usermeta." meta_lastname
    271271            on user.ID=meta_lastname.user_id and meta_lastname.meta_key='billing_last_name'
    272272            where
    273273        ".$where);
    274274
    275275        $processor->SendSuccessMessage($results);
    276276
    277277
    278278
    279279    }
    280280
    281281    public function DeletePDF(){
    282282        $processor=new HttpPostProcessor();
    283283        $OrderId=$processor->GetRequired('OrderId');
    284284        $InvoiceId=$processor->GetRequired('InvoiceId');
    285285        $nonce=$processor->GetRequired('Nonce');
    286286
    287287        if(!wp_verify_nonce($nonce,'delete_'.$OrderId))
    288288        {
    289289            $processor->SendErrorMessage('Invalid request, please refresh and try again');
    290290        }
    291291
    292292        global $wpdb;
    293293        $wpdb->delete(RednaoWooCommercePDFInvoice::$INVOICES_CREATED_TABLE,
    294294            array(
    295295               'invoice_id'=>$InvoiceId,
    296296                'order_id'=>$OrderId
    297297            ));
    298298
    299299        $this->SendSuccessMessage('');
    300300
    301301    }
    302302
    303303    public function LoadTemplate()
    304304    {
    305305        RednaoWooCommercePDFInvoice::CheckIfPDFAdmin();
    306306
    307307        $processor=new HttpPostProcessor();
    308308        $source=$processor->GetRequired('source');
    309309        $fileName=preg_replace("/[^a-z0-9.]+/i", "",$processor->GetRequired('fileName'));
    310310
    311311        $path=RednaoWooCommercePDFInvoice::$DIR;
    312312        if($source=='pr')
    313313            $path.='pr/';
    314314        else
    315315            $path.='js/';
    316316        $path.='templates/'.$fileName.'.json';
    317317
    318318        if(!file_exists($path))
    319319            $processor->SendErrorMessage('Template does not exists!');
    320320        $content=file_get_contents($path);
    321321        $content=json_decode($content);
    322322
    323323        $content->containerOptions=json_decode($content->containerOptions);
    324324        $content->pages=json_decode($content->pages);
    325325        if($content->pages==false)
    326326            $content->pages=[];
    327327
    328328        $content=DocumentOptionsCompatibility::execute($content);
    329329        $processor->SendSuccessMessage($content);
    330330    }
    331331
    332332    public function EmailPDF(){
    333333        $processor=new HttpPostProcessor();
    334334        $To=$processor->GetRequired('To');
    335335        $Subject=$processor->GetRequired('Subject');
    336336        $Body=$processor->GetRequired('Body');
    337337        $OrderId=$processor->GetRequired('OrderId');
    338338        $InvoiceId=$processor->GetRequired('InvoiceId');
    339339        $nonce=$processor->GetRequired('Nonce');
    340340        $saveTemplate=$processor->GetRequired('SaveTemplate');
    341341      //  RednaoWooCommercePDFInvoice::CheckIfPDFAdmin();
    342342        if(!wp_verify_nonce($nonce,'pdfi_manage_nonce'))
    343343        {
    344344            $processor->SendErrorMessage('Invalid request, please refresh and try again');
    345345        }
    346346
    347347        global $wpdb;
    348348        if($saveTemplate&&RednaoWooCommercePDFInvoice::IsPR())
    349349        {
    350350            $wpdb->update(RednaoWooCommercePDFInvoice::$INVOICE_TABLE,array(
    351351                'email_config'=>json_encode(array(
    352352                    'Subject'=>$Subject,
    353353                    'Body'=>$Body
    354354                ))
    355355            ),array('invoice_id'=>$InvoiceId));
    356356
    357357        }
    358358
    359359
    360360
    361361        $order=wc_get_order($OrderId);
    362362        if($order==false)
    363363        {
    364364            $processor->SendSuccessMessage('Invalid order number');
    365365            die();
    366366        }else{
    367367            require_once RednaoWooCommercePDFInvoice::$DIR. 'PDFGenerator.php';
    368368            $options=RednaoPDFGenerator::GetPageOptionsById($InvoiceId);
    369369            //remove printer so it is not printed automatically
    370370            for($i=0;$i<count($options->extensions);$i++)
    371371            {
    372372                if($options->extensions[$i]->extensionId=='printer')
    373373                {
    374374                    array_splice($options->extensions,$i,1);
    375375                }
    376376            }
    377377            $generator=\rnwcinv\GeneratorFactory::GetGenerator($options,$order);
    378378            $tmp_path = RednaoWooCommercePDFInvoice::GetSubFolderPath('attachments');
    379379            $tempFolderToReturn='';
    380380            while(is_dir($tempFolderToReturn=$tmp_path.'temp'.$i.'/'))
    381381            {
    382382                $i++;
    383383            }
    384384
    385385            if(!\mkdir($tempFolderToReturn))
    386386                throw new Exception('Could not create folder '.$tempFolderToReturn);
    387387
    388388            $tmp_path=$tempFolderToReturn;
    389389
    390390
    391391
    392392            $attachments=array();
    393393            $generator->GenerateAttachment($tmp_path,$attachments,0);
    394394            if(RednaoWooCommercePDFInvoice::IsPR())
    395395            {
    396396                ini_set('display_errors', 0);
    397397                $tagManager=new \rnwcinv\pr\Manager\TagManager($generator->orderValueRetriever);
    398398                $Subject=$tagManager->Process($Subject);
    399399            }
    400400
    401401            $headers = array('Content-Type: text/html; charset=UTF-8');
    402402            do_action('rnwcinv_send_pdf_email',$order->get_id(),$InvoiceId);
    403403
    404404            $emailData=(Object)[
    405405                'Order'=>$order,
    406406                'InvoiceId'=>$InvoiceId,
    407407                'To'=>$To,
    408408                'Subject'=>$Subject,
    409409                'Body'=>$Body,
    410410                'Attachments'=>$attachments,
    411411                'Headers'=>$headers
    412412            ];
    413413
    414414            $emailData=apply_filters('rnwcinv_before_sending_email',$emailData);
    415415
    416416            $result=wp_mail($emailData->To,$emailData->Subject,$emailData->Body,$emailData->Headers,$emailData->Attachments);
    417417            if($result==false)
    418418                $this->SendErrorMessage('The email could not be send, please try again');
    419419            else
    420420                $processor->SendSuccessMessage('');
    421421            die();
    422422        }
    423423    }
    424424
    425425    public function GetInvoiceDetail(){
    426426        $processor=new HttpPostProcessor();
    427427        $orderNumber=$processor->GetRequired('OrderNumber');
    428428        $invoiceId=$processor->GetRequired('InvoiceId');;
    429429
    430430        global $wpdb;
    431431        $row=$wpdb->get_row($wpdb->prepare('select invoice_number InvoiceNumber,formatted_invoice_number FormattedInvoiceNumber,unix_timestamp(date) Date from '.RednaoWooCommercePDFInvoice::$INVOICES_CREATED_TABLE.
    432432            ' where order_id=%s and invoice_id=%s',$orderNumber,$invoiceId));
    433433
    434434
    435435        $this->SendSuccessMessage($row);
    436436    }
    437437
    438438    public function PreviewCustomField(){
    439439        error_reporting(E_ERROR);
    440440        $processor=new HttpPostProcessor();
    441441        $options=$processor->GetRequired('Options');
    442442        CustomFieldValueRetriever::$order=new WC_Order($options->OrderNumber);
    443443
    444444        if($options->FieldType=='table')
    445445        {
    446446            $lineItems=CustomFieldValueRetriever::$order->get_items();
    447447            if(count($lineItems)>0)
    448448            {
    449449                $value=reset($lineItems);
    450450                CustomFieldValueRetriever::$lineItem = $value;
    451451            }
    452452
    453453        }
    454454
    455455        if(isset($options->OrderFields)&&count($options->OrderFields)>0&&$options->OrderFields[0]->dataType=='array')
    456456        {
    457457            $orderField=$options->OrderFields[0];
    458458
    459459            $this->SendSuccessMessage(array('html'=>(new CArrayField($orderField->fieldType,$orderField->source,$orderField->key))->GetHTML()));
    460460        }
    461461
    462462        $preview='';
    463463        foreach($options->OrderFields as $field)
    464464        {
    465465            $subTypeData=null;
    466466            if(isset($field->subTypeData))
    467467                $subTypeData=$field->subTypeData;
    468468            $integration=null;
    469469            if(isset($field->integration))
    470470                $integration=$field->integration;
    471471            $preview='';
    472472            if($field->fieldType=='rnepo')
    473473            {
    474474                $preview.=$field->html;
    475475            }
    476476
    477477
    478478            if($options->FormattingOptions->Type=='image')
    479479            {
    480480                $preview.=(new CImageField($field->fieldType,$field->source,$field->path,$integration,$subTypeData,$options->FormattingOptions->Width,$options->FormattingOptions->Height))->GetHTML().' ';
    481481            }else if($options->FormattingOptions->Type=='qrcode')
    482482            {
    483483                $preview.=(new CSimpleField($field->fieldType,$field->source,$field->path,$integration,$subTypeData))->GetStringValue().' ';
    484484
    485485                require_once RednaoWooCommercePDFInvoice::$DIR.'vendor/phpqrcode/qrlib.php';
    486486                $svgCode = \QRcode::svg($preview,false,QR_ECLEVEL_L,3,0);
    487487                $preview= '<img   src="data:image/svg+xml;base64,' . base64_encode($svgCode).'"></img>';
    488488
    489489
    490490            } else
    491491                $preview.=(new CSimpleField($field->fieldType,$field->source,$field->path,$integration,$subTypeData))->GetHTML().' ';
    492492        }
    493493        $this->SendSuccessMessage(array('html'=>$preview));
    494494
    495495
    496496    }
    497497
    498498    public function GetQrPreview(){
    499499        $options=(object)$this->GetArrayValue('options');
    500500        $field=FieldFactory::GetField($options,new OrderValueRetriever(null,null,true,null,null));
    501501        $this->SendSuccessMessage(array('image'=>$field->GetImage()));
    502502    }
    503503
    504504    public function InspectOrder(){
    505505        $processor=new HttpPostProcessor();
    506506
    507507        $orderNumber=$processor->GetRequired('OrderNumber');
    508508        $type=$processor->GetRequired('Type');
    509509
    510510        require_once RednaoWooCommercePDFInvoice::$DIR.'utilities/WCInspector.php';
    511511        $inspector=new WCInspector($orderNumber);
    512512
    513513        if($type=='normal')
    514514            $processor->SendSuccessMessage($inspector->InspectOrder());
    515515        else
    516516        if($type=='row')
    517517            $processor->SendSuccessMessage($inspector->InspectPossibleRows());
    518518        else
    519519            $processor->SendSuccessMessage($inspector->InspectOrderDetails());
    520520        die();
    521521
    522522    }
    523523
    524524    public function SearchInvoice(){
    525525        $processor=new HttpPostProcessor();
    526526
    527527        $criteria=$processor->GetRequired('SearchCriteria');
    528528
    529529        global $wpdb;
    530530
    531531
    532532
    533533        $query = "
    534534            select wp_posts.ID OrderNumber,invoice_date_meta.meta_value Date, invoice_number_meta.meta_value InvoiceNumber
    535535            from ".$wpdb->posts."
    536536              join ".$wpdb->postmeta."  invoice_date_meta
    537537              on invoice_date_meta.post_id=wp_posts.ID and invoice_date_meta.meta_key='REDNAO_WCPDFI_INVOICE_DATE'
    538538              join ".$wpdb->postmeta."  invoice_number_meta
    539539              on invoice_number_meta.post_id=wp_posts.ID and invoice_number_meta.meta_key='REDNAO_WCPDFI_INVOICE_ID'
    540540        ";
    541541
    542542        if($criteria=="InvoiceNumber"){
    543543            $query.=$wpdb->prepare(' where invoice_number_meta.meta_value=%s',$processor->GetRequired('InvoiceNumber'));
    544544        }
    545545
    546546        if($criteria=="InvoiceDate"){
    547547            $startDate=strtotime($processor->GetRequired('StartDate'));
    548548            $endDate=strtotime($processor->GetRequired('EndDate').' +1 day');
    549549            $query.=$wpdb->prepare(' where invoice_date_meta.meta_value between %d and %d',$startDate,$endDate);
    550550        }
    551551
    552552        if($criteria=="OrderNumber"){
    553553            $query.=$wpdb->prepare(' where wp_posts.ID=%s',$processor->GetRequired('OrderNumber'));
    554554        }
    555555
    556556
    557557        $results=$wpdb->get_results($query,'ARRAY_A');
    558558
    559559        foreach($results as &$result)
    560560        {
    561561            $result['Url']=wp_specialchars_decode(get_edit_post_link($result['OrderNumber']));
    562562            $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'] ));
    563563
    564564
    565565        }
    566566
    567567        $processor->SendSuccessMessage($results);
    568568        die();
    569569    }
    570570
    571571    public function DontShowNewsletter(){
    572572        update_option('pdfinvoice_newsletter',2);
    573573        $this->SendSuccessMessage(true);
    574574        die();
    575575    }
    576576
    577577    public function GetLatestError(){
    578578        // register_shutdown_function(array($this, 'CatchShutdownHandler'));
    579579        echo get_option('PDFInvoiceErrorMessage','');
    580580        die();
    581581    }
    582582
    583583    public function RemindMeLater(){
    584584        $currentStage=get_option('wopdfinv_stage',0);
    585585        update_option('wopdfinv_stage',$currentStage+1);
    586586    }
    587587
    588588    public function DontShowAgain(){
    589589        update_option('wopdfinv_stage',4);
    590590        $this->SendSuccessMessage('');
    591591    }
    592592
    593593    public function DiagnoseError(){
    594594        register_shutdown_function( array($this,'ShutDownCatch'));
    595595        set_error_handler(array($this, 'CatchShutdownHandler'));
    596596        delete_option('PDFInvoiceErrorMessage');
    597597        $invoiceId=$_POST['invoiceId'];
    598598        require_once 'PDFGenerator.php';
    599599        if($_POST['testType']=='preview'){
    600600
    601601            $generator=new RednaoPDFGenerator(RednaoPDFGenerator::GetPageOptionsById($invoiceId),true,null);
    602602
    603603        }else{
    604604            $orderNumber=$_POST['orderNumber'];
    605605            $order=wc_get_order($orderNumber);
    606606            if($order==false)
    607607            {
    608608                die();
    609609            }else{
    610610                $generator=new RednaoPDFGenerator(RednaoPDFGenerator::GetPageOptionsById($invoiceId),false,$order);
    611611            }
    612612
    613613        }
    614614
    615615        $generator->GeneratePreview();
    616616        die();
    617617    }
    618618
    619619    public function ShutDownCatch(){
    620620        if($this->detailCatched)
    621621            return;
    622622        $error = error_get_last();
    623623        if( $error !== NULL) {
    624624
    625625
    626626
    627627            update_option('PDFInvoiceErrorMessage',json_encode(array(
    628628                "ErrorNumber"=>$error["type"],
    629629                "ErrorMessage"=>$error["message"],
    630630                "ErrorFile"=>$error["file"],
    631631                "ErrorLine"=>$error["line"],
    632632                "ErrorContext"=>"N/A",
    633633                "Detail"=>"Unknown"
    634634
    635635            )));
    636636        }
    637637    }
    638638
    639639    public function CatchShutdownHandler($errorNumber, $errorStr,$errorFile,$errorLine){
    640640        $this->detailCatched=true;
    641641        $debug=json_encode(debug_backtrace());
    642642
    643643        update_option('PDFInvoiceErrorMessage',json_encode(array(
    644644            "ErrorNumber"=>$errorNumber,
    645645            "ErrorMessage"=>$errorStr,
    646646            "ErrorFile"=>$errorFile,
    647647            "ErrorLine"=>$errorLine,
    648648            "ErrorContext"=>null,
    649649            "Detail"=>$debug
    650650
    651651        )));
    652652    }
    653653
    654654    public function SaveCustomField(){
    655655        $id=$this->GetStringValue('id',true);
    656656        $name=$this->GetStringValue('name',true);
    657657        $code=$this->GetStringValue('code',true);
    658658        $type=$this->GetStringValue('type',true);
    659659
    660660        if(!is_super_admin())
    661661        {
    662662            $this->SendErrorMessage('Only admins can edit custom fields');
    663663        }
    664664
    665665        global $wpdb;
    666666        if($id==0||$id==null)
    667667        {
    668668
    669669            $result=$wpdb->insert(RednaoWooCommercePDFInvoice::$CUSTOM_FIELDS_TABLE,array(
    670670                'custom_field_name'=>$name,
    671671                'custom_field_text'=>$code,
    672672                'custom_field_type'=>$type
    673673            ));
    674674            $rowId=$wpdb->insert_id;
    675675        }else{
    676676            $result=$wpdb->update(RednaoWooCommercePDFInvoice::$CUSTOM_FIELDS_TABLE,array(
    677677                'custom_field_name'=>$name,
    678678                'custom_field_text'=>$code,
    679679                'custom_field_type'=>$type
    680680            ),array('custom_field_id'=>$id));
    681681            $rowId=$id;
    682682        }
    683683
    684684        if($result===false)
    685685        {
    686686            $this->SendErrorMessage('Data could not be inserted');
    687687        }
    688688        else
    689689        {
    690690            $this->SendSuccessMessage(array('row_id' => $rowId));
    691691        }
    692692
    693693        die();
    694694    }
    695695
    696696    private function ProcessPostParameter()
    697697    {
    698698        if(!isset($_POST['data']))
    699699            throw new Exception('Invalid post parameters');
    700700
    701701        $this->data=json_decode(stripslashes($_POST['data']),true);
    702702        if($this->data==null)
    703703            throw new Exception('Invalid post parameters');
    704704    }
    705705
    706706    public function Export(){
    707707        global $wpdb;
    708708        if(!isset($_POST['pageId']))
    709709        {
    710710            return;
    711711        }
    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']));
    713713        if($invoiceData==null){
    714714            return;
    715715        }
    716716        $invoiceData->extensions=json_decode($invoiceData->extensions);
    717717        $invoiceData->conditions=json_decode($invoiceData->conditions);
    718718        $invoiceData->attach_to=json_decode($invoiceData->attach_to);
    719719        $invoiceData->options=json_decode($invoiceData->options);
    720720        $invoiceData->pages=json_decode($invoiceData->pages);
    721721        $exporter=new \rnwcinv\ImportExport\TemplateExporter();
    722722        $path=$exporter->Export($invoiceData);
    723723
    724724
    725725
    726726        header("Content-Type: application/zip");
    727727        header("Content-Disposition: attachment; filename=".basename($path));
    728728        header("Content-Length: " . filesize($path));
    729729        readfile($path);
    730730
    731731        $exporter->Destroy();
    732732        die();
    733733    }
    734734
    735735    public function GetOptionalJsonValue($propertyName,$defaultValue=null)
    736736    {
    737737        if($this->data==null)
    738738            $this->ProcessPostParameter();
    739739
    740740        if(!isset($this->data[$propertyName]))
    741741            return $defaultValue;
    742742
    743743        return json_decode($this->data[$propertyName],true);
    744744
    745745    }
    746746
    747747
    748748
    749749
    750750    public function GetJsonValue($propertyName)
    751751    {
    752752        if($this->data==null)
    753753            $this->ProcessPostParameter();
    754754
    755755        return json_decode($this->data[$propertyName],true);
    756756    }
    757757
    758758    public function GetDesignerPreview()
    759759    {
    760760        require_once('PDFPreview.php');
    761761    }
    762762
    763763    public function CheckIfOrderIsValid()
    764764    {
    765765        $orderId=$this->GetNumberValue('OrderNumber');
    766766        $post=get_post($orderId);
    767767        if($post==null||$post->post_type!='shop_order')
    768768            $this->SendErrorMessage("Order Not Found");
    769769        /*if($post->post_status!='wc-completed')
    770770            $this->SendErrorMessage('Order is not completed');*/
    771771        $this->SendSuccessMessage('success');
    772772    }
    773773
    774774    public function GetStringValue($propertyName,$required){
    775775        if($this->data==null)
    776776            $this->ProcessPostParameter();
    777777
    778778        if(!isset($this->data[$propertyName]))
    779779            if($required)
    780780                throw new Exception("Parameter not found ".$propertyName);
    781781            else
    782782                return '';
    783783
    784784        return strval($this->data[$propertyName]);
    785785    }
    786786
    787787    public function UpdateTemplate(){
    788788        $this->Save();
    789789    }
    790790
    791791    public function CreatePDF(){
    792792
    793793        if(!isset($_GET['orderid'])|| wp_verify_nonce($_GET['_wpnonce'], 'rednao_wcpdfinv_generate_pdf_'.intval($_GET['orderid']))==false){
    794794            die('Forbidden');
    795795        }
    796796
    797797
    798798        if(!isset($_GET['orderid'])||$_GET['orderid']=='')
    799799        {
    800800            echo "Invalid request, please try again";
    801801            die();
    802802        }
    803803
    804804        $actionid='View';
    805805        if(isset($_GET['actionid'])&&($_GET['actionid']=='View'||$_GET['actionid']=='Download'))
    806806            $actionid=strval($_GET['actionid']);
    807807
    808808        $orderId=$_GET['orderid'];
    809809
    810810        $order=wc_get_order($orderId);
    811811        if($order==false)
    812812        {
    813813            echo "Invalid Order Number";
    814814            die();
    815815        }else{
    816816            $invoiceId=-1;
    817817            if(isset($_GET['invoice_id']))
    818818                $invoiceId=$_GET['invoice_id'];
    819819            require_once 'PDFGenerator.php';
    820820
    821821            $generator=\rnwcinv\GeneratorFactory::GetGenerator(RednaoPDFGenerator::GetOptionsForOrder($order,$invoiceId),$order);
    822822            if($actionid=='View')
    823823                $generator->GeneratePreview(true);
    824824            else
    825825            {
    826826                $generator->Generate();
    827827                header("Content-type: application/pdf");
    828828                header("Content-disposition: attachment; filename=".basename($generator->GetFileName()).'.pdf');
    829829                header('Expires: 0');
    830830                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    831831                echo $generator->GetOutput();
    832832            }
    833833            die();
    834834        }
    835835
    836836
    837837    }
    838838
    839839    public function GetNumberValue($propertyName, $required=false){
    840840        if($this->data==null)
    841841            $this->ProcessPostParameter();
    842842
    843843
    844844        if($required&&!is_numeric($this->data[$propertyName]))
    845845            throw new Exception("Invalid numeric parameter ".$propertyName);
    846846        return intval($this->data[$propertyName]);
    847847    }
    848848
    849849    public function GetBoolValue($propertyName, $required=false){
    850850        if($this->data==null)
    851851            $this->ProcessPostParameter();
    852852
    853853
    854854        if($required&&!isset($this->data[$propertyName]))
    855855            throw new Exception("Invalid numeric parameter ".$propertyName);
    856856
    857857        return $this->data[$propertyName]==true;
    858858    }
    859859
    860860    public function GetArrayValue($propertyName)
    861861    {
    862862        if($this->data==null)
    863863            $this->ProcessPostParameter();
    864864
    865865        if(!is_array($this->data[$propertyName]))
    866866            return array();
    867867
    868868        return $this->data[$propertyName];
    869869
    870870    }
    871871
    872872
    873873    public function GetFieldPreview(){
    874874        $type=$this->GetStringValue('type',false);
    875875        $options=(object)$this->GetArrayValue('fieldOptions');
    876876
    877877        /** @var FieldDTO $fieldOptions */
    878878        $fieldOptions=new stdClass();
    879879        $fieldOptions->type='field';
    880880        $fieldOptions->fieldOptions=$options;
    881881        $fieldOptions->fieldOptions->fieldType=$type;
    882882        $field=FieldFactory::GetField($fieldOptions,new OrderValueRetriever(null,null,true,null,null));
    883883
    884884        if($fieldOptions->fieldOptions->fieldType=='inv_number')
    885885        {
    886886            $additionalOptions=(object)$this->GetArrayValue('AdditionalOptions');
    887887            $formattedNumber=(new InvoiceInitialDataGenerator())->Create(0,0,(object)$additionalOptions->Format,true,new OrderValueRetriever(null,null,true,null,null));
    888888            $this->SendSuccessMessage($formattedNumber->FormattedInvoiceNumber);
    889889        }
    890890        $this->SendSuccessMessage($field->FormatValue($field->GetFieldValue()));
    891891
    892892    }
    893893
    894894    public function Save(){
    895895        $pageId=$this->GetNumberValue('pageId',true);
    896896        $pageType=$this->GetNumberValue('pageType',true);
    897897        $name=$this->GetStringValue('name',true);
    898898        $containerOptions=$this->GetStringValue('containerOptions',true);
    899899        $attachTo=$this->GetStringValue('attachTo',true);
    900900        $conditionOptions=$this->GetStringValue('conditions',false);
    901901        $pages=$this->GetStringValue('pages',false);
    902902        $createWhen=$this->GetStringValue('createWhen',false);
    903903        $originalExtensions=$this->GetJsonValue('extensions');
    904904        $myAccountDownload=$this->GetBoolValue('myAccountDownload',true);
    905905
    906906
    907907
    908908        $orderActions=$this->GetOptionalJsonValue('orderActions');
    909909        if($orderActions!=null)
    910910            $orderActions=json_encode($orderActions);
    911911
    912912        $extensions=json_encode(apply_filters('rnpdf_invoice_process_extensions_before_save',$originalExtensions));
    913913
    914914        global $wpdb;
    915915        $result=false;
    916916        $rowId=0;
    917917        $html='';
    918918        if($pageId==0||$pageId==null)
    919919        {
    920920
    921921
    922922            $result=$wpdb->insert(RednaoWooCommercePDFInvoice::$INVOICE_TABLE,array(
    923923                'name'=>$name,
    924924                'options'=>$containerOptions,
    925925                'type'=>$pageType,
    926926                'options'=>$containerOptions,
    927927                'attach_to'=>$attachTo,
    928928                'extensions'=>$extensions,
    929929                'conditions'=>$conditionOptions,
    930930                'create_when'=>$createWhen,
    931931                'order_actions'=>$orderActions,
    932932                'pages'=>$pages,
    933933                'html'=>$html,
    934934                'my_account_download'=>$myAccountDownload
    935935            ));
    936936            $rowId=$wpdb->insert_id;
    937937        }else{
    938938            $result=$wpdb->update(RednaoWooCommercePDFInvoice::$INVOICE_TABLE,array(
    939939                'name'=>$name,
    940940                'options'=>$containerOptions,
    941941                'type'=>$pageType,
    942942                'options'=>$containerOptions,
    943943                'pages'=>$pages,
    944944                'attach_to'=>$attachTo,
    945945                'order_actions'=>$orderActions,
    946946                'extensions'=>$extensions,
    947947                'create_when'=>$createWhen,
    948948                'conditions'=>$conditionOptions,
    949949                'my_account_download'=>$myAccountDownload,
    950950                'html'=>$html
    951951            ),array('invoice_id'=>$pageId));
    952952            $rowId=$pageId;
    953953        }
    954954
    955955        do_action('rnpdf_invoice_process_extensions_after_save',array('pageId'=>$rowId,'extensions'=>$originalExtensions));
    956956
    957957        if($result===false)
    958958            $this->SendErrorMessage('Data could not be inserted. Reason='.$wpdb->last_error);
    959959        else
    960960        {
    961961            update_option('REDNAO_PDF_INVOICE_EDITED',true);
    962962            $this->SendSuccessMessage(array('row_id' => $rowId));
    963963        }
    964964    }
    965965
    966966
    967967    public function SendSuccessMessage($data)
    968968    {
    969969        echo json_encode(array(
    970970            'success'=>true,
    971971            'result'=>$data)
    972972        );
    973973        die;
    974974    }
    975975
    976976    public function SendErrorMessage($errorMessage)
    977977    {
    978978        echo json_encode(array(
    979979                'success'=>false,
    980980                'errorMessage'=>$errorMessage)
    981981        );
    982982        die;
    983983    }
    984984
    985985
    986986
    987987
    988988}
    989989
    990990new RednaoWooCommercePDFInvoiceAjax();
    991991
Note: See TracChangeset for help on using the changeset viewer.