This file is indexed.

/usr/lib/python3/dist-packages/khard/helpers.py is in khard 0.12.2-2.

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
# -*- coding: utf-8 -*-

import os
import random
import string
from datetime import datetime
from textwrap import dedent

from .object_type import ObjectType


def pretty_print(table, justify="L"):
    # get width for every column
    column_widths = [0] * table[0].__len__()
    offset = 3
    for row in table:
        for index, col in enumerate(row):
            width = len(str(col))
            if width > column_widths[index]:
                column_widths[index] = width
    table_row_list = []
    for row in table:
        single_row_list = []
        for col_index, col in enumerate(row):
            if justify == "R":  # justify right
                formated_column = str(col).rjust(column_widths[col_index] +
                                                 offset)
            elif justify == "L":  # justify left
                formated_column = str(col).ljust(column_widths[col_index] +
                                                 offset)
            elif justify == "C":  # justify center
                formated_column = str(col).center(column_widths[col_index] +
                                                  offset)
            single_row_list.append(formated_column)
        table_row_list.append(' '.join(single_row_list))
    return '\n'.join(table_row_list)


def list_to_string(input, delimiter):
    """
    converts list to string recursively so that nested lists are supported
    """
    if isinstance(input, list):
        flat_list = []
        for item in input:
            flat_list.append(list_to_string(item, delimiter))
        return delimiter.join(flat_list)
    return input


def string_to_list(input, delimiter):
    if isinstance(input, list):
        return input
    return [x.strip() for x in input.split(delimiter)]


def string_to_date(input):
    """convert string to date object"""
    # try date format --mmdd
    try:
        return datetime.strptime(input, "--%m%d")
    except ValueError:
        pass
    # try date format --mm-dd
    try:
        return datetime.strptime(input, "--%m-%d")
    except ValueError:
        pass
    # try date format yyyymmdd
    try:
        return datetime.strptime(input, "%Y%m%d")
    except ValueError:
        pass
    # try date format yyyy-mm-dd
    try:
        return datetime.strptime(input, "%Y-%m-%d")
    except ValueError:
        pass
    # try datetime format yyyymmddThhmmss
    try:
        return datetime.strptime(input, "%Y%m%dT%H%M%S")
    except ValueError:
        pass
    # try datetime format yyyy-mm-ddThh:mm:ss
    try:
        return datetime.strptime(input, "%Y-%m-%dT%H:%M:%S")
    except ValueError:
        pass
    # try datetime format yyyymmddThhmmssZ
    try:
        return datetime.strptime(input, "%Y%m%dT%H%M%SZ")
    except ValueError:
        pass
    # try datetime format yyyy-mm-ddThh:mm:ssZ
    try:
        return datetime.strptime(input, "%Y-%m-%dT%H:%M:%SZ")
    except ValueError:
        pass
    # try datetime format yyyymmddThhmmsstz where tz may look like -06:00
    try:
        return datetime.strptime(''.join(input.rsplit(":", 1)),
                                 "%Y%m%dT%H%M%S%z")
    except ValueError:
        pass
    # try datetime format yyyy-mm-ddThh:mm:sstz where tz may look like -06:00
    try:
        return datetime.strptime(''.join(input.rsplit(":", 1)),
                                 "%Y-%m-%dT%H:%M:%S%z")
    except ValueError:
        pass
    raise ValueError


def get_random_uid():
    return ''.join([random.choice(string.ascii_lowercase + string.digits)
                    for _ in range(36)])


def compare_uids(uid1, uid2):
    sum = 0
    for c1, c2 in zip(uid1, uid2):
        if c1 == c2:
            sum += 1
        else:
            break
    return sum


def file_modification_date(filename):
    t = os.path.getmtime(filename)
    return datetime.fromtimestamp(t)


def convert_to_yaml(
        name, value, indentation, indexOfColon, show_multi_line_character):
    """converts a value list into yaml syntax
    :param name: name of object (example: phone)
    :type name: str
    :param value: object contents
    :type value: str, list(str), list(list(str))
    :param indentation: indent all by number of spaces
    :type indentation: int
    :param indexOfColon: use to position : at the name string (-1 for no space)
    :type indexOfColon: int
    :param show_multi_line_character: option to hide "|"
    :type show_multi_line_character: boolean
    :returns: yaml formatted string array of name, value pair
    :rtype: list(str)
    """
    strings = []
    if isinstance(value, list):
        # special case for single item lists:
        if len(value) == 1 \
                and isinstance(value[0], str):
            # value = ["string"] should not be converted to
            # name:
            #   - string
            # but to "name: string" instead
            value = value[0]
        elif len(value) == 1 \
                and isinstance(value[0], list) \
                and len(value[0]) == 1 \
                and isinstance(value[0][0], str):
            # same applies to value = [["string"]]
            value = value[0][0]
    if isinstance(value, str):
        strings.append("%s%s%s: %s" % (
            ' ' * indentation, name, ' ' * (indexOfColon-len(name)),
            indent_multiline_string(value, indentation+4,
                                    show_multi_line_character)))
    elif isinstance(value, list):
        strings.append("%s%s%s: " % (
            ' ' * indentation, name, ' ' * (indexOfColon-len(name))))
        for outer in value:
            # special case for single item sublists
            if isinstance(outer, list) \
                    and len(outer) == 1 \
                    and isinstance(outer[0], str):
                # outer = ["string"] should not be converted to
                # -
                #   - string
                # but to "- string" instead
                outer = outer[0]
            if isinstance(outer, str):
                strings.append("%s- %s" % (
                    ' ' * (indentation+4), indent_multiline_string(
                        outer, indentation+8, show_multi_line_character)))
            elif isinstance(outer, list):
                strings.append("%s- " % (' ' * (indentation+4)))
                for inner in outer:
                    if isinstance(inner, str):
                        strings.append("%s- %s" % (
                            ' ' * (indentation+8), indent_multiline_string(
                                inner, indentation+12,
                                show_multi_line_character)))
    return strings


def convert_to_vcard(name, value, allowed_object_type):
    """converts user input into vcard compatible data structures
    :param name: object name, only required for error messages
    :type name: str
    :param value: user input
    :type value: str or list(str)
    :param allowed_object_type: set the accepted return type for vcard
        attribute
    :type allowed_object_type: enum of type ObjectType
    :returns: cleaned user input, ready for vcard or a ValueError
    :rtype: str or list(str)
    """
    if isinstance(value, str):
        if allowed_object_type == ObjectType.list_with_strings:
            raise ValueError(
                "Error: " + name + " must not contain a single string.")
        else:
            return value.strip()
    elif isinstance(value, list):
        if allowed_object_type == ObjectType.string:
            raise ValueError(
                "Error: " + name + " must not contain a list.")
        else:
            for entry in value:
                if not isinstance(entry, str):
                    raise ValueError(
                        "Error: " + name + " must not contain a nested list")
            # filter out empty list items and strip leading and trailing space
            return [x.strip() for x in value if x]
    else:
        if allowed_object_type == ObjectType.string:
            raise ValueError(
                "Error: " + name + " must be a string.")
        elif allowed_object_type == ObjectType.list_with_strings:
            raise ValueError(
                "Error: " + name + " must be a list with strings.")
        else:
            raise ValueError(
                "Error: " + name + " must be a string or a list with strings.")


def indent_multiline_string(input, indentation, show_multi_line_character):
    # if input is a list, convert to string first
    if isinstance(input, list):
        input = list_to_string(input, "")
    # format multiline string
    if "\n" in input:
        lines = ["|"] if show_multi_line_character else [""]
        for line in input.split("\n"):
            lines.append("%s%s" % (' ' * indentation, line.strip()))
        return '\n'.join(lines)
    return input.strip()


def get_new_contact_template(supported_private_objects=[]):
    formatted_private_objects = []
    if supported_private_objects:
        formatted_private_objects.append("")
        longest_key = max(supported_private_objects, key=len)
        for object in supported_private_objects:
            formatted_private_objects += convert_to_yaml(
                object, "", 12, len(longest_key)+1, True)

    # create template
    return dedent("""
        # name components
        # every entry may contain a string or a list of strings
        # format:
        #   First name : name1
        #   Additional : 
        #       - name2
        #       - name3
        #   Last name  : name4
        Prefix     : 
        First name : 
        Additional : 
        Last name  : 
        Suffix     : 

        # nickname
        # may contain a string or a list of strings
        Nickname : 

        # important dates
        # Formats:
        #   vcard 3.0 and 4.0: yyyy-mm-dd or yyyy-mm-ddTHH:MM:SS
        #   vcard 4.0 only: --mm-dd or text= string value
        # anniversary
        Anniversary : 
        # birthday
        Birthday : 

        # organisation
        # format:
        #   Organisation : company
        # or
        #   Organisation :
        #       - company1
        #       - company2
        # or
        #   Organisation :
        #       -
        #           - company
        #           - unit
        Organisation : 

        # organisation title and role
        # every entry may contain a string or a list of strings
        #
        # title at organisation
        # example usage: research scientist
        Title : 
        # role at organisation
        # example usage: project leader
        Role  : 

        # phone numbers
        # format:
        #   Phone:
        #       type1, type2: number
        #       type3:
        #           - number1
        #           - number2
        #       custom: number
        # allowed types:
        #   vcard 3.0: At least one of bbs, car, cell, fax, home, isdn, msg, modem,
        #                              pager, pcs, pref, video, voice, work
        #   vcard 4.0: At least one of home, work, pref, text, voice, fax, cell, video,
        #                              pager, textphone
        #   Alternatively you may use a single custom label (only letters).
        #   But beware, that not all address book clients will support custom labels.
        Phone :
            cell : 
            home : 

        # email addresses
        # format like phone numbers above
        # allowed types:
        #   vcard 3.0: At least one of home, internet, pref, work, x400
        #   vcard 4.0: At least one of home, internet, pref, work
        #   Alternatively you may use a single custom label (only letters).
        Email :
            home : 
            work : 

        # post addresses
        # allowed types:
        #   vcard 3.0: At least one of dom, intl, home, parcel, postal, pref, work
        #   vcard 4.0: At least one of home, pref, work
        #   Alternatively you may use a single custom label (only letters).
        Address :
            home :
                Box      : 
                Extended : 
                Street   : 
                Code     : 
                City     : 
                Region   : 
                Country  : 

        # categories or tags
        # format:
        #   Categories : single category
        # or
        #   Categories :
        #       - category1
        #       - category2
        Categories : 

        # web pages
        # may contain a string or a list of strings
        Webpage : 

        # private objects
        # define your own private objects in the vcard section of your khard config file
        # example:
        #   [vcard]
        #   private_objects = Jabber, Skype, Twitter
        # these objects are stored with a leading "X-" before the object name in the
        # vcard files.
        # every entry may contain a string or a list of strings
        Private :%s

        # notes
        # may contain a string or a list of strings
        # for multi-line notes use:
        #   Note : |
        #       line one
        #       line two
        Note : 
        """ % '\n'.join(formatted_private_objects))