Passed
Push — master ( 2bc9d0...c77363 )
by Andreas
10:41
created

midcom_helper_metadata::approve()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
/**
3
 * @package midcom.helper
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
use midcom\datamanager\schemadb;
10
use midcom\datamanager\datamanager;
11
12
/**
13
 * This class is an interface to the metadata of MidCOM objects.
14
 *
15
 * It will use an internal mechanism to cache repeated accesses to the same
16
 * metadata key during its lifetime. (Invalidating this cache will be possible
17
 * though.)
18
 *
19
 * <b>Metadata Key Reference</b>
20
 *
21
 * See the schema in /midcom/config/metadata_default.inc
22
 *
23
 * <b>Example Usage, Metadata Retrieval</b>
24
 *
25
 * <code>
26
 * <?php
27
 * $nap = new midcom_helper_nav();
28
 * $node = $nap->get_node($nap->get_current_node());
29
 *
30
 * $meta = $node[MIDCOM_NAV_OBJECT]->metadata;
31
 * echo "Visible : " . $meta->is_visible() . "</br>";
32
 * echo "Approved : " . $meta->is_approved() . "</br>";
33
 * echo "Keywords: " . $meta->get('keywords') . "</br>";
34
 * </code>
35
 *
36
 * <b>Example Usage, Approval</b>
37
 *
38
 * <code>
39
 * <?php
40
 * $article = new midcom_db_article($my_article_created_id);
41
 *
42
 * $article->metadata->approve();
43
 * </code>
44
 *
45
 * @property integer $schedulestart The time upon which the object should be made visible. 0 for no restriction.
46
 * @property integer $scheduleend The time upon which the object should be made invisible. 0 for no restriction.
47
 * @property boolean $navnoentry Set this to true if you do not want this object to appear in the navigation without it being completely hidden.
48
 * @property boolean $hidden Set this to true to hide the object on-site, overriding scheduling.
49
 * @property integer $published The publication time of the object.
50
 * @property string $publisher The person that published the object (i.e. author), read-only except on articles and pages.
51
 * @property string $authors The persons that worked on the object, pipe-separated list of GUIDs
52
 * @property string $owner The group that owns the object.
53
 * @property-read integer $created The creation time of the object.
54
 * @property-read string $creator The person that created the object.
55
 * @property-read integer $revised The last-modified time of the object.
56
 * @property-read string $revisor The person that modified the object.
57
 * @property-read integer $revision The object's revision.
58
 * @property-read integer $locked The lock time of the object.
59
 * @property-read string $locker The person that locked the object.
60
 * @property-read integer $size The object's size in bytes.
61
 * @property-read boolean $deleted Is the object deleted.
62
 * @property integer $approved The time of approval of the object, or 0 if not approved. Set automatically through approve/unapprove.
63
 * @property string $approver The person that approved/unapproved the object. Set automatically through approve/unapprove.
64
 * @property integer $score The object's score for sorting.
65
 * @property midcom_core_dbaobject $object Object to which we are attached.
66
 * @package midcom.helper
67
 */
68
class midcom_helper_metadata
69
{
70
    /**
71
     * @var midcom_core_dbaobject
72
     */
73
    private $__object;
74
75
    /**
76
     * @var midgard\portable\api\metadata
77
     */
78
    private $__metadata;
79
80
    /**
81
     * @var array
82
     */
83
    private $_cache = [];
84
85
    private $field_config = [
86
        'readonly' => ['creator', 'created', 'revisor', 'revised', 'locker', 'locked', 'revision', 'size', 'deleted', 'exported', 'imported', 'islocked', 'isapproved'],
87
        'timebased' => ['created', 'revised', 'published', 'locked', 'approved', 'schedulestart', 'scheduleend', 'exported', 'imported'],
88
        'person' => ['creator', 'revisor', 'locker', 'approver'],
89
        'other' => ['authors', 'owner', 'hidden', 'navnoentry', 'score', 'revision', 'size', 'deleted'],
90
        'functions' => [
91
            'islocked' => 'is_locked',
92
            'isapproved' => 'is_approved'
93
        ]
94
    ];
95
96
    /**
97
     * This will construct a new metadata object for an existing content object.
98
     */
99 413
    public function __construct(midcom_core_dbaobject $object)
100
    {
101 413
        $this->__metadata = $object->__object->metadata;
102 413
        $this->__object = $object;
103
    }
104
105
    /* ------- BASIC METADATA INTERFACE --------- */
106
107
    /**
108
     * Return a single metadata key from the object. The return
109
     * type depends on the metadata key that is requested (see the class introduction).
110
     *
111
     * You will not get the data from the datamanager using this calls, but the only
112
     * slightly post-processed metadata values. See _retrieve_value for post processing.
113
     *
114
     * @see midcom_helper_metadata::_retrieve_value()
115
     * @return mixed The key's value.
116
     */
117 425
    public function get(string $key)
118
    {
119 425
        if (!isset($this->_cache[$key])) {
120 298
            $this->_cache[$key] = $this->_retrieve_value($key);
121
        }
122
123 425
        return $this->_cache[$key];
124
    }
125
126 380
    public function __get($key)
127
    {
128 380
        if ($key == 'object') {
129 79
            return $this->__object;
130
        }
131 380
        return $this->get($key);
132
    }
133
134 325
    public function __isset($key)
135
    {
136 325
        if (!isset($this->_cache[$key])) {
137 325
            $this->_cache[$key] = $this->_retrieve_value($key);
138
        }
139
140 325
        return isset($this->_cache[$key]);
141
    }
142
143
    /**
144
     * Return a Datamanager instance for the current object.
145
     *
146
     * Also, whenever the containing datamanager stores its data, you
147
     * <b>must</b> call the on_update() method of this class. This is
148
     * very important or backwards compatibility will be broken.
149
     *
150
     * @see midcom_helper_metadata::on_update()
151
     */
152 9
    public function get_datamanager() : datamanager
153
    {
154
        static $schemadb;
155 9
        if ($schemadb === null) {
156 1
            $schemadb = schemadb::from_path(midcom::get()->config->get('metadata_schema'));
0 ignored issues
show
Bug introduced by
It seems like midcom::get()->config->get('metadata_schema') can also be of type null; however, parameter $path of midcom\datamanager\schemadb::from_path() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

156
            $schemadb = schemadb::from_path(/** @scrutinizer ignore-type */ midcom::get()->config->get('metadata_schema'));
Loading history...
157
        }
158
159
        // Check if we have metadata schema defined in the schemadb specific for the object's schema or component
160 9
        $object_schema = $this->__object->get_parameter('midcom.helper.datamanager2', 'schema_name');
161 9
        if (!$object_schema || !$schemadb->has($object_schema)) {
162 9
            $component_schema = str_replace('.', '_', midcom_core_context::get()->get_key(MIDCOM_CONTEXT_COMPONENT) ?: 'midcom');
163 9
            if ($schemadb->has($component_schema)) {
164
                // No specific metadata schema for object, fall back to component-specific metadata schema
165
                $object_schema = $component_schema;
166
            } else {
167
                // No metadata schema for component, fall back to default
168 9
                $object_schema = 'metadata';
169
            }
170
        }
171 9
        $dm = new datamanager($schemadb);
172 9
        return $dm->set_storage($this->__object, $object_schema);
173
    }
174
175
    /**
176
     * Frontend for setting a single metadata option
177
     */
178 313
    public function set(string $key, $value) : bool
179
    {
180
        // Store the RCS mode
181 313
        $rcs_mode = $this->__object->_use_rcs;
182
183 313
        if ($return = $this->_set_property($key, $value)) {
184 313
            if ($this->__object->guid) {
185 11
                $return = $this->__object->update();
186
            }
187
188
            // Update the corresponding cache variable
189 313
            $this->on_update($key);
190
        }
191
        // Return the original RCS mode
192 313
        $this->__object->_use_rcs = $rcs_mode;
193 313
        return $return;
194
    }
195
196 17
    public function __set($key, $value)
197
    {
198 17
        $this->set($key, $value);
199
    }
200
201
    /**
202
     * Directly set a metadata option.
203
     *
204
     * The passed value will be stored using the follow transformations:
205
     *
206
     * - Storing into the approver field will automatically recognize Person Objects and simple
207
     *   IDs and transform them into a GUID.
208
     * - created can only be set with articles.
209
     * - creator, editor and edited cannot be set.
210
     *
211
     * Any error will trigger midcom_error.
212
     */
213 313
    private function _set_property(string $key, $value) : bool
214
    {
215 313
        if (is_object($value)) {
216
            $classname = get_class($value);
217
            debug_add("Can not set metadata '{$key}' property with '{$classname}' object as value", MIDCOM_LOG_WARN);
218
            return false;
219
        }
220
221 313
        if (in_array($key, $this->field_config['readonly'])) {
222
            midcom_connection::set_error(MGD_ERR_ACCESS_DENIED);
223
            return false;
224
        }
225
226 313
        if (in_array($key, ['approver', 'approved'])) {
227
            // Prevent lock changes from creating new revisions
228
            $this->__object->_use_rcs = false;
229
        }
230
231 313
        if (in_array($key, $this->field_config['timebased'])) {
232 311
            if (!is_numeric($value) || $value == 0) {
233 3
                $value = null;
234
            } else {
235 311
                $value = new midgard_datetime(gmdate('Y-m-d H:i:s', $value));
236
            }
237 158
        } elseif (!in_array($key, $this->field_config['other']) && $key !== 'approver') {
238
            // Fall-back for non-core properties
239 4
            return $this->__object->set_parameter('midcom.helper.metadata', $key, $value);
240
        }
241
242 313
        $this->__metadata->$key = $value;
243 313
        return true;
244
    }
245
246
    /**
247
     * This is the update event handler for the Metadata system. It must be called
248
     * whenever metadata changes to synchronize the various backwards-compatibility
249
     * values in place throughout the system.
250
     *
251
     * @param string $key The key that was updated. Leave empty for a complete update by the Datamanager.
252
     */
253 313
    private function on_update(string $key = null)
254
    {
255 313
        if ($key) {
256 313
            unset($this->_cache[$key]);
257
        } else {
258
            $this->_cache = [];
259
        }
260
261 313
        if (!empty($this->__object->guid)) {
262 11
            midcom::get()->cache->invalidate($this->__object->guid);
263
        }
264
    }
265
266
    /* ------- METADATA I/O INTERFACE -------- */
267
268
    /**
269
     * Retrieves a given metadata key, postprocesses it where necessary
270
     * and stores it into the local cache.
271
     *
272
     * - Person references (both guid and id) get resolved into the corresponding
273
     *   Person object.
274
     * - created, creator, edited and editor are taken from the corresponding
275
     *   MidgardObject fields.
276
     * - Parameters are accessed using $object->get_parameter directly
277
     *
278
     * Note, that we hide any errors from not existent properties explicitly,
279
     * as a few of the MidCOM objects do not support all of the predefined meta
280
     * data fields, PHP will default to "0" in these cases. For Person IDs, this
281
     * "0" is rewritten to "1" to use the MidgardAdministrator account instead.
282
     */
283 425
    private function _retrieve_value(string $key)
284
    {
285 425
        if (in_array($key, $this->field_config['timebased'])) {
286
            // This is ugly, but seems the only possible way...
287 403
            if (   isset($this->__metadata->$key)
288 403
                && (string) $this->__metadata->$key !== "0001-01-01T00:00:00+00:00") {
289 179
                return (int) $this->__metadata->$key->format('U');
290
            }
291 355
            return 0;
292
        }
293 279
        if (in_array($key, $this->field_config['person'])) {
294 117
            if (!$this->__metadata->$key) {
295
                // Fall back to "Midgard root user" if person is not found
296
                static $root_user_guid = null;
297 88
                if (!$root_user_guid) {
298
                    $mc = new midgard_collector('midgard_person', 'id', 1);
299
                    $mc->set_key_property('guid');
300
                    $mc->execute();
301
                    $root_user_guid = key($mc->list_keys()) ?: 'f6b665f1984503790ed91f39b11b5392';
302
                }
303
304 88
                return $root_user_guid;
305
            }
306 70
            return $this->__metadata->$key;
307
        }
308 268
        if (array_key_exists($key, $this->field_config['functions'])) {
309 79
            $function = $this->field_config['functions'][$key];
310 79
            return $this->$function();
311
        }
312 268
        if (!in_array($key, $this->field_config['other'])) {
313
            // Fall-back for non-core properties
314 8
            $dm = $this->get_datamanager();
315 8
            if (!$dm->get_schema()->has_field($key)) {
316
                // Fall back to the parameter reader for non-core MidCOM metadata params
317 4
                return $this->__object->get_parameter('midcom.helper.metadata', $key);
318
            }
319 4
            return $dm->get_content_csv()[$key];
320
        }
321 266
        return $this->__metadata->$key;
322
    }
323
324
    /* ------- CONVENIENCE METADATA INTERFACE --------- */
325
326
    /**
327
     * Checks whether the object has been approved since its last editing.
328
     */
329 79
    public function is_approved() : bool
330
    {
331 79
        return $this->__object->is_approved();
332
    }
333
334
    /**
335
     * Checks the object's visibility regarding scheduling and the hide flag.
336
     *
337
     * This does not check approval, use is_approved for that.
338
     *
339
     * @see midcom_helper_metadata::is_approved()
340
     */
341
    public function is_visible() : bool
342
    {
343
        if ($this->get('hidden')) {
344
            return false;
345
        }
346
347
        $now = time();
348
        if (   $this->get('schedulestart')
349
            && $this->get('schedulestart') > $now) {
350
            return false;
351
        }
352
        if (   $this->get('scheduleend')
353
            && $this->get('scheduleend') < $now) {
354
            return false;
355
        }
356
        return true;
357
    }
358
359
    /**
360
     * This is a helper function which indicates whether a given object may be shown onsite
361
     * taking approval, scheduling and visibility settings into account. The important point
362
     * here is that it also checks the global configuration defaults, so that this is
363
     * basically the same base on which NAP decides whether to show an item or not.
364
     */
365 145
    public function is_object_visible_onsite() : bool
366
    {
367
        return
368 145
        (   (   midcom::get()->config->get('show_hidden_objects')
369 145
             || $this->is_visible())
370 145
         && (   midcom::get()->config->get('show_unapproved_objects')
371 145
             || $this->is_approved())
372
        );
373
    }
374
375
    /**
376
     * Approves the object.
377
     *
378
     * This sets the approved timestamp to the current time and the
379
     * approver person GUID to the GUID of the person currently
380
     * authenticated.
381
     */
382 1
    public function approve() : bool
383
    {
384 1
        midcom::get()->auth->require_do('midcom:approve', $this->__object);
385 1
        midcom::get()->auth->require_do('midgard:update', $this->__object);
386 1
        return $this->__object->approve();
387
    }
388
389
    /**
390
     * Unapproves the object.
391
     *
392
     * This resets the approved timestamp and sets the
393
     * approver person GUID to the GUID of the person currently
394
     * authenticated.
395
     */
396 1
    public function unapprove() : bool
397
    {
398 1
        midcom::get()->auth->require_do('midcom:approve', $this->__object);
399 1
        midcom::get()->auth->require_do('midgard:update', $this->__object);
400 1
        return $this->__object->unapprove();
401
    }
402
403
    /* ------- CLASS MEMBER FUNCTIONS ------- */
404
405
    /**
406
     * Returns a metadata object for a given content object.
407
     *
408
     * You may pass any one of the following arguments to the function:
409
     *
410
     * - Any class derived from MidgardObject, you must only ensure, that the parameter
411
     *   and guid member functions stays available.
412
     * - Any valid GUID
413
     *
414
     * @param mixed $source The object to attach to, this may be either a MidgardObject or a GUID.
415
     */
416 51
    public static function retrieve($source) : ?self
417
    {
418 51
        $object = null;
419
420 51
        if (is_object($source)) {
421 51
            $object = $source;
422 51
            $guid = $source->guid;
423
        } else {
424
            $guid = $source;
425
        }
426
427 51
        if (   $object === null
428 51
            && mgd_is_guid($guid)) {
429
            try {
430
                $object = midcom::get()->dbfactory->get_object_by_guid($guid);
431
            } catch (midcom_error $e) {
432
                debug_add("Failed to create a metadata instance for the GUID {$guid}: " . $e->getMessage(), MIDCOM_LOG_WARN);
433
                debug_print_r("Source was:", $source);
434
435
                return null;
436
            }
437
        }
438
439
        // $object is now populated, too
440 51
        return new self($object);
0 ignored issues
show
Bug introduced by
It seems like $object can also be of type null; however, parameter $object of midcom_helper_metadata::__construct() does only seem to accept midcom_core_dbaobject, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

440
        return new self(/** @scrutinizer ignore-type */ $object);
Loading history...
441
    }
442
443
    /**
444
     * Check if the requested object is locked
445
     */
446 158
    public function is_locked() : bool
447
    {
448
        // Object hasn't been marked to be edited
449 158
        if ($this->get('locked') == 0) {
450 126
            return false;
451
        }
452
453 32
        if (($this->get('locked') + (midcom::get()->config->get('metadata_lock_timeout') * 60)) < time()) {
454
            // lock expired, explicitly clear lock
455
            $this->unlock();
456
            return false;
457
        }
458
459
        // Lock was created by the user, return "not locked"
460 32
        if (   !empty(midcom::get()->auth->user->guid)
461 32
            && $this->get('locker') === midcom::get()->auth->user->guid) {
462 31
            return false;
463
        }
464
465
        // Unlocked states checked and none matched, consider locked
466 1
        return $this->__object->is_locked();
467
    }
468
469
    /**
470
     * Set the object lock
471
     *
472
     * @return boolean       Indicating success
473
     */
474 45
    public function lock() : bool
475
    {
476 45
        midcom::get()->auth->require_do('midgard:update', $this->__object);
477
478 45
        if ($this->__object->lock()) {
479 33
            $this->_cache = [];
480 33
            return true;
481
        }
482
483 12
        return false;
484
    }
485
486
    /**
487
     * Check whether current user can unlock the object
488
     *
489
     * @todo enable specifying user ?
490
     */
491 15
    public function can_unlock() : bool
492
    {
493 15
        return (   $this->__object->can_do('midcom:unlock')
494 15
                || midcom::get()->auth->can_user_do('midcom:unlock', null, midcom_services_auth::class));
495
    }
496
497
    /**
498
     * Unlock the object
499
     *
500
     * @return boolean    Indicating success
501
     */
502 14
    public function unlock() : bool
503
    {
504 14
        if (   $this->can_unlock()
505 14
            && $this->__object->unlock()) {
506 13
            $this->_cache = [];
507 13
            return true;
508
        }
509
510 1
        return false;
511
    }
512
}
513