digitalResource.php 26 KB
Newer Older
Prosper De Laure's avatar
Prosper De Laure committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php

/*
 * Copyright (C) 2015 Maarch
 *
 * This file is part of bundle digitalResource.
 *
 * Bundle digitalResource is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Bundle digitalResource is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with bundle digitalResource.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace bundle\digitalResource\Controller;

/**
 * Main digital resource controller
 */
class digitalResource
{

    protected $finfo;
    protected $sdoFactory;
    public $hashAlgorithm;

    /**
     * Cluster controller
     * @var digitalResource/Controller/format
     */
    protected $formatController;

    /**
     * Cluster controller
     * @var digitalResource/cluster
     */
    protected $clusterController;

    /**
     * Previously loaded digital resource clusters
     * @var array
     */
    protected $clusters;

    /**
     * Currently used ddigital resource cluster
     * @var digitalResource/cluster
     */
    protected $currentCluster;

    /**
     * Constructor
     * @param \dependency\sdo\Factory $sdoFactory    The dependency sdo factory
     * @param string                  $hashAlgorithm The hash algorithm as in php::hash_algos()
     */
    public function __construct(\dependency\sdo\Factory $sdoFactory, $hashAlgorithm = "sha256")
    {
        $this->hashAlgorithm = $hashAlgorithm;

        $this->finfo = new \finfo(FILEINFO_MIME_TYPE);

        $this->sdoFactory = $sdoFactory;

        $this->clusterController = \laabs::newController('digitalResource/cluster');

        $this->formatController = \laabs::newController('digitalResource/format');
74
75

        $this->clusters = [];
Prosper De Laure's avatar
Prosper De Laure committed
76
77
78
79
80
81
    }

    /**
     * Get file information about one file
     * @param string $filename The file name
     *
Dylan's avatar
Dylan committed
82
     * @return digitalResource/digitalResource The digitalResource
Prosper De Laure's avatar
Prosper De Laure committed
83
     */
Alexis Ragot's avatar
Alexis Ragot committed
84
    public function createFromFile($filename, $withDateTime = true)
Prosper De Laure's avatar
Prosper De Laure committed
85
86
87
88
89
90
91
    {
        if (!file_exists($filename)) {
            return false;
        }

        $resource = $this->newResource();

92
93
94
95
        $UTF8filename = $filename;
        if (!preg_match('//u', $filename)) {
            $UTF8filename = utf8_encode($filename);
        }
Alexandre Morin's avatar
Alexandre Morin committed
96

Prosper De Laure's avatar
Prosper De Laure committed
97
        // Basic path information
98
        $pathinfo = pathinfo($UTF8filename);
Alexis Ragot's avatar
Alexis Ragot committed
99
100
101
102
103
104
105

        $resource->fileName = $pathinfo['filename'];

        if ($withDateTime) {
            $resource->fileName .= "_".(string) \laabs::newDate(\laabs::newDatetime(null, "UTC"), "Y-m-d_H:i:s");
        }

Prosper De Laure's avatar
Prosper De Laure committed
106
        if (isset($pathinfo['extension'])) {
107
            $resource->fileName .= "." . $pathinfo['extension'];
Prosper De Laure's avatar
Prosper De Laure committed
108
109
110
111
112
113
            $resource->fileExtension = $pathinfo['extension'];
        }

        $resource->size = filesize($filename);
        $resource->mimetype = $this->finfo->file($filename, \FILEINFO_MIME_TYPE);

Cyril Vazquez's avatar
Cyril Vazquez committed
114
        $resource->setFilename($filename);
Prosper De Laure's avatar
Prosper De Laure committed
115
116
117
118
119
120
121
122
123

        return $resource;
    }

    /**
     * Get information about resource contents
     * @param string $contents The contents to store
     * @param string $filename The original filename
     *
Dylan's avatar
Dylan committed
124
     * @return digitalResource/digitalResource The digitalResource
Prosper De Laure's avatar
Prosper De Laure committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
     */
    public function createFromContents($contents, $filename = false)
    {
        $resource = $this->newResource();

        // Basic path information
        $resource->size = strlen($contents);
        $resource->mimetype = $this->finfo->buffer($contents, \FILEINFO_MIME_TYPE);

        if ($filename) {
            $pathinfo = pathinfo($filename);
            $resource->fileName = $pathinfo['basename'];
            if (isset($pathinfo['extension'])) {
                $resource->fileExtension = $pathinfo['extension'];
            }
        }

Cyril Vazquez's avatar
Cyril Vazquez committed
142
143
144
145
146
        $tmpfile = \laabs\tempnam();
        file_put_contents($tmpfile, $contents);
        $handler = fopen($tmpfile, 'r+');

        $resource->sethandler($handler, $isTemp = true);
Prosper De Laure's avatar
Prosper De Laure committed
147
148
149
150
151
152

        return $resource;
    }

    /**
     * Get information about resource stream contents
153
154
     * @param string $stream   The data stream to store
     * @param string $filename The original filename
Prosper De Laure's avatar
Prosper De Laure committed
155
     *
Dylan's avatar
Dylan committed
156
     * @return digitalResource/digitalResource The digitalResource
Prosper De Laure's avatar
Prosper De Laure committed
157
     */
158
    public function createFromStream($stream, $filename = null)
Prosper De Laure's avatar
Prosper De Laure committed
159
    {
Cyril Vazquez's avatar
Cyril Vazquez committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
        $resource = $this->newResource();

        $resource->setHandler($stream);

        $this->getHash($resource);
        $this->getMimetype($resource);
        $this->getSize($resource);

        if ($filename) {
            $pathinfo = pathinfo($filename);
            $resource->fileName = $pathinfo['basename'];
            if (isset($pathinfo['extension'])) {
                $resource->fileExtension = $pathinfo['extension'];
            }
        }
Prosper De Laure's avatar
Prosper De Laure committed
175

Cyril Vazquez's avatar
Cyril Vazquez committed
176
        return $resource;
Prosper De Laure's avatar
Prosper De Laure committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    }

    protected function newResource()
    {
        $resource = \laabs::newInstance("digitalResource/digitalResource");

        $resource->resId = \laabs::newId();

        $resource->created = \laabs::newTimestamp();

        return $resource;
    }


    /**
     * Get the hash for a given resource
     * @param digitalResource/digitalResource $resource      The resource
     * @param string                          $hashAlgorithm The hash algorithm to use
     */
    public function getHash($resource, $hashAlgorithm = false)
    {
        if (!$hashAlgorithm) {
            $hashAlgorithm = $this->hashAlgorithm;
        }

        $resource->hashAlgorithm = $hashAlgorithm;
Cyril Vazquez's avatar
Cyril Vazquez committed
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
        $resource->hash = \laabs\hash_stream($hashAlgorithm, $resource->gethandler());
    }

    /**
     * Get the mimetype for a given resource
     * @param digitalResource/digitalResource $resource The resource
     */
    public function getMimetype($resource)
    {
        $handler = $resource->gethandler();
        $metadata = stream_get_meta_data($handler);
        if ($metadata['wrapper_type'] == 'plainfile') {
            $resource->mimetype = $this->finfo->file($metadata['uri'], \FILEINFO_MIME_TYPE);
        }
    }

    /**
     * Get the size for a given resource
     * @param digitalResource/digitalResource $resource The resource
     */
    public function getSize($resource)
    {
        $handler = $resource->gethandler();
        $metadata = stream_get_meta_data($handler);
        if ($metadata['wrapper_type'] == 'plainfile') {
228
229
230
231
232
233
            $resource->size = filesize($metadata['uri']);
        } else {
            $fstats = fstat($handler);
            if (isset($fstats['size'])) {
                $resource->size = $fstats['size'];
            }
Cyril Vazquez's avatar
Cyril Vazquez committed
234
        }
Prosper De Laure's avatar
Prosper De Laure committed
235
236
237
238
239
240
241
242
    }

    /**
     * Use a digital resource cluster for storage
     * @param string $clusterId
     * @param string $mode
     * @param bool   $limit
     *
Dylan's avatar
Dylan committed
243
     * @return digitalResource/cluster The cluster
Prosper De Laure's avatar
Prosper De Laure committed
244
245
246
     */
    public function useCluster($clusterId, $mode, $limit)
    {
247
        if (!isset($this->clusters[$mode][(string) $clusterId])) {
Prosper De Laure's avatar
Prosper De Laure committed
248
            $this->currentCluster = $this->clusterController->openCluster($clusterId, $mode, $limit);
249
            $this->clusters[$mode][(string) $clusterId] = $this->currentCluster;
Prosper De Laure's avatar
Prosper De Laure committed
250
        } else {
251
            $this->currentCluster = $this->clusters[$mode][(string) $clusterId];
Prosper De Laure's avatar
Prosper De Laure committed
252
253
254
255
256
        }

        return $this->currentCluster;
    }

257
258
259
260
261
    /**
     * Create a ressource container on the cluster (after opening it)
     * @param string $clusterId
     * @param string $path
     * @param mixed  $metadata
Alexandre Morin's avatar
Alexandre Morin committed
262
     *
Dylan's avatar
Dylan committed
263
     * @return string Ressource container on the cluster
264
265
266
     */
    public function openContainers($clusterId, $path, $metadata=null)
    {
267
        $cluster = $this->useCluster($clusterId, Cluster::MODE_WRITE, true);
268

269
        return $this->clusterController->openContainers($cluster, $path, $metadata);
270
271
272
    }


Prosper De Laure's avatar
Prosper De Laure committed
273
274
    /**
     * Store a given resource
275
     * @param digitalResource/digitalResource $resource The ressource object
Prosper De Laure's avatar
Prosper De Laure committed
276
     *
Dylan's avatar
Dylan committed
277
     * @return digitalResource/digitalResource digitalResource object
Prosper De Laure's avatar
Prosper De Laure committed
278
     */
279
    public function store($resource)
Prosper De Laure's avatar
Prosper De Laure committed
280
281
    {
        // Store resource + metadata
282
        $this->storeDigitalResource($resource);
Prosper De Laure's avatar
Prosper De Laure committed
283
284
285
286
287
288

        return $resource;
    }

    /**
     * Store a collection of resources sharing the same cluster and repositories from a list of resources
289
290
     * @param array  $resources An array of resources to store
     * @param string $clusterId The cluster to apply for store procedure
Prosper De Laure's avatar
Prosper De Laure committed
291
     *
Dylan's avatar
Dylan committed
292
     * @return mixed Collection of resources
Prosper De Laure's avatar
Prosper De Laure committed
293
     */
294
    public function storeCollection($resources, $clusterId)
Prosper De Laure's avatar
Prosper De Laure committed
295
296
    {
        // Get the storage objects
297
        $this->useCluster($clusterId, Cluster::MODE_WRITE, true);
Prosper De Laure's avatar
Prosper De Laure committed
298
299

        foreach ($resources as $resource) {
300
            $this->storeDigitalResource($resource);
Prosper De Laure's avatar
Prosper De Laure committed
301
302
303
304
305
306
307
308
            $resources[] = $resource;
        }

        return $resources;
    }

    /**
     * Store a new resource in current cluster
309
     * @param object $resource The resource
Prosper De Laure's avatar
Prosper De Laure committed
310
     */
311
    public function storeDigitalResource($resource)
Prosper De Laure's avatar
Prosper De Laure committed
312
313
    {
        if (empty($resource->size)) {
Cyril Vazquez's avatar
Cyril Vazquez committed
314
            $this->getSize($resource);
Prosper De Laure's avatar
Prosper De Laure committed
315
316
317
        }

        if (empty($resource->mimetype)) {
Cyril Vazquez's avatar
Cyril Vazquez committed
318
319
320
321
322
            $this->getMimetype($resource);
        }

        if (empty($resource->hash)) {
            $this->getHash($resource);
Prosper De Laure's avatar
Prosper De Laure committed
323
324
        }

Cyril Vazquez's avatar
Cyril Vazquez committed
325
326
327
        $resource->clusterId = $this->currentCluster->clusterId;
        $resource->created = \laabs::newTimestamp();

Prosper De Laure's avatar
Prosper De Laure committed
328
329
330
331
332
333
334
        $transactionControl = !$this->sdoFactory->inTransaction();

        if ($transactionControl) {
            $this->sdoFactory->beginTransaction();
        }

        try {
335
336
            $this->sdoFactory->create($resource, 'digitalResource/digitalResource');

337
            $this->clusterController->storeResource($this->currentCluster, $resource);
Prosper De Laure's avatar
Prosper De Laure committed
338
339
340

            if ($resource->relatedResource) {
                foreach ($resource->relatedResource as $relatedResource) {
Cyril Vazquez's avatar
Cyril Vazquez committed
341
342
343
344
345
346
347
                    if (empty($relatedResource->relatedResId)) {
                        $relatedResource->relatedResId = $resource->resId;
                    }
                    if (empty($relatedResource->archiveId)) {
                        $relatedResource->archiveId = $resource->archiveId;
                    }

348
                    $this->storeDigitalResource($relatedResource);
Prosper De Laure's avatar
Prosper De Laure committed
349
350
351
352
353
354
355
356
                }
            }
        } catch (\Exception $exception) {
            $this->clusterController->rollbackStorage($resource);

            if ($transactionControl) {
                $this->sdoFactory->rollback();
            }
357

Prosper De Laure's avatar
Prosper De Laure committed
358
            throw \laabs::newException("digitalResource/clusterException", 'Resource %1$s not created: %2$s', 404, $exception, [$resource->resId, $exception->getMessage()]);
Prosper De Laure's avatar
Prosper De Laure committed
359
360
361
362
363
364
365
366
367
        }

        // All repositories returned an uri, save all
        if ($transactionControl) {
            $this->sdoFactory->commit();
        }
    }

    /**
368
369
     * Get resources of archive
     * @param id $archiveId The archive identifier
Prosper De Laure's avatar
Prosper De Laure committed
370
     *
371
     * @return array Array of digitalResource object
Prosper De Laure's avatar
Prosper De Laure committed
372
     */
373
    public function getResourcesByArchiveId($archiveId)
Prosper De Laure's avatar
Prosper De Laure committed
374
    {
375
        $resources = $this->sdoFactory->find("digitalResource/digitalResource", "archiveId='$archiveId' AND relatedResId=null");
Prosper De Laure's avatar
Prosper De Laure committed
376

377
378
379
380
        foreach ($resources as $key => $resource) {
            $resources[$key] = $this->info($resource->resId);
        }

381
        return $resources;
Prosper De Laure's avatar
Prosper De Laure committed
382
383
384
385
386
387
388
    }

    /**
     * Get related resources
     * @param string $resId            The identifier of the converted or the original resource
     * @param string $relationshipType The relationship type with the resource identified by the second parameter
     *
Dylan's avatar
Dylan committed
389
     * @return digitalResource/digialResource[] Array of digitalResource/digialResource object
Prosper De Laure's avatar
Prosper De Laure committed
390
     */
391
    public function getRelatedResources($resId, $relationshipType = null)
Prosper De Laure's avatar
Prosper De Laure committed
392
393
    {
        // $relationshipType = isConversionOf OR isSignatureOf
394
        $whereClause = "relatedResId='$resId'";
Prosper De Laure's avatar
Prosper De Laure committed
395
396
397
398
399
400
401
402
403
404
405
406
407
408

        if ($relationshipType) {
            $whereClause .= " AND relationshipType='$relationshipType'";
        }

        $resources = $this->sdoFactory->find("digitalResource/digitalResource", $whereClause);

        return $resources;
    }

    /**
     * Retrieve a resource
     * @param string $resId The resource identifier
     *
Dylan's avatar
Dylan committed
409
     * @return digitalResource/digitalResource digitalResource object
Prosper De Laure's avatar
Prosper De Laure committed
410
411
412
413
414
415
416
417
418
419
420
421
422
     */
    public function retrieve($resId)
    {
        $resource = $this->sdoFactory->read("digitalResource/digitalResource", $resId);

        if (!$resource) {
            throw \laabs::newException("digitalResource/resourceNotFoundException");
        }

        if (isset($resource->puid)) {
            $resource->format = $this->formatController->get($resource->puid);
        }

423
        $cluster = $this->useCluster($resource->clusterId, Cluster::MODE_READ, false);
Prosper De Laure's avatar
Prosper De Laure committed
424
        $resource->cluster = $cluster;
425
        $handler = $this->clusterController->retrieveResource($cluster, $resource);
Prosper De Laure's avatar
Prosper De Laure committed
426

427
        if (!$handler) {
Prosper De Laure's avatar
Prosper De Laure committed
428
            throw \laabs::newException("digitalResource/clusterException", "Resource %s could not be retrieved.", 404, null, [$resource->resId]);
Prosper De Laure's avatar
Prosper De Laure committed
429
430
        }

431
        $relatedResources = $this->getRelatedResources($resource->resId);
Prosper De Laure's avatar
Prosper De Laure committed
432
433
434
435
436
437
438
        foreach ($relatedResources as $relatedResource) {
            $resource->relatedResource[] = $this->retrieve($relatedResource->resId);
        }

        return $resource;
    }

Cyril Vazquez's avatar
Cyril Vazquez committed
439
    public function checkHash($handler, $hash, $hashAlgorithm)
Alexandre Morin's avatar
Alexandre Morin committed
440
    {
Cyril Vazquez's avatar
Cyril Vazquez committed
441
        $hash_calculated = \laabs\hash_stream($hashAlgorithm, $handler);
Alexandre Morin's avatar
Alexandre Morin committed
442
443
444
445
446
447

        if ($hash_calculated !== strtolower($hash)) {
            throw \laabs::newException("digitalResource/invalidHashException", "Invalid hash.");
        }
    }

Prosper De Laure's avatar
Prosper De Laure committed
448
449
450
451
    /**
     * Get the contents of a given resource
     * @param string $resId
     *
Dylan's avatar
Dylan committed
452
     * @return string The contents of a given resource
Prosper De Laure's avatar
Prosper De Laure committed
453
454
455
456
457
458
459
460
     */
    public function contents($resId)
    {
        $resource = $this->sdoFactory->read("digitalResource/digitalResource", $resId);
        if (!$resource) {
            throw \laabs::newException("digitalResource/resourceNotFoundException");
        }

461
        $cluster = $this->useCluster($resource->clusterId, Cluster::MODE_READ, false);
Prosper De Laure's avatar
Prosper De Laure committed
462
463
464
465
466
467
468

        foreach ($cluster->clusterRepository as $clusterRepository) {
            $repositoryService = $clusterRepository->repository->getService();

            $address = $this->sdoFactory->read("digitalResource/address", array('resId' => $resId, 'repositoryId' => $clusterRepository->repositoryId));

            if ($address) {
Cyril Vazquez's avatar
Cyril Vazquez committed
469
470
                $handler = null;
                if (!$handler) {
Prosper De Laure's avatar
Prosper De Laure committed
471
                    try {
Cyril Vazquez's avatar
Cyril Vazquez committed
472
                        $handler = $repositoryService->readObject($address->path);
Alexandre Morin's avatar
Alexandre Morin committed
473

Cyril Vazquez's avatar
Cyril Vazquez committed
474
                        $this->checkHash($handler, $resource->hash, $resource->hashAlgorithm);
Prosper De Laure's avatar
Prosper De Laure committed
475
476
477
478
479
480
481
482
483
                    } catch (\Exception $e) {
                        // TODO : throw exception if resource not available on repo, based on options ?
                    }
                }
            } else {
                // TODO : throw exception if resource not available on repo, based on options ?
            }
        }

Cyril Vazquez's avatar
Cyril Vazquez committed
484
        if (!$handler) {
Prosper De Laure's avatar
Prosper De Laure committed
485
486
487
            throw \laabs::newException("digitalResource/clusterException", "Resource unavailable");
        }

Cyril Vazquez's avatar
Cyril Vazquez committed
488
        return $handler;
Prosper De Laure's avatar
Prosper De Laure committed
489
490
491
492
493
494
    }

    /**
     * Retrieve a resource metadata
     * @param string $resId
     *
Dylan's avatar
Dylan committed
495
     * @return mixed Resource metadata
Prosper De Laure's avatar
Prosper De Laure committed
496
497
498
499
500
501
502
503
     */
    public function metadata($resId)
    {
        $resource = $this->sdoFactory->read("digitalResource/digitalResource", $resId);
        if (!$resource) {
            throw \laabs::newException("digitalResource/clusterException", "Resource not found");
        }

504
        $cluster = $this->useCluster($resource->clusterId, Cluster::MODE_READ, false);
Prosper De Laure's avatar
Prosper De Laure committed
505
506
507
508
509
510
511
512
513
514
515

        if (!$cluster->storeMetadata) {
            return;
        }

        foreach ($cluster->clusterRepository as $clusterRepository) {
            $repositoryService = $clusterRepository->repository->getService();

            $address = $this->sdoFactory->read("digitalResource/address", array('resId' => $resId, 'repositoryId' => $clusterRepository->repositoryId));

            if ($address) {
516
                if ($contents = $repositoryService->readObject($address->path, 2)) {
Prosper De Laure's avatar
Prosper De Laure committed
517
518
519
520
521
522
523
524
525
526
                    return $contents;
                }
            }
        }
    }

    /**
     * Get all information about one digital resource
     * @param string $resId The identifier of digital resource
     *
Dylan's avatar
Dylan committed
527
     * @return digitalResource/digitalResource digitalResource object whith all information
Prosper De Laure's avatar
Prosper De Laure committed
528
529
530
531
532
533
534
535
536
537
538
539
540
     */
    public function info($resId)
    {
        $resource = $this->sdoFactory->read("digitalResource/digitalResource", $resId);

        if (!$resource) {
            throw \laabs::newException("digitalResource/clusterException", "Resource not found");
        }

        if (isset($resource->puid)) {
            $resource->format = $this->formatController->get($resource->puid);
        }

541
        $cluster = $this->useCluster($resource->clusterId, Cluster::MODE_READ, false);
Prosper De Laure's avatar
Prosper De Laure committed
542
543
544
545
546
547
548
549
550
551

        foreach ($cluster->clusterRepository as $clusterRepository) {
            $repositoryId = $clusterRepository->repositoryId;
            $repository = $this->sdoFactory->read("digitalResource/repository", $repositoryId);
            $address = $this->sdoFactory->read("digitalResource/address", array('resId' => $resId, 'repositoryId' => $repositoryId));
            $address->path = str_replace('\\', '/', $address->path);
            $address->repository = $repository;
            $resource->address[] = $address;
        }

552
        $relatedResources = $this->getRelatedResources($resource->resId);
Prosper De Laure's avatar
Prosper De Laure committed
553
554
555
556
557
558
559
560
561
562
563
        foreach ($relatedResources as $relatedResource) {
            $resource->relatedResource[] = $this->info($relatedResource->resId);
        }

        return $resource;
    }

    /**
     * Delete entire resource and all addresses
     * @param string $resId The resource identifier
     *
Dylan's avatar
Dylan committed
564
     * @return bool The result of the operation
Prosper De Laure's avatar
Prosper De Laure committed
565
566
567
568
569
570
571
572
     */
    public function delete($resId)
    {
        $resource = $this->sdoFactory->read("digitalResource/digitalResource", $resId);
        if (!$resource) {
            throw \laabs::newException("digitalResource/clusterException", "Resource not found");
        }

573
        $relatedResources = $this->getRelatedResources($resource->resId);
Prosper De Laure's avatar
Prosper De Laure committed
574
575
576
577
        foreach ($relatedResources as $relatedResource) {
            $resource->relatedResource[] = $this->delete($relatedResource->resId);
        }

578
        $cluster = $this->useCluster($resource->clusterId, Cluster::MODE_DELETE, false);
Prosper De Laure's avatar
Prosper De Laure committed
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598

        foreach ($cluster->clusterRepository as $clusterRepository) {
            $repositoryId = $clusterRepository->repositoryId;
            $address = $this->sdoFactory->read("digitalResource/address", array('resId' => $resId, 'repositoryId' => $repositoryId));
            $address->repository = $clusterRepository->repository;
            $resource->address[] = $address;
        }

        $transactionControl = !$this->sdoFactory->inTransaction();

        if ($transactionControl) {
            $this->sdoFactory->beginTransaction();
        }

        try {
            foreach ($resource->address as $address) {
                $this->sdoFactory->read("digitalResource/repository", $address->repositoryId);

                $repositoryService = $address->repository->getService();

599
                $repositoryService->deleteObject($address->path);
Prosper De Laure's avatar
Prosper De Laure committed
600
601
602
603
604
605
606
607
608

                $this->sdoFactory->delete($address);
            }

            $this->sdoFactory->delete($resource);
        } catch (\Exception $exception) {
            if ($transactionControl) {
                $this->sdoFactory->rollback();
            }
Prosper De Laure's avatar
Prosper De Laure committed
609
            throw \laabs::newException("digitalResource/clusterException", 'Resource not deleted at address %1$s : %2$s',  404, $exception, [$address->path, $exception->getMessage()]);
Prosper De Laure's avatar
Prosper De Laure committed
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
        }
        if ($transactionControl) {
            $this->sdoFactory->commit();
        }

        return true;
    }

    /**
     * Delete resource contents only
     * @param object $resource
     */
    public function rollbackStorage($resource)
    {
        $this->clusterController->rollbackStorage($resource);
    }

    /**
     * Verify integrity of resource
     * @param digitalResource/digitalResource $resource The digital resource
630
     * @param string                          $mode     The mode
Prosper De Laure's avatar
Prosper De Laure committed
631
     *
632
     * @return digitalResource/digitalResource The digitalResource object verify
Prosper De Laure's avatar
Prosper De Laure committed
633
634
635
     *
     * @throws digitalResource/resourceNotFoundException
     */
636
    public function verifyResource($resource, $mode = Cluster::MODE_READ)
Prosper De Laure's avatar
Prosper De Laure committed
637
638
639
640
641
    {
        if (!$resource) {
            throw \laabs::newException("digitalResource/resourceNotFoundException");
        }

642
        $cluster = $this->useCluster($resource->clusterId, $mode, false);
Prosper De Laure's avatar
Prosper De Laure committed
643
644
645
646
647
648
649
650

        return $this->clusterController->verifyResource($cluster, $resource);
    }

    /**
     * Convert resource to another format
     * @param object $digitalResource
     *
Dylan's avatar
Dylan committed
651
     * @return object The resource converted
Prosper De Laure's avatar
Prosper De Laure committed
652
     */
Alexis Ragot's avatar
Alexis Ragot committed
653
    public function convert($digitalResource)
Prosper De Laure's avatar
Prosper De Laure committed
654
    {
655
        $convert = $this->isConvertible($digitalResource);
Alexis Ragot's avatar
Alexis Ragot committed
656

Alexandre Morin's avatar
Alexandre Morin committed
657
        if ($convert == false) {
Prosper De Laure's avatar
Prosper De Laure committed
658
659
660
            return false;
        }

661
662
        $configuration =  \laabs::configuration('dependency.fileSystem');
        $conversionRule = $this->sdoFactory->read("digitalResource/conversionRule", array('puid' => $digitalResource->puid));
Prosper De Laure's avatar
Prosper De Laure committed
663
664
665
666
667
668
669
670
671
672
673
        $conversionServices = $configuration['conversionServices'];

        $outputFormats = null;
        $convertService = null;
        foreach ($conversionServices as $service) {
            if ($service["serviceName"] == $conversionRule->conversionService) {
                $outputFormats = $service["outputFormats"];
                $convertService = $service;
            }
        }

Cyril Vazquez's avatar
Cyril Vazquez committed
674
        $handler = $digitalResource->getHandler();
Prosper De Laure's avatar
Prosper De Laure committed
675

676
        $tempdir = str_replace("/", DIRECTORY_SEPARATOR, \laabs\tempdir());
Prosper De Laure's avatar
Prosper De Laure committed
677

678
679
680
681
        if (isset($digitalResource->fileName)) {
            $srcfile = $tempdir.DIRECTORY_SEPARATOR.$digitalResource->fileName;
        } else {
            $srcfile = $tempdir.DIRECTORY_SEPARATOR.$digitalResource->resId;
Prosper De Laure's avatar
Prosper De Laure committed
682
683
        }

684
685
686
687
688
        $tgtfp = fopen($srcfile, 'w');
        stream_copy_to_stream($handler, $tgtfp);
        rewind($handler);
        fclose($tgtfp);

689
        $conversionRule = $this->sdoFactory->read("digitalResource/conversionRule", array('puid' => $digitalResource->puid));
Prosper De Laure's avatar
Prosper De Laure committed
690

691
        $converter = \laabs::newService($conversionRule->conversionService);
Prosper De Laure's avatar
Prosper De Laure committed
692
693
694

        $tgtfile = $converter->convert($srcfile, $outputFormats[$conversionRule->targetPuid]);

695
        unlink($srcfile);
Cyril Vazquez's avatar
Cyril Vazquez committed
696

Prosper De Laure's avatar
Prosper De Laure committed
697
698
699
700
701
        if (!file_exists($tgtfile)) {
            return false;
        }

        $convertedResource = $this->createFromFile($tgtfile);
702
        $convertedResource->archiveId = $digitalResource->archiveId;
Prosper De Laure's avatar
Prosper De Laure committed
703
        $convertedResource->puid = $conversionRule->targetPuid;
704
705
        $convertedResource->softwareName = $convertService["softwareName"];
        $convertedResource->softwareVersion = $convertService["softwareVersion"];
Prosper De Laure's avatar
Prosper De Laure committed
706
707
        $this->getHash($convertedResource);

708
709
        $convertedResource->relationshipType = "isConversionOf";

710
        // Get previous
711
712
713
        while ($digitalResource->relatedResId != "" && $digitalResource->relationshipType == "isConversionOf") {
            $digitalResource = $this->sdoFactory->read("digitalResource/digitalResource", $digitalResource->relatedResId);
        }
Alexis Ragot's avatar
Alexis Ragot committed
714
        $convertedResource->relatedResId = $digitalResource->resId;
715

Prosper De Laure's avatar
Prosper De Laure committed
716
717
        return $convertedResource;
    }
718

719
720
721
722
    /**
     * Check if the resource can be convertible
     * @param $digitalResource/digitalResource $digitalResource The resource object
     *
723
     * @return mixed The convertion rule or false if it's no possible
724
     */
Alexandre Morin's avatar
Alexandre Morin committed
725
726
    public function isConvertible($digitalResource)
    {
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
        if (!$this->sdoFactory->exists("digitalResource/conversionRule", array('puid' => $digitalResource->puid))) {
            return false;
        }

        $configuration =  \laabs::configuration('dependency.fileSystem');

        if (!isset($configuration['conversionServices'])) {
            return false;
        }

        $conversionServices = $configuration['conversionServices'];

        if (!is_array($conversionServices)) {
            return false;
        }

        $conversionRule = $this->sdoFactory->read("digitalResource/conversionRule", array('puid' => $digitalResource->puid));

        $outputFormats = null;
        $convertService = null;
        foreach ($conversionServices as $service) {
            if ($service["serviceName"] == $conversionRule->conversionService) {
                $outputFormats = $service["outputFormats"];
                $convertService = $service;
            }
        }

        if (!in_array($digitalResource->puid, $convertService["inputFormats"])) {
            return false;
        }

        if (!$outputFormats) {
            return false;
        }

        $conversionRule = $this->sdoFactory->read("digitalResource/conversionRule", array('puid' => $digitalResource->puid));

        $converter = \laabs::newService($conversionRule->conversionService);

        if (!($converter instanceof \dependency\fileSystem\conversionInterface)) {
            return false;
        }

        return $converter;
    }

773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
    /**
     * Get the text of the resources of an archive
     * @param string $archiveId The resources archive identifier
     *
     * @return string The text of the resources
     */
    public function getFullTextByArchiveId($archiveId)
    {
        $fullText = "";
        $digitalResources = $this->sdoFactory->find("digitalResource/digitalResource", "archiveId='$archiveId' AND relatedResId=null");

        if (count($digitalResources)) {
            $fullTextService = \laabs::newService('dependency/fileSystem/plugins/tika');

            foreach ($digitalResources as $digitalResource) {
                $contents = $this->contents($digitalResource->resId);
                $tempdir = str_replace("/", DIRECTORY_SEPARATOR, \laabs\tempdir());
Alexandre Morin's avatar
Alexandre Morin committed
790

791
792
793
794
795
796
797
798
799
800
                $srcfile = $tempdir.DIRECTORY_SEPARATOR.$digitalResource->resId;

                file_put_contents($srcfile, $contents);

                $fullText .= $fullTextService->getText($srcfile);
            }
        }

        return $fullText;
    }
Prosper De Laure's avatar
Prosper De Laure committed
801
}