This file is indexed.

/usr/lib/python2.7/dist-packages/pycalendar/componentbase.py is in python-pycalendar 2.0~svn13177-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
##
#    Copyright (c) 2007-2012 Cyrus Daboo. All rights reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
##

from cStringIO import StringIO
from pycalendar import xmldefs
from pycalendar.datetimevalue import PyCalendarDateTimeValue
from pycalendar.periodvalue import PyCalendarPeriodValue
from pycalendar.property import PyCalendarProperty
from pycalendar.value import PyCalendarValue
import xml.etree.cElementTree as XML

class PyCalendarComponentBase(object):

    # These are class attributes for sets of properties for testing cardinality constraints. The sets
    # must contain property names.
    propertyCardinality_1 = ()           # Must be present
    propertyCardinality_1_Fix_Empty = () # Must be present but can be fixed by adding an empty value
    propertyCardinality_0_1 = ()         # 0 or 1 only
    propertyCardinality_1_More = ()      # 1 or more

    propertyValueChecks = None  # Either iCalendar or vCard validation

    sortSubComponents = True

    def __init__(self, parent=None):
        self.mParentComponent = parent
        self.mComponents = []
        self.mProperties = {}

        # This is the set of checks we do by default for components
        self.cardinalityChecks = (
            self.check_cardinality_1,
            self.check_cardinality_1_Fix_Empty,
            self.check_cardinality_0_1,
            self.check_cardinality_1_More,
        )


    def duplicate(self, **args):
        other = self.__class__(**args)

        for component in self.mComponents:
            other.addComponent(component.duplicate(parent=other))

        other.mProperties = {}
        for propname, props in self.mProperties.iteritems():
            other.mProperties[propname] = [i.duplicate() for i in props]
        return other


    def __str__(self):
        return self.getText()


    def __ne__(self, other):
        return not self.__eq__(other)


    def __eq__(self, other):
        if not isinstance(other, PyCalendarComponentBase):
            return False
        return self.getType() == other.getType() and self.compareProperties(other) and self.compareComponents(other)


    def getType(self):
        raise NotImplementedError


    def getBeginDelimiter(self):
        return "BEGIN:" + self.getType()


    def getEndDelimiter(self):
        return "END:" + self.getType()


    def getSortKey(self):
        return ""


    def getParentComponent(self):
        return self.mParentComponent


    def setParentComponent(self, parent):
        self.mParentComponent = parent


    def compareComponents(self, other):
        mine = set(self.mComponents)
        theirs = set(other.mComponents)

        for item in mine:
            for another in theirs:
                if item == another:
                    theirs.remove(another)
                    break
            else:
                return False
        return len(theirs) == 0


    def getComponents(self, compname=None):
        compname = compname.upper() if compname else None
        return [component for component in self.mComponents if compname is None or component.getType().upper() == compname]


    def getComponentByKey(self, key):
        for component in self.mComponents:
            if component.getMapKey() == key:
                return component
        else:
            return None


    def removeComponentByKey(self, key):

        for component in self.mComponents:
            if component.getMapKey() == key:
                self.removeComponent(component)
                return


    def addComponent(self, component):
        self.mComponents.append(component)


    def hasComponent(self, compname):
        return self.countComponents(compname) != 0


    def countComponents(self, compname):
        return len(self.getComponents(compname))


    def removeComponent(self, component):
        self.mComponents.remove(component)


    def removeAllComponent(self, compname=None):
        if compname:
            compname = compname.upper()
            for component in tuple(self.mComponents):
                if component.getType().upper() == compname:
                    self.removeComponent(component)
        else:
            self.mComponents = []


    def sortedComponentNames(self):
        return ()


    def compareProperties(self, other):
        mine = set()
        for props in self.mProperties.values():
            mine.update(props)
        theirs = set()
        for props in other.mProperties.values():
            theirs.update(props)
        return mine == theirs


    def getProperties(self, propname=None):
        return self.mProperties.get(propname.upper(), []) if propname else self.mProperties


    def setProperties(self, props):
        self.mProperties = props


    def addProperty(self, prop):
        self.mProperties.setdefault(prop.getName().upper(), []).append(prop)


    def hasProperty(self, propname):
        return propname.upper() in self.mProperties


    def countProperty(self, propname):
        return len(self.mProperties.get(propname.upper(), []))


    def findFirstProperty(self, propname):
        return self.mProperties.get(propname.upper(), [None])[0]


    def removeProperty(self, prop):
        if prop.getName().upper() in self.mProperties:
            self.mProperties[prop.getName().upper()].remove(prop)
            if len(self.mProperties[prop.getName().upper()]) == 0:
                del self.mProperties[prop.getName().upper()]


    def removeProperties(self, propname):
        if propname.upper() in self.mProperties:
            del self.mProperties[propname.upper()]


    def getPropertyInteger(self, prop, type=None):
        return self.loadValueInteger(prop, type)


    def getPropertyString(self, prop):
        return self.loadValueString(prop)


    def getProperty(self, prop, value):
        return self.loadValue(prop, value)


    def finalise(self):
        raise NotImplemented


    def validate(self, doFix=False):
        """
        Validate the data in this component and optionally fix any problems. Return
        a tuple containing two lists: the first describes problems that were fixed, the
        second problems that were not fixed. Caller can then decide what to do with unfixed
        issues.
        """

        fixed = []
        unfixed = []

        # Cardinality tests
        for check in self.cardinalityChecks:
            check(fixed, unfixed, doFix)

        # Value constraints - these tests come from class specific attributes
        if self.propertyValueChecks is not None:
            for properties in self.mProperties.values():
                for property in properties:
                    propname = property.getName().upper()
                    if propname in self.propertyValueChecks:
                        if not self.propertyValueChecks[propname](property):
                            # Cannot fix a bad property value
                            logProblem = "[%s] Property value incorrect: %s" % (self.getType(), propname,)
                            unfixed.append(logProblem)

        # Validate all subcomponents
        for component in self.mComponents:
            morefixed, moreunfixed = component.validate(doFix)
            fixed.extend(morefixed)
            unfixed.extend(moreunfixed)

        return fixed, unfixed


    def check_cardinality_1(self, fixed, unfixed, doFix):
        for propname in self.propertyCardinality_1:
            if self.countProperty(propname) != 1: # Cannot fix a missing required property
                logProblem = "[%s] Missing or too many required property: %s" % (self.getType(), propname)
                unfixed.append(logProblem)


    def check_cardinality_1_Fix_Empty(self, fixed, unfixed, doFix):
        for propname in self.propertyCardinality_1_Fix_Empty:
            if self.countProperty(propname) > 1: # Cannot fix too many required property
                logProblem = "[%s] Too many required property: %s" % (self.getType(), propname)
                unfixed.append(logProblem)
            elif self.countProperty(propname) == 0: # Possibly fix by adding empty property
                logProblem = "[%s] Missing required property: %s" % (self.getType(), propname)
                if doFix:
                    self.addProperty(PyCalendarProperty(propname, ""))
                    fixed.append(logProblem)
                else:
                    unfixed.append(logProblem)


    def check_cardinality_0_1(self, fixed, unfixed, doFix):
        for propname in self.propertyCardinality_0_1:
            if self.countProperty(propname) > 1: # Cannot be fixed - no idea which one to delete
                logProblem = "[%s] Too many properties present: %s" % (self.getType(), propname)
                unfixed.append(logProblem)


    def check_cardinality_1_More(self, fixed, unfixed, doFix):
        for propname in self.propertyCardinality_1_More:
            if not self.countProperty(propname) > 0: # Cannot fix a missing required property
                logProblem = "[%s] Missing required property: %s" % (self.getType(), propname)
                unfixed.append(logProblem)


    def getText(self):
        s = StringIO()
        self.generate(s)
        return s.getvalue()


    def generate(self, os):
        # Header
        os.write(self.getBeginDelimiter())
        os.write("\r\n")

        # Write each property
        self.writeProperties(os)

        # Write each embedded component based on specific order
        self.writeComponents(os)

        # Footer
        os.write(self.getEndDelimiter())
        os.write("\r\n")


    def generateFiltered(self, os, filter):
        # Header
        os.write(self.getBeginDelimiter())
        os.write("\r\n")

        # Write each property
        self.writePropertiesFiltered(os, filter)

        # Write each embedded component based on specific order
        self.writeComponentsFiltered(os, filter)

        # Footer
        os.write(self.getEndDelimiter())
        os.write("\r\n")


    def writeXML(self, node, namespace):

        # Component element
        comp = XML.SubElement(node, xmldefs.makeTag(namespace, self.getType()))

        # Each property
        self.writePropertiesXML(comp, namespace)

        # Each component
        self.writeComponentsXML(comp, namespace)


    def writeXMLFiltered(self, node, namespace, filter):
        # Component element
        comp = XML.SubElement(node, xmldefs.makeTag(namespace, self.getType()))

        # Each property
        self.writePropertiesFilteredXML(comp, namespace, filter)

        # Each component
        self.writeComponentsFilteredXML(comp, namespace, filter)


    def sortedComponents(self):

        components = self.mComponents[:]
        sortedcomponents = []

        # Write each component based on specific order
        orderedNames = self.sortedComponentNames()
        for name in orderedNames:

            # Group by name then sort by map key (UID/R-ID)
            namedcomponents = []
            for component in tuple(components):
                if component.getType().upper() == name:
                    namedcomponents.append(component)
                    components.remove(component)
            for component in sorted(namedcomponents, key=lambda x: x.getSortKey()):
                sortedcomponents.append(component)

        # Write out the remainder sorted by name, sortKey
        if self.sortSubComponents:
            remainder = sorted(components, key=lambda x: (x.getType().upper(), x.getSortKey(),))
        else:
            remainder = components
        for component in remainder:
            sortedcomponents.append(component)

        return sortedcomponents


    def writeComponents(self, os):

        # Write out the remainder
        for component in self.sortedComponents():
            component.generate(os)


    def writeComponentsFiltered(self, os, filter):
        # Shortcut for all sub-components
        if filter.isAllSubComponents():
            self.writeComponents(os)
        elif filter.hasSubComponentFilters():
            for subcomp in self.sortedcomponents():
                subfilter = filter.getSubComponentFilter(subcomp.getType())
                if subfilter is not None:
                    subcomp.generateFiltered(os, subfilter)


    def writeComponentsXML(self, node, namespace):

        if self.mComponents:
            comps = XML.SubElement(node, xmldefs.makeTag(namespace, xmldefs.components))

            # Write out the remainder
            for component in self.sortedComponents():
                component.writeXML(comps, namespace)


    def writeComponentsFilteredXML(self, node, namespace, filter):

        if self.mComponents:
            comps = XML.SubElement(node, xmldefs.makeTag(namespace, xmldefs.components))

            # Shortcut for all sub-components
            if filter.isAllSubComponents():
                self.writeXML(comps, namespace)
            elif filter.hasSubComponentFilters():
                for subcomp in self.sortedcomponents():
                    subfilter = filter.getSubComponentFilter(subcomp.getType())
                    if subfilter is not None:
                        subcomp.writeFilteredXML(comps, namespace, subfilter)


    def loadValue(self, value_name):
        if self.hasProperty(value_name):
            return self.findFirstProperty(value_name)

        return None


    def loadValueInteger(self, value_name, type=None):
        if type:
            if self.hasProperty(value_name):
                if type == PyCalendarValue.VALUETYPE_INTEGER:
                    ivalue = self.findFirstProperty(value_name).getIntegerValue()
                    if ivalue is not None:
                        return ivalue.getValue()
                elif type == PyCalendarValue.VALUETYPE_UTC_OFFSET:
                    uvalue = self.findFirstProperty(value_name).getUTCOffsetValue()
                    if (uvalue is not None):
                        return uvalue.getValue()

            return None
        else:
            return self.loadValueInteger(value_name, PyCalendarValue.VALUETYPE_INTEGER)


    def loadValueString(self, value_name):
        if self.hasProperty(value_name):
            tvalue = self.findFirstProperty(value_name).getTextValue()
            if (tvalue is not None):
                return tvalue.getValue()

        return None


    def loadValueDateTime(self, value_name):
        if self.hasProperty(value_name):
            dtvalue = self.findFirstProperty(value_name).getDateTimeValue()
            if dtvalue is not None:
                return dtvalue.getValue()

        return None


    def loadValueDuration(self, value_name):
        if self.hasProperty(value_name):
            dvalue = self.findFirstProperty(value_name).getDurationValue()
            if (dvalue is not None):
                return dvalue.getValue()

        return None


    def loadValuePeriod(self, value_name):
        if self.hasProperty(value_name):
            pvalue = self.findFirstProperty(value_name).getPeriodValue()
            if (pvalue is not None):
                return pvalue.getValue()

        return None


    def loadValueRRULE(self, value_name, value, add):
        # Get RRULEs
        if self.hasProperty(value_name):
            items = self.getProperties()[value_name]
            for iter in items:
                rvalue = iter.getRecurrenceValue()
                if (rvalue is not None):
                    if add:
                        value.addRule(rvalue.getValue())
                    else:
                        value.subtractRule(rvalue.getValue())
            return True
        else:
            return False


    def loadValueRDATE(self, value_name, value, add):
        # Get RDATEs
        if self.hasProperty(value_name):
            for iter in self.getProperties(value_name):
                mvalue = iter.getMultiValue()
                if (mvalue is not None):
                    for obj in mvalue.getValues():
                        # cast to date-time
                        if isinstance(obj, PyCalendarDateTimeValue):
                            if add:
                                value.addDT(obj.getValue())
                            else:
                                value.subtractDT(obj.getValue())
                        elif isinstance(obj, PyCalendarPeriodValue):
                            if add:
                                value.addPeriod(obj.getValue().getStart())
                            else:
                                value.subtractPeriod(obj.getValue().getStart())

            return True
        else:
            return False


    def sortedPropertyKeys(self):
        keys = self.mProperties.keys()
        keys.sort()

        results = []
        for skey in self.sortedPropertyKeyOrder():
            if skey in keys:
                results.append(skey)
                keys.remove(skey)
        results.extend(keys)
        return results


    def sortedPropertyKeyOrder(self):
        return ()


    def writeProperties(self, os):
        # Sort properties by name
        keys = self.sortedPropertyKeys()
        for key in keys:
            props = self.mProperties[key]
            for prop in props:
                prop.generate(os)


    def writePropertiesFiltered(self, os, filter):

        # Sort properties by name
        keys = self.sortedPropertyKeys()

        # Shortcut for all properties
        if filter.isAllProperties():
            for key in keys:
                for prop in self.getProperties(key):
                    prop.generate(os)
        elif filter.hasPropertyFilters():
            for key in keys:
                for prop in self.getProperties(key):
                    prop.generateFiltered(os, filter)


    def writePropertiesXML(self, node, namespace):

        properties = XML.SubElement(node, xmldefs.makeTag(namespace, xmldefs.properties))

        # Sort properties by name
        keys = self.sortedPropertyKeys()
        for key in keys:
            props = self.mProperties[key]
            for prop in props:
                prop.writeXML(properties, namespace)


    def writePropertiesFilteredXML(self, node, namespace, filter):

        props = XML.SubElement(node, xmldefs.makeTag(namespace, xmldefs.properties))

        # Sort properties by name
        keys = self.sortedPropertyKeys()

        # Shortcut for all properties
        if filter.isAllProperties():
            for key in keys:
                for prop in self.getProperties(key):
                    prop.writeXML(props, namespace)
        elif filter.hasPropertyFilters():
            for key in keys:
                for prop in self.getProperties(key):
                    prop.writeFilteredXML(props, namespace, filter)


    def loadPrivateValue(self, value_name):
        # Read it in from properties list and then delete the property from the
        # main list
        result = self.loadValueString(value_name)
        if (result is not None):
            self.removeProperties(value_name)
        return result


    def writePrivateProperty(self, os, key, value):
        prop = PyCalendarProperty(name=key, value=value)
        prop.generate(os)


    def editProperty(self, propname, propvalue):

        # Remove existing items
        self.removeProperties(propname)

        # Now create properties
        if propvalue:
            self.addProperty(PyCalendarProperty(name=propname, value=propvalue))