Exemple #1
0
 public function GetModifications()
 {
     $query = "SELECT * FROM phpmmo_storage_file_history WHERE file_id = " . $this->ID;
     $result = mysql_query($query);
     $count = mysql_num_rows($result);
     $retval = array();
     for ($i = 0; $i < $count; $i++) {
         $values = mysql_fetch_assoc($result);
         $retval[] = FileModification::GetByAssoc($values);
     }
     return $retval;
 }
Exemple #2
0
    /**
     * Generate or regenerate PDF for AP
     * @param $apId
     * @param bool $approved
     * @deprecated since 26.05.2015
     *
     */
    public static function generatePdf($apId, $approved = false)
    {
        // get AP
        $ap = Aps::model()->with('dists', 'document', 'ck_req_detail')->findByPk($apId);

        $ckReqDet = $ap->ck_req_detail;

        // get PO dists
        $apDists = $ap->dists;

        // get PO formatting
        $poFormatting = PoFormatting::model()->findByAttributes(array(
            'Project_ID' => $ap->document->Project_ID,
        ));

        // get Sign_Requested_By user info
        $signRequestedByUser = Users::model()->with('person')->findByPk($ckReqDet->Sign_Requested_By);

        $aproval_detail_list = Audits::getApprovalDetailList($ap->Document_ID);
        // get current vendor info
        $currentVendor = Vendors::model()->with('client.company.adreses')->findByPk($ap->Vendor_ID);

        $condition = UsersClientList::getClientAdminCondition($currentVendor->client->Client_ID);
        $vendorAdmin = UsersClientList::model()->with('user.person')->find($condition);

        // get content for pdf
        $content = Yii::app()->controller->renderPartial('application.views.ap.ap_template', array(
            'ap' => $ap,
            'ckReqDet' => $ckReqDet,
            'poFormatting' => $poFormatting,
            'apDists' => $apDists,
            'currentVendor' => $currentVendor,
            'vendorAdmin' => $vendorAdmin,
            'signRequestedByUser' => $signRequestedByUser,

            'aproval_detail_list' => $aproval_detail_list,

            'approved' => $approved,
        ), true);

        $fileName = Helper::createDirectory('generated_po');
        $fileName = $fileName.'/' . Yii::app()->user->userID . '-' . date("Y_m_d_H_i_s") . '.pdf';
        Yii::import('ext.html2pdf.HTML2PDF');
        $html2pdf = new HTML2PDF('P', 'A4', 'en');
        $html2pdf->writeHTML($content);
        $html2pdf->Output($fileName, 'F');

        // insert or update image image
        $image = Images::model()->findByAttributes(array(
            'Document_ID' => $ap->Document_ID,
        ));

        if (!$image) {
            $image = new Images();
        }

        $imageData = addslashes(fread(fopen($fileName,"rb"),filesize($fileName)));
        $image->Document_ID = $ap->Document_ID;
        $image->Img = $imageData;
        $image->File_Name = Yii::app()->user->userID . '-' . date("Y_m_d_H_i_s") . '.pdf';
        $image->Mime_Type = 'application/pdf';
        $image->File_Hash = sha1_file($fileName);
        $image->File_Size = intval(filesize($fileName));
        $image->Pages_Count = FileModification::calculatePagesByPath($fileName);
        $image->save();

        if (file_exists($fileName)) {
            @unlink($fileName);
        }
    }
Exemple #3
0
    public function actionRotateNotSaved(){
        $result['success'] = false;
        if(Yii::app()->request->isAjaxRequest && $_POST['docID']){

            $filepath=strval($_POST['docID']);
            if(is_file($filepath)) {

                $path_parts = pathinfo($filepath);
                $return_array['ext']=$path_parts['extension'];
                $return_array['path_to_dir']=$path_parts['dirname'];
                $return_array['filename']=$path_parts['basename'];

                $rotate_direction=strval ($_POST['action']);

                if($return_array['ext']!='pdf'){
                    $return_array = FileModification::ImageToPdf($return_array['path_to_dir'],$return_array['filename'],$return_array['ext']);
                }

                if(!$result['error']) {
                    $result=FileModification::rotateFile($return_array['path_to_dir'],$return_array['filename'],$rotate_direction);
                    $result['success'] = true;
                } else {
                    $result['success'] = false;
                    $result['error_message'] = "File was not rendered.";
                }
            }
        }

        echo CJSON::encode($result);
    }
Exemple #4
0
    public function run() {
        //convert to pdf
        if( $this->params['mime_type'] && strtolower( $this->params['mime_type'])!='application/pdf' &&  intval($this->params['doc_id'])>0 ) {
            $return_array=FileModification::prepareFile($this->params['doc_id']);
            $return_array = FileModification::ImageToPdf($return_array['path_to_dir'],$return_array['filename'],$return_array['ext']);
            $return_array = FileModification::writeToBase($return_array['path_to_dir'],$return_array['filename'],'application/pdf',$this->params['doc_id']);
            $this->params['mime_type'] = 'application/pdf';
        } else if (!$this->params['mime_type']) {
            $return_array=FileModification::prepareFile($this->params['doc_id']);
            $return_array = FileModification::writeToBase($return_array['path_to_dir'],$return_array['filename'],'application/pdf',$this->params['doc_id']);
        }

        //old style display
        if ($this->params['mode']==1) {
            if ($this->params['show_rotate']) {
                $show_rotate_buttons_block =  $this->render("application.views.filemodification.buttons",array(
                        'buttons' => array('rotate_cw','rotate_ccw'),
                        'docId'  => $this->params['doc_id'],
                        'file_name'=>'',
                        'imgId'=>''
                    ), true);

            }

            $result = $this->render('application.views.filemodification.iframe',array(
                    'mime_type'=>$this->params['mime_type'],
                    'doc_id'=>$this->params['doc_id'],
                    'show_rotate_buttons_block'=> $show_rotate_buttons_block,
                ),true
            );

           echo $result;
        }


        //PDF.js iframe
        //full version PDF.js viewer only with CSS modified and some toolbars and buttons hided
        if ($this->params['mode']==3) {
            /*$result = $this->render('application.views.filemodification.pdfjs',array(
                    'doc_id'=>$this->params['doc_id'],
                    'mime_type'=>$this->params['mime_type'],
                    'approved'=>$this->params['approved'],
                    'height'=>$this->params['height'],
                ),true
            );
            echo $result;*/

            /*$url = '/documents/getdocumentfile?doc_id='.intval($this->params['doc_id']);
            $this->widget('ext.pdfJs.QPdfJs',array(
                'url'=>$url,
                'options'=>array(
                    'buttons'=>array(
                        'print' => $this->params['approved'],
                        'download'=>$this->params['approved'],
                    ),
                    'height'=>800,
                    'approved'=>$this->params['approved'],

                )
            ));*/

            //we need to add files in cache in order not to show real path to whole internet.
            $file_id = FileCache::addToFileCache($this->params['doc_id']);
            $height = $this->params['height']? $this->params['height']: 800 ;
            $content = '<iframe src="/documents/PreviewFile?file_id='.$file_id.'&approved='.$this->params['approved'].'" style="width: 99.9%;height:'.$height.'px;" > </iframe>';
            echo $content;

        }


        //PDF.js own viewer
        //custom viewer based on PDF.JS sample customised as a built-in Chrome viewer. Has text selection functionallity
        if ($this->params['mode']==4) {
            $result = $this->render('application.views.filemodification.ownviewer',array(
                    'doc_id'=>$this->params['doc_id'],
                    'mime_type'=>$this->params['mime_type'],
                    'approved'=>$this->params['approved']
                ),true
            );
            echo $result;
        }

        //PDF.js own viewer
        //custom viewer based on PDF.JS sample customised as a built-in Chrome viewer. WITHOUT text selection functionallity
        if ($this->params['mode']==5) {
            $result = $this->render('application.views.filemodification.ownviewer_light',array(
                    'doc_id'=>$this->params['doc_id'],
                    'mime_type'=>$this->params['mime_type'],
                    'approved'=>$this->params['approved']
                ),true
            );
            echo $result;
        }





        //$this->render('breadCrumb');
    }
Exemple #5
0
    public static function pdfGeneration ($doc_id,$doc_type, $approved) {

        $pdf_array = FileModification::generatePdfFpdf($doc_id,$doc_type,$approved);

        $result = Images::fileToDatabase($doc_id,$pdf_array['path'],$pdf_array['pages']);

        if (file_exists($pdf_array['path'])) {
            @unlink($pdf_array['path']);
        }


    }
Exemple #6
0
    protected function generate_response($content, $print_response = true) {
        if ($print_response) {

            //replace values with modified after file conversion
            foreach ($content['files'] as $file_item) {
                $file_item->url='';
                $file_item->thumbnailUrl='';
                $file_item->path= FileCache::updateFileInCache($file_item->path);

                $new_file_name = FileModification::getFileNameByPath(FileCache::getCacheFilePath($file_item->path));
                if ($new_file_name)  $file_item->name = $new_file_name ;

                //$new_file_ext = FileModification::getFileExtByPath(FileCache::getCacheFilePath($file_item->path));
                $file_item->type = 'application/pdf' ;

                $newcontent['files'][] = $file_item;
            }

            $content = $newcontent;
            $json = json_encode($content);
            $redirect = isset($_REQUEST['redirect']) ?
                stripslashes($_REQUEST['redirect']) : null;
            if ($redirect) {
                $this->header('Location: '.sprintf($redirect, rawurlencode($json)));
                return;
            }
            $this->head();
            if ($this->get_server_var('HTTP_CONTENT_RANGE')) {
                $files = isset($content[$this->options['param_name']]) ?
                    $content[$this->options['param_name']] : null;
                if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) {
                    $this->header('Range: 0-'.(
                        $this->fix_integer_overflow(intval($files[0]->size)) - 1
                    ));
                }
            }
            $this->body($json);
        }
        return $content;
    }
Exemple #7
0
    public static function commandLineConcat($files_array,$path) {

        chdir($path);
        $string_file_list = '';
        foreach ($files_array AS $file) {
              $string_file_list.= $file.' ';
        }

        $command = 'gs -o SummaryPDF.pdf -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress '.$string_file_list;
        exec($command);

        $filename  = $path.'/SummaryPDF.pdf';
        $page_count = FileModification::getPdfPagesCount($filename);

        return array(
            'filename'=>$filename,
            'page_count'=>$page_count);

    }
Exemple #8
0
    public static function createNewFromSessionData($current_upload_file,$client){

        if (file_exists($current_upload_file['filepath'])) {
            // create document

            $document = new Documents();
            $document->Document_Type = $current_upload_file['doctype'];
            $document->User_ID = Yii::app()->user->userID;
            $document->Client_ID = Yii::app()->user->clientID;
            $document->Project_ID = Yii::app()->user->projectID;
            $document->Created = date("Y-m-d H:i:s");
            $document->save();
            $new_doc_id=$document->Document_ID;

            Audits::LogAction($document->Document_ID ,Audits::ACTION_UPLOAD);

            // insert image
            $image = new Images();
            $imageData = addslashes(fread(fopen($current_upload_file['filepath'],"rb"),filesize($current_upload_file['filepath'])));
            //$imageData = FileModification::ImageToPdfByFilePath($current_upload_file['filepath']);
            $image->Document_ID = $document->Document_ID;
            $image->Img = $imageData;
            $image->File_Name = $current_upload_file['name'];
            $image->Mime_Type = $current_upload_file['mimetype'];
            $image->File_Hash = sha1_file($current_upload_file['filepath']);
            $image->File_Size = intval(filesize($current_upload_file['filepath']));
            $image->Pages_Count = FileModification::calculatePagesByPath($current_upload_file['filepath']);

            $image->save();

            $infile = @file_get_contents($current_upload_file['filepath'], FILE_BINARY);
            if (($current_upload_file['mimetype'] == 'application/pdf' && $image->findPdfText($infile) == '')
                || $current_upload_file['mimetype'] != 'application/pdf') {
                Documents::crateDocumentThumbnail($current_upload_file['filepath'], 'thumbs', $current_upload_file['mimetype'], $document->Document_ID, 80);
            }

            // delete file from temporary catalog
            unlink($current_upload_file['filepath']);
        }

        $fedId = trim($current_upload_file['fed_id']);
        $newCompanyName = trim($current_upload_file['company_name']);

        // get company info
        $company = Companies::model()->with('client')->findByAttributes(array(
            'Company_Fed_ID' => $fedId,
        ));

        // create w9
        $W9 = new W9();
        $W9->Document_ID = $document->Document_ID;
        $W9->W9_Owner_ID = Yii::app()->user->clientID;
        $W9->Creator_ID = Yii::app()->user->userID;
        $W9->Business_Name = trim($current_upload_file['bus_name']);
        $W9->Tax_Class =  trim($current_upload_file['tax_name']);

        // get user info
        $user = Users::model()->with('person')->findByPk(Yii::app()->user->userID);

        if ($company) {
            // if company exisits
            $client = $company->client;

            //fill created company with dataentry values from session
            Companies::fillWithSessionDataEntry($company,$current_upload_file);

            $existingW9 = W9::model()->findByAttributes(array(
                'Client_ID' => $client->Client_ID,
                'W9_Owner_ID' => Yii::app()->user->clientID,
            ));

            if ($existingW9) {
                $W9->Revision_ID = -1;
            } else {
                $W9->Revision_ID = 0;
            }

            $vendor = Vendors::model()->findByAttributes(array(
                'Client_Client_ID' => Yii::app()->user->clientID,
                'Vendor_Client_ID' => $client->Client_ID,
            ));

            if (isset($vendor->Active_Relationship) && $vendor->Active_Relationship == Vendors::NOT_ACTIVE_RELATIONSHIP) {
                $vendor->Active_Relationship = Vendors::ACTIVE_RELATIONSHIP;
                $vendor->save();
            } else if (!$vendor && Yii::app()->user->clientID != 0 && Yii::app()->user->clientID != $client->Client_ID) {
                $vendor = new Vendors();
                $vendor->Vendor_ID_Shortcut = '';
                $vendor->Vendor_Client_ID = $client->Client_ID;
                $vendor->Client_Client_ID = Yii::app()->user->clientID;
                $vendor->Vendor_Name_Checkprint = '';
                $vendor->Vendor_1099 = '';
                $vendor->Vendor_Default_GL = '';
                $vendor->Vendor_Default_GL_Note = '';
                $vendor->Vendor_Note_General = '';
                $vendor->save();
            }
        } else {
            //if company does not exists, create new company

            $company_model = Companies::model()->findByPk($client->Company_ID);
            //fill created company with dataentry values from session
            Companies::fillWithSessionDataEntry($company_model,$current_upload_file);

            if (Yii::app()->user->clientID != 0) {
                $vendor = new Vendors();
                $vendor->Vendor_ID_Shortcut = '';
                $vendor->Vendor_Client_ID = $company_model->Company_ID;
                $vendor->Client_Client_ID = Yii::app()->user->clientID;
                $vendor->Vendor_Name_Checkprint = '';
                $vendor->Vendor_1099 = '';
                $vendor->Vendor_Default_GL = '';
                $vendor->Vendor_Default_GL_Note = '';
                $vendor->Vendor_Note_General = '';
                $vendor->save();
            }

            $W9->Revision_ID = 0;
        }

        // save w9
        $W9->Client_ID = $client->Client_ID;
        $W9->save();

        return $W9;

    }
    public static function CalculatePages($origing,$cli_id) {

        set_time_limit(200);
        $sum = 0;
        $condition = new CDbCriteria();
        if ($origing != '') $condition->condition = "Origin='" . $origing . "'";
        $condition->addCondition("Client_ID = '" . $cli_id . "'");

        $documents = Documents::model()->findAll($condition);

        require_once(Yii::app()->basePath.'/extensions/Fpdf/fpdf.php');
        require_once(Yii::app()->basePath.'/extensions/Fpdi/fpdi.php');

        foreach($documents as $document) {
            $pages = FileModification::calculatePagesByDocID($document->Document_ID);

            if ($pages > 1)
            {
                $image = Images::model()->findByAttributes(array(
                    'Document_ID'=>$document->Document_ID
                ));
                if ($image ) {
                    $image->Pages_Count = $pages;
                    $image->save();
                }

            }


            $sum += $pages;

        }

        return $sum;

    }
Exemple #10
0
    /**
     * Generate or regenerate PDF for PO
     * @param $poId
     * @param bool $approved
     */
    public static function generatePdf($poId, $approved = false)
    {
        // get PO
        $po = Pos::model()->with('dists', 'decr_details', 'document')->findByPk($poId);

        // get PO dists
        $poDists = $po->dists;

        // get PO details
        $poDecrDetails = $po->decr_details;

        // get PO formatting
        $poFormatting = PoFormatting::model()->findByAttributes(array(
            'Project_ID' => $po->document->Project_ID,
        ));

        // get Sign_Requested_By user info
        $signRequestedByUser = Users::model()->with('person')->findByPk($po->Sign_Requested_By);

        $aproval_detail_list = Audits::getApprovalDetailList($po->Document_ID);

        // get current vendor info
        $currentVendor = Vendors::model()->with('client.company.adreses')->findByPk($po->Vendor_ID);

        $condition = UsersClientList::getClientAdminCondition($currentVendor->client->Client_ID);
        $vendorAdmin = UsersClientList::model()->with('user.person')->find($condition);

        // get content for pdf
        $content = Yii::app()->controller->renderPartial('application.views.po.po_template', array(
            'po' => $po,
            'poFormatting' => $poFormatting,
            'poDecrDetails' => $poDecrDetails,
            'poDists' => $poDists,
            'currentVendor' => $currentVendor,
            'vendorAdmin' => $vendorAdmin,
            'signRequestedByUser' => $signRequestedByUser,

            'aproval_detail_list' => $aproval_detail_list,
            'approved' => $approved,
            'paymentTypes' => array(
                'OA' => 'On Account',
                'CC' => 'Credit Card',
                'DP' => 'Deposit',
                'CK' => 'Payment Check',
                'PC' => 'Petty Cash',
            ),
        ), true);

        $fileName = 'protected/data/generated_po/' . Yii::app()->user->userID . '-' . date("Y_m_d_H_i_s") . '.pdf';
        Yii::import('ext.html2pdf.HTML2PDF');
        $html2pdf = new HTML2PDF('P', 'A4', 'en');
        $html2pdf->writeHTML($content);//TO LONG TIME!!!!!! NEEDS OPTIMISATION
        $html2pdf->Output($fileName, 'F');

        // insert or update image image
        $image = Images::model()->findByAttributes(array(
            'Document_ID' => $po->Document_ID,
        ));

        if (!$image) {
            $image = new Images();
        }

        $imageData = addslashes(fread(fopen($fileName,"rb"), filesize($fileName)));
        $image->Document_ID = $po->Document_ID;
        $image->Img = $imageData;
        $image->File_Name = Yii::app()->user->userID . '-' . date("Y_m_d_H_i_s") . '.pdf';
        $image->Mime_Type = 'application/pdf';
        $image->File_Hash = sha1_file($fileName);
        $image->File_Size = intval(filesize($fileName));
        $image->Pages_Count = FileModification::calculatePagesByPath($fileName);
        $image->save();

        if (file_exists($fileName)) {
            @unlink($fileName);
        }
    }
Exemple #11
0
    /**
     * Updates file in cashe. Even if it already in it.
     * @param $fileitentifier
     */
    public static function updateFileInCache($fileitentifier) {
        $path = FileModification::createDirectory('filecache');
        $path = FileModification::createDirectory('filecache/'.Yii::app()->user->clientID);

        if (is_file($fileitentifier)) {
            //if this if image from filesystem

            //convert to pdf
            $result_file_array = FileModification::PdfByFilePath($fileitentifier);
            $filepath = $result_file_array['filepath'];
            $filename = $result_file_array['filename'];

            $path_to_base = $filepath;
            $fileId = sha1_file($filepath).sha1($filepath);

        } else {
            //if this is image from database
                $image = Images::model()->findByAttributes(array(
                    'Document_ID' => intval($fileitentifier)
                ));

                if($image) {
                    $mime = explode('/', $image->Mime_Type);
                    $temp_file_path = $path . '/' . $image->File_Name;
                    $infile = stripslashes($image->Img);
                    file_put_contents($temp_file_path, $infile);

                    $fileId = intval($fileitentifier);
                    $path_to_base = $temp_file_path;
                }
        }


        FileCache::deleteFromCacheById($fileitentifier);
        FileCache::deleteFromCacheById($fileId);

        $fileCash = new FileCache();

            $fileCash->file_id = $fileId;
            $fileCash->path = $path_to_base;
            $fileCash->client_id = Yii::app()->user->clientID;
            $fileCash->user_id = Yii::app()->user->userID;
            $fileCash->Created = time();
            $fileCash->save();

            $result_id = $fileCash->file_id;

        return $result_id;
    }
Exemple #12
0
    /**
     * Generate report files
     * @param $docType
     * @param $batchType
     * @param $batchFormat
     * @param $documents
     */
    public function generateReports($docType, $batchType, $batchFormat, $documents,$client_datetime, $batch_id)
    {
        if ($docType == Documents::AP) {
            $sql = "SELECT
                        a.Document_ID as docID,
                        v.Vendor_ID_Shortcut as VendorID,
                        com.Company_Name as vendorName,
                        a.Invoice_Number as InvNum,
                        a.Invoice_Date as InvDate,
                        a.Invoice_Due_Date as DueDate,
                        a.Invoice_Amount as InvAmt,
                        a.Invoice_Reference as InvDesc,
                        a.Detail_1099 ,
                        a.Detail_1099_Box_Number as Box,
                        d.GL_Dist_Detail_COA_Acct_Number as GLCode,
                        d.GL_Dist_Detail_Amt as GLAmt,
                        d.GL_Dist_Detail_Desc as GLDesc
                    FROM aps as a

                    LEFT JOIN gl_dist_details as d ON d.AP_ID = a.AP_ID
                    LEFT JOIN documents as doc ON doc.Document_ID = a.Document_ID
                    LEFT JOIN vendors as v ON v.Vendor_ID = a.Vendor_ID
                    LEFT JOIN clients as c ON v.Vendor_Client_ID = c.Client_ID
                    LEFT JOIN companies as com ON com.Company_ID = c.Company_ID
                    WHERE doc.Document_ID IN (" . implode(',', $documents) . ")";


        } else {
            $sql = "SELECT
                        p.Document_ID as docID,
                        v.Vendor_ID_Shortcut as VendorID,
                        com.Company_Name as vendorName,
                        p.PO_Number as InvNum,
                        p.PO_Date as InvDate,
                        p.PO_Total as InvAmt,
                        p.PO_Pmts_Tracking_Note as InvDesc,
                        d.PO_Dists_GL_Code as GLCode,
                        d.PO_Dists_Amount as GLAmt,
                        d.PO_Dists_Description as GLDesc
                    FROM pos as p
                    LEFT JOIN po_dists as d ON d.PO_ID = p.PO_ID
                    LEFT JOIN documents as doc ON doc.Document_ID = p.Document_ID
                    LEFT JOIN vendors as v ON v.Vendor_ID = p.Vendor_ID
                    LEFT JOIN clients as c ON v.Vendor_Client_ID = c.Client_ID
                    LEFT JOIN companies as com ON com.Company_ID = c.Company_ID
                    WHERE doc.Document_ID IN (" . implode(',', $documents) . ")";


        }

        $connection = Yii::app()->db;
        $command = $connection->createCommand($sql);
        $exportRows = $command->queryAll();


        if ($batchType == self::EXCEL) {
            //generating of main batch
            $documentFilePath = self::generateBatchExcel($exportRows, $batchFormat);
            //generating of pdf report
            $reportFilePath = $this->generateSummaryFPDF($exportRows,$client_datetime,$batch_id,$docType);
        } else if ($batchType == self::CSV) {
            //generating of main batch
            $documentFilePath = self::generateBatchCSV($exportRows, $batchFormat);
            //generating of pdf report
            $reportFilePath = $this->generateSummaryFPDF($exportRows,$client_datetime,$batch_id,$docType);
        } else if ($batchType == self::PDF) {
            //generating of pdf report
            $reportFilePath = $this->generateSummaryFPDF($exportRows,$client_datetime,$batch_id,$docType);
            //generating of main batch
            $documentFilePath = self::generateBatchPDF($exportRows, $batch_id,$client_datetime,$docType,$batchFormat);
            $reportFilePath = FileModification::concatFiles(array($reportFilePath,$documentFilePath));
        }

        //generation of report



        $this->Batch_Document = addslashes(fread(fopen($documentFilePath,"rb"),filesize($documentFilePath)));
        $this->Batch_Summary = addslashes(fread(fopen($reportFilePath,"rb"),filesize($reportFilePath)));

        @unlink($documentFilePath);
        @unlink($reportFilePath);
    }
Exemple #13
-2
public static function writeToBase($path_to_dir,$filename,$mime,$docId){

    $image = Images::model()->findByAttributes(array(
        'Document_ID' => $docId,
    ));

    if(!$image) {
        $image= new Images();
        $image->Document_ID=$docId;
    }
    $path= $path_to_dir.'/'.$filename;
    $imageData = addslashes(fread(fopen($path,"rb"),filesize($path)));

    $image->Img = $imageData;
    $image->File_Name = $filename;
    $image->Mime_Type = $mime;
    $image->File_Hash = sha1_file($path);
    $image->File_Size = intval(filesize($path));
    $image->Pages_Count = FileModification::calculatePagesByPath($path);
    $image->save();

    unlink($path);

    $result['path_to_dir']=$path_to_dir;
    $result['file_name']=$filename;
    $result['mime']=$mime;

}