Subversion Repositories enhancedezbinaryfile

[/] [datatypes/] [enhancedezbinaryfile/] [enhancedezbinaryfiletype.php] - Blame information for rev 5

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 1 steven.bailey
<?php
2
//
3
// Definition of EnhancedeZBinaryFileType class
4
//
5
// SOFTWARE NAME: eZ Publish
6 5 steven.bailey
// SOFTWARE RELEASE: 4.5.0
7 1 steven.bailey
// BUILD VERSION: 21995
8 4 steven.bailey
// COPYRIGHT NOTICE: Copyright (C) 1999-2010 Contactivity.com
9 1 steven.bailey
// SOFTWARE LICENSE: GNU General Public License v2.0
10
// NOTICE: >
11
//   This program is free software; you can redistribute it and/or
12
//   modify it under the terms of version 2.0  of the GNU General
13
//   Public License as published by the Free Software Foundation.
14
//
15
//   This program is distributed in the hope that it will be useful,
16
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
17
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
//   GNU General Public License for more details.
19
//
20
//   You should have received a copy of version 2.0 of the GNU General
21
//   Public License along with this program; if not, write to the Free
22
//   Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
23
//   MA 02110-1301, USA.
24
//
25
//
26
 
27
/*!
28
  \class EnhancedeZBinaryFileType enhancedezbinaryfiletype.php
29
  \ingroup eZDatatype
30
  \brief The class EnhancedeZBinaryFileType handles files and association with content objects with the collectedinformation function
31
 
32
*/
33
 
34
class EnhancedeZBinaryFileType extends eZDataType
35
{
36
    const MAX_FILESIZE_FIELD = 'data_int1';
37
    const MAX_FILESIZE_VARIABLE = '_enhancedezbinaryfile_max_filesize_';
38
    const DATA_TYPE_STRING = "enhancedezbinaryfile";
39 4 steven.bailey
 
40
    /*!
41
     Construction of the class, note that the second parameter in eZDataType
42
     is the actual name showed in the datatype dropdown list.
43
    */
44
    function __construct()
45
    {
46 5 steven.bailey
        parent::__construct( self::DATA_TYPE_STRING, ezpI18n::tr( 'extension/enhancedezbinaryfile/datatype', 'Enhanced File', 'Datatype name' ), array( 'serialize_supported' => true, 'object_serialize_map' => array( 'data_text' => 'filename' )));
47 4 steven.bailey
    }
48 1 steven.bailey
 
49
    function EnhancedeZBinaryFileType()
50
    {
51 5 steven.bailey
        $this->eZDataType( self::DATA_TYPE_STRING, ezpI18n::tr( 'kernel/classes/datatypes', "Enhanced File", 'Datatype name' ),
52 4 steven.bailey
                           array( 'serialize_supported' => true,'object_serialize_map' => array( 'data_text' => 'filename' )
53
                            ));
54 1 steven.bailey
    }
55
 
56
    /*!
57
     \return the binary file handler.
58
    */
59
    function fileHandler()
60
    {
61
        return eZBinaryFileHandler::instance();
62
    }
63
 
64
    /*!
65
     \reimp
66
     \return the template name which the handler decides upon.
67
    */
68
    function viewTemplate( $contentobjectAttribute )
69
    {
70
        $handler = $this->fileHandler();
71
        $handlerTemplate = $handler->viewTemplate( $contentobjectAttribute );
72
        $template = $this->DataTypeString;
73
        if ( $handlerTemplate !== false )
74
            $template .= '_' . $handlerTemplate;
75
        return $template;
76
    }
77
 
78
    /*!
79
     \return the template name to use for editing the attribute.
80
     \note Default is to return the datatype string which is OK
81
           for most datatypes, if you want dynamic templates
82
           reimplement this function and return a template name.
83
     \note The returned template name does not include the .tpl extension.
84
     \sa viewTemplate, informationTemplate
85
    */
86
    function editTemplate( $contentobjectAttribute )
87
    {
88
        $handler = $this->fileHandler();
89
        $handlerTemplate = $handler->editTemplate( $contentobjectAttribute );
90
        $template = $this->DataTypeString;
91
        if ( $handlerTemplate !== false )
92
            $template .= '_' . $handlerTemplate;
93
        return $template;
94
    }
95
 
96
    /*!
97
     \return the template name to use for information collection for the attribute.
98
     \note Default is to return the datatype string which is OK
99
           for most datatypes, if you want dynamic templates
100
           reimplement this function and return a template name.
101
     \note The returned template name does not include the .tpl extension.
102
     \sa viewTemplate, editTemplate
103
    */
104
 
105
    function informationTemplate( $contentobjectAttribute )
106
    {
107
        $handler = $this->fileHandler();
108
        $handlerTemplate = $handler->informationTemplate( $contentobjectAttribute );
109
        $template = $this->DataTypeString;
110
        if ( $handlerTemplate !== false )
111
            $template .= '_' . $handlerTemplate;
112
        return $template;
113
    }
114
 
115
    /*!
116
     Sets value according to current version
117
    */
118
    function initializeObjectAttribute( $contentObjectAttribute, $currentVersion, $originalContentObjectAttribute )
119
    {
120
        if ( $currentVersion != false )
121
        {
122
            $contentObjectAttributeID = $originalContentObjectAttribute->attribute( "id" );
123
            $version = $contentObjectAttribute->attribute( "version" );
124
            $oldfile = eZBinaryFile::fetch( $contentObjectAttributeID, $currentVersion );
125
            if ( $oldfile != null )
126
            {
127
                $oldfile->setAttribute( 'contentobject_attribute_id', $contentObjectAttribute->attribute( 'id' ) );
128
                $oldfile->setAttribute( "version",  $version );
129
                $oldfile->store();
130
            }
131
        }
132
    }
133
 
134
    /*!
135
     Delete stored attribute
136
    */
137
    function deleteStoredObjectAttribute( $contentObjectAttribute, $version = null )
138
    {
139
    /* This is called when you delete the datatype from the class*/
140
        $contentObjectAttributeID = $contentObjectAttribute->attribute( "id" );
141
        $sys = eZSys::instance();
142
        $storage_dir = $sys->storageDirectory();
143
 
144
        require_once( 'kernel/classes/ezclusterfilehandler.php' );
145
        if ( $version == null )
146
        {
147
            $binaryFiles = eZBinaryFile::fetch( $contentObjectAttributeID );
148
            eZBinaryFile::removeByID( $contentObjectAttributeID, null );
149
 
150
            foreach ( $binaryFiles as  $binaryFile )
151
            {
152
                $mimeType =  $binaryFile->attribute( "mime_type" );
153
                list( $prefix, $suffix ) = split ('[/]', $mimeType );
154
                $orig_dir = $storage_dir . '/'.$downloadPath.'/' . $prefix;
155
                $fileName = $binaryFile->attribute( "filename" );
156
 
157
                // Check if there are any other records in ezbinaryfile that point to that fileName.
158
                $binaryObjectsWithSameFileName = eZBinaryFile::fetchByFileName( $fileName );
159
 
160
                $filePath = $orig_dir . "/" . $fileName;
161
                $file = eZClusterFileHandler::instance( $filePath );
162
 
163
                if ( $file->exists() and count( $binaryObjectsWithSameFileName ) < 1 )
164
                    $file->delete();
165
            }
166
        }
167
        else
168
        {
169
            $count = 0;
170
            $binaryFile = eZBinaryFile::fetch( $contentObjectAttributeID, $version );
171
            if ( $binaryFile != null )
172
            {
173
                $mimeType =  $binaryFile->attribute( "mime_type" );
174
                list( $prefix, $suffix ) = split ('[/]', $mimeType );
175
                $orig_dir = $storage_dir . "/original/" . $prefix;
176
                $fileName = $binaryFile->attribute( "filename" );
177
 
178
                eZBinaryFile::removeByID( $contentObjectAttributeID, $version );
179
 
180
                // Check if there are any other records in ezbinaryfile that point to that fileName.
181
                $binaryObjectsWithSameFileName = eZBinaryFile::fetchByFileName( $fileName );
182
 
183
                $filePath = $orig_dir . "/" . $fileName;
184
                $file = eZClusterFileHandler::instance( $filePath );
185
 
186
                if ( $file->exists() and count( $binaryObjectsWithSameFileName ) < 1 )
187
                    $file->delete();
188
            }
189
        }
190
    }
191
 
192
    /*!
193
     Checks if file uploads are enabled, if not it gives a warning.
194
    */
195
    function checkFileUploads()
196
    {
197
        $isFileUploadsEnabled = ini_get( 'file_uploads' ) != 0;
198
        if ( !$isFileUploadsEnabled )
199
        {
200
            $isFileWarningAdded = $GLOBALS['eZBinaryFileTypeWarningAdded'];
201
            if ( !isset( $isFileWarningAdded ) or
202
                 !$isFileWarningAdded )
203
            {
204
                eZAppendWarningItem( array( 'error' => array( 'type' => 'kernel',
205
                                                              'number' => eZError::KERNEL_NOT_AVAILABLE ),
206 5 steven.bailey
                                            'text' => ezpI18n::tr( 'kernel/classes/datatypes',
207 1 steven.bailey
                                                              'File uploading is not enabled. Please contact the site administrator to enable it.' ) ) );
208
                $GLOBALS['eZBinaryFileTypeWarningAdded'] = true;
209
            }
210
        }
211
    }
212
 
213
 
214
    /*!
215
     Fetches the http post var integer input and stores it in the data instance.
216
    */
217
    function fetchObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
218
    {
219
    /*gets hit the first time through*/
220
        EnhancedeZBinaryFileType::checkFileUploads();
221
        if ( !EnhancedeZBinaryFileType::canFetch( $base . "_data_enhancedbinaryfilename_" . $contentObjectAttribute->attribute( "id" ) ) )
222
            return false;
223
 
224
        $binaryFile = eZHTTPFile::fetch( $base . "_data_enhancedbinaryfilename_" . $contentObjectAttribute->attribute( "id" ) );
225
 
226
        $contentObjectAttribute->setContent( $binaryFile );
227
 
228
        if ( $binaryFile instanceof eZHTTPFile )
229
        {
230
            $contentObjectAttributeID = $contentObjectAttribute->attribute( "id" );
231
            $version = $contentObjectAttribute->attribute( "version" );
232
 
233
            /*
234
            $mimeObj = new  eZMimeType();
235
            $mimeData = $mimeObj->findByURL( $binaryFile->attribute( "original_filename" ), true );
236
            $mime = $mimeData['name'];
237
            */
238
 
239
            $mimeData = eZMimeType::findByFileContents( $binaryFile->attribute( "original_filename" ) );
240
            $mime = $mimeData['name'];
241
 
242
            if ( $mime == '' )
243
            {
244
                $mime = $binaryFile->attribute( "mime_type" );
245
            }
246
 
247
            $extension = eZFile::suffix( $binaryFile->attribute( "original_filename" ) );
248
            $binaryFile->setMimeType( $mime );
249
            if ( !$binaryFile->store( "original", $extension ) )
250
            {
251
                eZDebug::writeError( "Failed to store http-file: " . $binaryFile->attribute( "original_filename" ),
252
                                     "EnhancedeZBinaryFileType" );
253
                return false;
254
            }
255
 
256
            $binary = eZBinaryFile::fetch( $contentObjectAttributeID, $version );
257
            if ( $binary === null )
258
                $binary = eZBinaryFile::create( $contentObjectAttributeID, $version );
259
 
260
            $orig_dir = $binaryFile->storageDir( "original" );
261
 
262
            $binary->setAttribute( "contentobject_attribute_id", $contentObjectAttributeID );
263
            $binary->setAttribute( "version", $version );
264
            $binary->setAttribute( "filename", basename( $binaryFile->attribute( "filename" ) ) );
265
            $binary->setAttribute( "original_filename", $binaryFile->attribute( "original_filename" ) );
266
            $binary->setAttribute( "mime_type", $mime );
267
 
268
            $binary->store();
269
 
270
            // VS-DBFILE
271
 
272
            require_once( 'kernel/classes/ezclusterfilehandler.php' );
273
            $filePath = $binaryFile->attribute( 'filename' );
274
            $fileHandler = eZClusterFileHandler::instance();
275
            $fileHandler->fileStore( $filePath, 'binaryfile', true, $mime );
276
 
277
            $contentObjectAttribute->setContent( $binary );
278
        }
279
        return true;
280
    }
281
 
282
    /*!
283
     Does nothing, since the file has been stored. See fetchObjectAttributeHTTPInput for the actual storing.
284
    */
285
    function storeObjectAttribute( $contentObjectAttribute )
286
    {
287
    }
288
 
289
    function customObjectAttributeHTTPAction( $http, $action, $contentObjectAttribute, $parameters )
290
    {
291
        EnhancedeZBinaryFileType::checkFileUploads();
292
        if( $action == "delete_binary" )
293
        {
294
            $contentObjectAttributeID = $contentObjectAttribute->attribute( "id" );
295
            $version = $contentObjectAttribute->attribute( "version" );
296
            $this->deleteStoredObjectAttribute( $contentObjectAttribute, $version );
297
        }
298
    }
299
 
300
    /*!
301
     \reimp
302
     HTTP file insertion is supported.
303
    */
304
    function isHTTPFileInsertionSupported()
305
    {
306
        return true;
307
    }
308
 
309
    /*!
310
     \reimp
311
     HTTP file insertion is supported.
312
    */
313
    function isRegularFileInsertionSupported()
314
    {
315
        return true;
316
    }
317
 
318
    function fetchClassAttributeHTTPInput( $http, $base, $classAttribute )
319
    {
320
        $filesizeName = $base . self::MAX_FILESIZE_VARIABLE . $classAttribute->attribute( 'id' );
321
        if ( $http->hasPostVariable( $filesizeName ) )
322
        {
323
            $filesizeValue = $http->postVariable( $filesizeName );
324
            $classAttribute->setAttribute( self::MAX_FILESIZE_FIELD, $filesizeValue );
325
        }
326
    }
327
 
328
    /*!
329
     Returns the object title.
330
    */
331
    function title( $contentObjectAttribute,  $name = "original_filename" )
332
    {
333
        $value = false;
334
        $binaryFile = eZBinaryFile::fetch( $contentObjectAttribute->attribute( 'id' ),
335
                                           $contentObjectAttribute->attribute( 'version' ) );
336
        if ( is_object( $binaryFile ) )
337
            $value = $binaryFile->attribute( $name );
338
 
339
        return $value;
340
    }
341
 
342
    function hasObjectAttributeContent( $contentObjectAttribute )
343
    {
344
    /* Gets hit the first time through */
345
        $binaryFile = eZBinaryFile::fetch( $contentObjectAttribute->attribute( "id" ),
346
                                            $contentObjectAttribute->attribute( "version" ) );
347
        if ( !$binaryFile )
348
            return false;
349
        return true;
350
    }
351
 
352
    function objectAttributeContent( $contentObjectAttribute )
353
    {
354
        $binaryFile = eZBinaryFile::fetch( $contentObjectAttribute->attribute( "id" ), $contentObjectAttribute->attribute( "version" ) );
355
        if ( !$binaryFile )
356
        {
357
            $attrValue = false;
358
            return $attrValue;
359
        }
360
        return $binaryFile;
361
    }
362
 
363
    /*!
364
     \reimp
365
    */
366
    function isIndexable()
367
    {
368
        return true;
369
    }
370
 
371
    /*!
372
     \reimp
373
    */
374
    function isInformationCollector()
375
    {
376
        return true;
377
    }
378
 
379
    /*!
380
     Fetches the http post var integer input and stores it in the data instance.
381
    */
382
    function fetchCollectionAttributeHTTPInput( $collection, $collectionAttribute, $http, $base, $contentObjectAttribute )
383
    {
384
        EnhancedeZBinaryFileType::checkFileUploads();
385
        if ( eZHTTPFile::canFetch( $base . "_data_enhancedbinaryfilename_" . $contentObjectAttribute->attribute( "id" ) ) != eZHTTPFile::UPLOADEDFILE_OK ) {
386
            return false;
387
        }
388
        //Check allowed file type - must do it here,again - otherwise an illegal
389
        //file will still be created in the storage directory
390
        $binaryFile = eZHTTPFile::fetch( $base . "_data_enhancedbinaryfilename_" . $contentObjectAttribute->attribute( "id" ) );
391
        if (!$binaryFile) return eZInputValidator::STATE_INVALID;
392
 
393
        $moduleINI = eZINI::instance( 'module.ini.append.php', 'settings');
394
        $allowed = $moduleINI->variable('AllowedFileTypes', 'AllowedFileTypeList');
395
 
396
        // $binaryFile->attribute( 'mime_type_part' ) not always the extension
397
        $extension = preg_replace('/.*\.(.+?)$/', '\\1', $binaryFile->attribute( "original_filename" ) );
398
        if (!in_array(strtolower($extension),$allowed))
399
        {
400 5 steven.bailey
                $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes','Failed to store file. Only the following file types are allowed: %1.' ), implode(", ",$allowed) );
401 1 steven.bailey
                return eZInputValidator::STATE_INVALID;
402
        }
403
 
404
        //$contentObjectAttribute->setContent( $binaryFile );
405
 
406
        if ( $binaryFile instanceof eZHTTPFile )
407
        {
408
                //clean up older files.
409
                $moduleINI = eZINI::instance( 'module.ini.append.php', 'settings');
410
                $maxFiles=$moduleINI->variable('RemoveFiles', 'MaxFiles');
411
                $downloadPath=$moduleINI->variable('RemoveFiles', 'DownloadPath');
412
                $downloadPath=trim($downloadPath,"/");
413
                if (!$downloadPath) $downloadPath='original/collected';
414
 
415
                if ( $maxFiles>0 )
416
                {
417
                        $Files = array();
418
                        $storageDir=eZSys::storageDirectory();
419
                        $fileCollection=eZDir::recursiveFindRelative( $storageDir, $downloadPath, '.*' );
420
                        if ( count($fileCollection)>=$maxFiles )
421
                        {
422
                                foreach ( $fileCollection as $fileItem )
423
                                {
424
                                        $lastModified = filemtime( $storageDir .'/'. $fileItem);
425
                                        $Files[$fileItem] = filemtime($storageDir .'/'. $fileItem);
426
                                }
427
                                asort($Files, SORT_NUMERIC);
428
                                while (count($Files)>=$maxFiles){
429
                                        $removeFile=key($Files);
430
                                        if ( file_exists( $storageDir .'/'. $removeFile ) )
431
                                        {
432
                                                if (!unlink( $storageDir .'/'. $removeFile ) )
433
                                                {
434
                                                        eZDebug::writeError( "Failed to delete file: " . $storageDir .'/'. $removeFile, "EnhancedeZBinaryFileType" );
435
                                                        return false;
436
                                                }
437
                                        }
438
                                        array_shift($Files);
439
                                }
440
                        }
441
                }
442
                //end cleanup
443
 
444
           // $contentObjectAttributeID = $contentObjectAttribute->attribute( "id" );
445
            //$version = $contentObjectAttribute->attribute( "version" );
446
 
447
            $mimeData = eZMimeType::findByFileContents( $binaryFile->attribute( "original_filename" ) );  //Nice name but it still uses the extension to set the mimetype and therefore can be bogus
448
            $mime = $mimeData['name'];
449
 
450
            if ( $mime == '' )
451
            {
452
                $mime = $binaryFile->attribute( "mime_type" );
453
            }
454
            $extension = eZFile::suffix( $binaryFile->attribute( "original_filename" ) );
455
            $binaryFile->setMimeType( $mime );
456
            if ( !$binaryFile->store( $downloadPath, $extension ) )
457
            {
458
                eZDebug::writeError( "Failed to store http-file: " . $binaryFile->attribute( "original_filename" ),
459
                                     "EnhancedeZBinaryFileType" );
460
                return false;
461
            }
462
 
463
        //Adds xmltext to collection attribute with file info to data_text attribute
464 3 steven.bailey
        $doc = new DOMDocument( '1.0', 'utf-8' );
465
        $root = $doc->createElement( 'binaryfile-info' );
466
        $binaryFileList = $doc->createElement( 'binaryfile-attributes' );
467 1 steven.bailey
        foreach ( $binaryFile as $key => $binaryFileItem )
468
        {
469 3 steven.bailey
                $binaryFileElement = $doc->createElement(  $key, $binaryFileItem );
470
                $binaryFileList->appendChild( $binaryFileElement );
471 1 steven.bailey
        }
472
        $root->appendChild( $binaryFileList );
473 3 steven.bailey
        $doc->appendChild( $root );
474 1 steven.bailey
        $docText = EnhancedeZBinaryFileType::domString( $doc );
475
        $collectionAttribute->setAttribute( 'data_text', $docText );
476
        }
477
        return true;
478
    }
479
 
480
    /*!
481
     Validates the input and returns true if the input was
482
     valid for this datatype.
483
    */
484
    function validateCollectionAttributeHTTPInput( $http, $base, $contentObjectAttribute )
485
    {
486
        //validateCollection goes first, then the fetchCollection
487
        /*WITH THE ENCTYPE OF MULTIPART THE $_POST FOR A FILE IS EMPTY so can't use haspostvariable */
488
 
489
        $binaryFile = eZHTTPFile::fetch( $base . "_data_enhancedbinaryfilename_" . $contentObjectAttribute->attribute( "id" ) );
490
        $classAttribute = $contentObjectAttribute->contentClassAttribute();
491
        //This is only checking if it is required or not
492
        if ( !$binaryFile )
493
        {
494
                if ( $contentObjectAttribute->validateIsRequired() )
495
                {
496 5 steven.bailey
                        $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes','Input required.' ) );
497 1 steven.bailey
                        return eZInputValidator::STATE_INVALID;
498
                }
499
                else
500
                        return eZInputValidator::STATE_ACCEPTED;
501
        }
502
        else {
503
                return $this->validateFileHTTPInput( $base, $contentObjectAttribute, $classAttribute );
504
        }
505
    }
506
 
507
    /*
508
     Private method, only for using inside this class.
509
    */
510
 
511
    function validateFileHTTPInput( $base, $contentObjectAttribute, $classAttribute )
512
    {
513
        //Check allowed file type
514
        //Have to do it here again, otherwise no error message
515
        $binaryFile = eZHTTPFile::fetch( $base . "_data_enhancedbinaryfilename_" . $contentObjectAttribute->attribute( "id" ) );
516
        if (!$binaryFile) return eZInputValidator::STATE_INVALID;
517
 
518
        $moduleINI = eZINI::instance( 'module.ini.append.php', 'settings');
519
        $allowed = $moduleINI->variable('AllowedFileTypes', 'AllowedFileTypeList');
520
 
521
        // $binaryFile->attribute( 'mime_type_part' ) not always the extension
522
        $extension = preg_replace('/.*\.(.+?)$/', '\\1', $binaryFile->attribute( "original_filename" ) );
523
        if (!in_array(strtolower($extension),$allowed))
524
        {
525 5 steven.bailey
                $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes','Failed to store file. Only the following file types are allowed: %1.' ), implode(", ",$allowed) );
526 1 steven.bailey
                return eZInputValidator::STATE_INVALID;
527
        }
528
 
529
        //Check size
530
        $mustUpload = false;
531
        $maxSize = 1024 * 1024 * $classAttribute->attribute( self::MAX_FILESIZE_FIELD );
532
 
533
/* Since it is not an ezbinary file this can never be true
534
   unfortunately, this is where the check would be to not upload the file
535
   multiple times in the event the form fails somewhere.  Unfortunately it
536
   can't be a binary file since it is a collection object and not a content
537
   object.
538
        if ( $contentObjectAttribute->validateIsRequired() )
539
        {
540
            $contentObjectAttributeID = $contentObjectAttribute->attribute( "id" );
541
            $version = $contentObjectAttribute->attribute( "version" );
542
            $binary = eZBinaryFile::fetch( $contentObjectAttributeID, $version );
543
            if ( $binary === null )
544
            {
545
                $mustUpload = true;
546
            }
547
        }
548
*/
549
        $canFetchResult = EnhancedeZBinaryFileType::canFetch( $base . "_data_enhancedbinaryfilename_" . $contentObjectAttribute->attribute( "id" ), $maxSize );
550
        //$binaryfile doesn't have an attribute(http_name)
551
        if ( $mustUpload && $canFetchResult === eZHTTPFile::UPLOADEDFILE_DOES_NOT_EXIST )
552
        {
553 5 steven.bailey
            $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes', 'A valid file is required.' ) );
554 1 steven.bailey
            return eZInputValidator::STATE_INVALID;
555
        }
556
        if ( $canFetchResult == eZHTTPFile::UPLOADEDFILE_EXCEEDS_PHP_LIMIT )
557
        {
558 5 steven.bailey
            $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes', 'The size of the uploaded file exceeds the limit set by the upload_max_filesize directive in php.ini.' ) );
559 1 steven.bailey
            return eZInputValidator::STATE_INVALID;
560
        }
561
        if ( $canFetchResult == eZHTTPFile::UPLOADEDFILE_EXCEEDS_MAX_SIZE )
562
        {
563 5 steven.bailey
            $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes', 'The size of the uploaded file exceeds the maximum upload size: %1 bytes.' ), $maxSize );
564 1 steven.bailey
            return eZInputValidator::STATE_INVALID;
565
        }
566
        //Dropped all the way through with no error
567
        return eZInputValidator::STATE_ACCEPTED;
568
    }
569
    /*!
570
     \return true if the HTTP file $http_name can be fetched. If $maxSize is given,
571
     the function returns
572
 
573
       -1 (eZHTTPFile::UPLOADEDFILE_DOES_NOT_EXIST) if there has been no file uploaded,
574
       -2 (eZHTTPFile::UPLOADEDFILE_EXCEEDS_PHP_LIMIT) if the file was uploaded but size
575
          exceeds the upload_max_size limit (set in the PHP configuration),
576
       -3 (eZHTTPFile::UPLOADEDFILE_EXCEEDS_MAX_SIZE) if the file was uploaded but size
577
          exceeds $maxSize or MAX_FILE_SIZE variable in the form.
578
    */
579 3 steven.bailey
    function canFetch( $http_name, $maxSize = false )
580 1 steven.bailey
    {
581
       if ( isset( $GLOBALS["eZHTTPFile-$http_name"] ) AND
582
           $GLOBALS["eZHTTPFile-$http_name"] instanceof eZHTTPFile  )
583
        {
584
        //No idea why it's the opposite from ezHTTPFile::canfetch
585
            if ( $maxSize === false )
586
            {
587
                return isset( $_FILES[$http_name] ) and $_FILES[$http_name]['name'] != "" and $_FILES[$http_name]['error'] == 0;
588
            }
589
 
590
            if ( isset( $_FILES[$http_name] ) and $_FILES[$http_name]['name'] != "" )
591
            {
592
                switch ( $_FILES[$http_name]['error'] )
593
                {
594
                    case ( UPLOAD_ERR_NO_FILE ):
595
                    {
596
                        return eZHTTPFile::UPLOADEDFILE_DOES_NOT_EXIST;
597
                    }break;
598
 
599
                    case ( UPLOAD_ERR_INI_SIZE ):
600
                    {
601
                        return eZHTTPFile::UPLOADEDFILE_EXCEEDS_PHP_LIMIT;
602
                    }break;
603
 
604
                    case ( UPLOAD_ERR_FORM_SIZE ):
605
                    {
606
                        return eZHTTPFile::UPLOADEDFILE_EXCEEDS_MAX_SIZE;
607
                    }break;
608
 
609
                    default:
610
                    {
611
                        return ( $maxSize == 0 || $_FILES[$http_name]['size'] <= $maxSize )? eZHTTPFile::UPLOADEDFILE_OK:
612
                        eZHTTPFile::UPLOADEDFILE_EXCEEDS_MAX_SIZE;
613
                    }
614
                }
615
            }
616
            else
617
            {
618
                return eZHTTPFile::UPLOADEDFILE_DOES_NOT_EXIST;
619
            }
620
        }
621
        if ( $maxSize === false )
622
            return eZHTTPFile::UPLOADEDFILE_OK;
623
        else
624
            return true;
625
    }
626
 
627
    /*!
628
     \return the XML structure in \a $domDocument as text.
629
             It will take of care of the necessary charset conversions
630
             for content storage.
631
    */
632
    function domString( $domDocument )
633
    {
634
        $ini = eZINI::instance();
635
        $xmlCharset = $ini->variable( 'RegionalSettings', 'ContentXMLCharset' );
636
        if ( $xmlCharset == 'enabled' )
637
        {
638
            $charset = eZTextCodec::internalCharset();
639
        }
640
        else if ( $xmlCharset == 'disabled' )
641
            $charset = true;
642
        else
643
            $charset = $xmlCharset;
644
        if ( $charset !== true )
645
        {
646
            $charset = eZCharsetInfo::realCharsetCode( $charset );
647
        }
648 3 steven.bailey
        $domString = $domDocument->saveXML();
649 1 steven.bailey
        return $domString;
650
    }
651
 
652
    function metaData( $contentObjectAttribute )
653
    {
654
        $binaryFile = $contentObjectAttribute->content();
655
 
656
        $metaData = "";
657
        if ( $binaryFile instanceof eZBinaryFile )
658
        {
659
            $metaData = $binaryFile->metaData();
660
        }
661
        return $metaData;
662
    }
663
 
664
    /*!
665
     \reimp
666
    */
667
    function serializeContentClassAttribute( $classAttribute, $attributeNode, $attributeParametersNode )
668
    {
669
        $dom = $attributeParametersNode->ownerDocument;
670
        $maxSize = $classAttribute->attribute( self::MAX_FILESIZE_FIELD );
671
        $maxSizeNode = $dom->createElement( 'max-size', $maxSize );
672
        $maxSizeNode->setAttribute( 'unit-size', 'mega' );
673
        $attributeParametersNode->appendChild( $maxSizeNode );
674
    }
675
 
676
    /*!
677
     \reimp
678
    */
679
    function unserializeContentClassAttribute( $classAttribute, $attributeNode, $attributeParametersNode )
680
    {
681
        $sizeNode = $attributeParametersNode->getElementsByTagName( 'max-size' )->item( 0 );
682
        $maxSize = $sizeNode->textContent;
683
        $unitSize = $sizeNode->getAttribute( 'unit-size' );
684
        $classAttribute->setAttribute( self::MAX_FILESIZE_FIELD, $maxSize );
685
    }
686
 
687
    /*!
688
     \return string representation of an contentobjectattribute data for simplified export
689
 
690
    */
691
    function toString( $objectAttribute )
692
    {
693
        $binaryFile = $objectAttribute->content();
694
 
695
        if ( is_object( $binaryFile ) )
696
        {
697
            return implode( '|', array( $binaryFile->attribute( 'filepath' ), $binaryFile->attribute( 'original_filename' ) ) );
698
        }
699
        else
700
            return '';
701
    }
702
 
703
    function fromString( $objectAttribute, $string )
704
    {
705
        if( !$string )
706
            return true;
707
 
708
        $result = array();
709
        return $this->insertRegularFile( $objectAttribute->attribute( 'object' ),
710
                                         $objectAttribute->attribute( 'version' ),
711
                                         $objectAttribute->attribute( 'language_code' ),
712
                                         $objectAttribute,
713
                                         $string,
714
                                         $result );
715
    }
716
 
717
    /*!
718
     \param package
719
     \param content attribute
720
 
721
     \return a DOM representation of the content object attribute
722
    */
723
    function serializeContentObjectAttribute( $package, $objectAttribute )
724
    {
725
        $node = $this->createContentObjectAttributeDOMNode( $objectAttribute );
726
 
727
        $binaryFile = $objectAttribute->attribute( 'content' );
728
        if ( is_object( $binaryFile ) )
729
        {
730
            $fileKey = md5( mt_rand() );
731
            $package->appendSimpleFile( $fileKey, $binaryFile->attribute( 'filepath' ) );
732
 
733
            $dom = $node->ownerDocument;
734
            $fileNode = $dom->createElement( 'binary-file' );
735
            $fileNode->setAttribute( 'filesize', $binaryFile->attribute( 'filesize' ) );
736
            $fileNode->setAttribute( 'filename', $binaryFile->attribute( 'filename' ) );
737
            $fileNode->setAttribute( 'original-filename', $binaryFile->attribute( 'original_filename' ) );
738
            $fileNode->setAttribute( 'mime-type', $binaryFile->attribute( 'mime_type' ) );
739
            $fileNode->setAttribute( 'filekey', $fileKey );
740
            $node->appendChild( $fileNode );
741
        }
742
 
743
        return $node;
744
    }
745
 
746
    /*!
747
     \reimp
748
     \param package
749
     \param contentobject attribute object
750
     \param domnode object
751
    */
752
    function unserializeContentObjectAttribute( $package, $objectAttribute, $attributeNode )
753
    {
754
        $fileNode = $attributeNode->getElementsByTagName( 'binary-file' )->item( 0 );
755
        if ( !is_object( $fileNode ) or !$fileNode->hasAttributes() )
756
        {
757
            return;
758
        }
759
 
760
        $binaryFile = eZBinaryFile::create( $objectAttribute->attribute( 'id' ), $objectAttribute->attribute( 'version' ) );
761
 
762
        $sourcePath = $package->simpleFilePath( $fileNode->getAttribute( 'filekey' ) );
763
 
764
        if ( !file_exists( $sourcePath ) )
765
        {
766
            eZDebug::writeError( "The file '$sourcePath' does not exist, cannot initialize file attribute with it",
767
                                 'EnhancedeZBinaryFileType::unserializeContentObjectAttribute' );
768
            return false;
769
        }
770
 
771
        //include_once( 'lib/ezfile/classes/ezdir.php' );
772
        $ini = eZINI::instance();
773
        $mimeType = $fileNode->getAttribute( 'mime-type' );
774
        list( $mimeTypeCategory, $mimeTypeName ) = explode( '/', $mimeType );
775
        $destinationPath = eZSys::storageDirectory() . '/original/' . $mimeTypeCategory . '/';
776
        if ( !file_exists( $destinationPath ) )
777
        {
778
            $oldumask = umask( 0 );
779
            if ( !eZDir::mkdir( $destinationPath, eZDir::directoryPermission(), true ) )
780
            {
781
                umask( $oldumask );
782
                return false;
783
            }
784
            umask( $oldumask );
785
        }
786
 
787
        $basename = basename( $fileNode->getAttribute( 'filename' ) );
788
        while ( file_exists( $destinationPath . $basename ) )
789
        {
790
            $basename = substr( md5( mt_rand() ), 0, 8 ) . '.' . eZFile::suffix( $fileNode->getAttribute( 'filename' ) );
791
        }
792
 
793
        //include_once( 'lib/ezfile/classes/ezfilehandler.php' );
794
        eZFileHandler::copy( $sourcePath, $destinationPath . $basename );
795
        eZDebug::writeNotice( 'Copied: ' . $sourcePath . ' to: ' . $destinationPath . $basename,
796
                              'EnhancedeZBinaryFileType::unserializeContentObjectAttribute()' );
797
 
798
        $binaryFile->setAttribute( 'contentobject_attribute_id', $objectAttribute->attribute( 'id' ) );
799
        $binaryFile->setAttribute( 'filename', $basename );
800
        $binaryFile->setAttribute( 'original_filename', $fileNode->getAttribute( 'original-filename' ) );
801
        $binaryFile->setAttribute( 'mime_type', $fileNode->getAttribute( 'mime-type' ) );
802
 
803
        $binaryFile->store();
804
 
805
        // VS-DBFILE + SP DBFile fix
806
 
807
        require_once( 'kernel/classes/ezclusterfilehandler.php' );
808
        $fileHandler = eZClusterFileHandler::instance();
809
        $fileHandler->fileStore( $destinationPath . $basename, 'binaryfile', true );
810
    }
811
 
812
}
813
 
814
eZDataType::register( EnhancedeZBinaryFileType::DATA_TYPE_STRING, "enhancedezbinaryfiletype" );
815
 
816
?>