Subversion Repositories enhancedezbinaryfile

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

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