1
2
3 """
4 A PHP abstraction layer for Python
5
6 @package drupy
7 @see <a href='http://drupy.net'>Drupy Homepage</a>
8 @see <a href='http://drupal.org'>Drupal Homepage</a>
9 @note Drupy is a port of the Drupal project.
10 @note
11 This file currently is built to working only with CGI.
12 Eventually it will be constructed to work with WSGI
13 @author Brendon Crawford
14 @copyright 2008 Brendon Crawford
15 @contact message144 at users dot sourceforge dot net
16 @created 2008-02-05
17 @version 0.1
18 @note License:
19
20 This program is free software; you can redistribute it and/or
21 modify it under the terms of the GNU General Public License
22 as published by the Free Software Foundation; either version 2
23 of the License, or (at your option) any later version.
24
25 This program is distributed in the hope that it will be useful,
26 but WITHOUT ANY WARRANTY; without even the implied warranty of
27 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 GNU General Public License for more details.
29
30 You should have received a copy of the GNU General Public License
31 along with this program; if not, write to:
32
33 The Free Software Foundation, Inc.,
34 51 Franklin Street, Fifth Floor,
35 Boston, MA 02110-1301,
36 USA
37 """
38
39 __version__ = "$Revision: 1 $"
40
41
42
43
44 import sys
45 import StringIO
46 import time
47 import datetime
48 import os
49 import urlparse
50 import random
51 import copy
52 import re
53 import base64
54 import pickle
55 import hashlib
56 import zlib
57 import pprint
58 import htmlentitydefs
59 import cgi
60 import cgitb;
61 import urllib
62 from PIL import Image
63 from beaker import session
64
65
66
67
68
69 SERVER = None
70 GET = None
71 POST = None
72 REQUEST = None
73 SESSION = None
74
75
76
77
78 ENT_QUOTES = 1
79 E_USER_WARNING = 512
80 E_ALL = 6143
81 CRLF = "\r\n"
82
83
84
85
86
87
88
89 gzencode = None
90 gzdecode = None
91 sizeof = None
92 require_once = None
93 require = None
94 include_once = None
95 substr = None
96 preg_replace_callback = None
97 is_writeable = None
98 header = None
99 flush = None
102 """
103 Initiate superglobals and set output buffering
104 """
105 global SERVER, GET, POST, REQUEST, SESSION, OUTPUT
106 global __DRUPY_OUTPUT
107 global header, flush
108 global gzencode, gzdecode, sizeof, require_once, require, include_once, \
109 substr, preg_replace_callback, is_writeable
110
111 SERVER = __SuperGlobals.getSERVER()
112 GET = __SuperGlobals.getGET()
113 POST = __SuperGlobals.getPOST()
114 REQUEST = __SuperGlobals.getREQUEST(GET, POST)
115 SESSION = __SuperGlobals.getSESSION()
116
117 output = __Output(SERVER['WEB'])
118 header = output.header
119 flush = output.flush
120
121 gzencode = gzdeflate
122 gzdecode = gzinflate
123 sizeof = count
124 require_once = include
125 require = include
126 include_once = include
127 substr = array_slice
128 preg_replace_callback = preg_replace
129 is_writeable = is_writable
130 return
131
134 """
135 Std class
136 """
138
141 """
142 Reference class
143 """
144
145 """
146 Wrapper to setup a reference object
147 """
150
151 @staticmethod
153 """
154 Enforces a reference
155 @param data Object
156 @raise Exception
157 @return Bool
158 """
159 if not isinstance(data, Reference) and \
160 not isinstance(data, dict) and \
161 not isinstance(data, list) and \
162 not isinstance(data, tuple) and \
163 type(data).__name__ != 'instance':
164 raise Exception, \
165 "Argument must be a Reference, dict, list, tuple, or object"
166 else:
167 return True
168
170 """
171 Class to handle super globals
172 """
173
174 @staticmethod
176 """
177 _SERVER vars
178 If this is not being run from a webserver, we will simulate
179 the web server vars for CLI testing.
180 @return Dict
181 """
182 env = dict(os.environ)
183 if not env.has_key('DOCUMENT_ROOT'):
184 out = {
185 'WEB' : False,
186 'DOCUMENT_ROOT': env['PWD'],
187 'GATEWAY_INTERFACE': 'CGI/1.1',
188 'HTTP_ACCEPT': 'text/xml,application/xml,application/xhtml+xml,' + \
189 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
190 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
191 'HTTP_ACCEPT_ENCODING': 'gzip,deflate',
192 'HTTP_ACCEPT_LANGUAGE': 'en-us,en;q=0.5',
193 'HTTP_CONNECTION': 'keep-alive',
194 'HTTP_HOST': 'localhost',
195 'HTTP_KEEP_ALIVE': '300',
196 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; ' + \
197 'en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
198 'QUERY_STRING': '',
199 'REMOTE_ADDR': '127.0.0.1',
200 'REMOTE_PORT': '49999',
201 'REQUEST_METHOD': 'GET',
202 'REQUEST_URI': '/drupy.py',
203 'SCRIPT_FILENAME': env['PWD'] + '/drupy.py',
204 'SCRIPT_NAME': '/drupy.py',
205 'SERVER_ADDR': '127.0.0.1',
206 'SERVER_ADMIN': 'root@localhost',
207 'SERVER_NAME': 'localhost',
208 'SERVER_PORT': '80',
209 'SERVER_PROTOCOL': 'HTTP/1.1',
210 'SERVER_SIGNATURE': '',
211 'SERVER_SOFTWARE': 'Apache/2.2.8 (Unix) PHP/5.2.5'
212 }
213 return array_merge(env, out)
214 else:
215 env['WEB'] = True
216 return env
217
218 @staticmethod
220 """
221 _GET vars
222 @return Dict
223 """
224 return cgi.parse()
225
226 @staticmethod
228 """
229 _POST vars
230 @return Dict
231 """
232 a = {}
233 f = cgi.FieldStorage()
234 for i in f:
235 if isinstance(f[i], list):
236 a[i] = []
237 for j in f[i]:
238 a[i].append(j.value)
239 else:
240 a[i] = f[i].value
241 return a
242
243 @staticmethod
245 """
246 _REQUEST vars
247 @return Dict
248 """
249 return array_merge(get, post)
250
251 @staticmethod
253 """
254 _SESSION vars
255 @return Dict
256 """
257 return None
258
263 """
264 Handles drupy output functions
265 """
266
268 """
269 init
270 """
271 self._usebuffer = usebuffer
272 self._body = ""
273 self._headers = {}
274 if self._usebuffer:
275 cgitb.enable()
276 sys.stdout = self
277
279 """
280 Write body
281 @param data Str
282 """
283 if self._usebuffer:
284 self._body += data
285
287 """
288 Write headers
289 @param data Str
290 """
291 if self._usebuffer:
292 parts = re.split('\s*:\s*', str(data), 1)
293 parts_len = len(parts)
294 if parts_len > 0:
295 if parts_len == 1:
296 name = 'status'
297 value = parts[0]
298 elif parts_len == 2:
299 name = parts[0].lower()
300 value = parts[1]
301 self._headers[name] = value
302
304 """
305 Get header string
306 @param item Str
307 """
308 if self._headers.has_key(item):
309 if item == 'status':
310 out = "%s%s" % (self._headers[item], CRLF)
311 else:
312 out = "%s: %s%s" % (item, self._headers[item], CRLF)
313 if remove:
314 self._headers.pop(item)
315 else:
316 out = ''
317 return out
318
319
321 """
322 Set a header
323 @param item Str
324 @param val Str
325 @param check Bool
326 @return Bool
327 """
328 if not check or not self._headers.has_key(item):
329 self._headers[item] = val
330 return True
331 return False
332
333
335 """
336 Flush buffer
337 For now this is only constructed to work with CGI
338 Eventually this will need to be modified to work with WSGI
339 """
340 if self._usebuffer:
341 sys.stdout = sys.__stdout__
342
343 self._set_header('content-type', "text/html; Charset=UTF-8", True)
344
345 sys.stdout.write( self._get_header( 'content-type' ) )
346 for k,v in self._headers.items():
347 sys.stdout.write( self._get_header(k) )
348 sys.stdout.write( CRLF )
349 sys.stdout.write( self._body )
350
355 """
356 Sets user-level session storage functions
357 @param open_ Func
358 @param close_ Func
359 @param read_ Func
360 @param write_ Func
361 @param destroy_ Func
362 @param gc_ Func
363 @return Bool
364 """
365 pass
366
369 """
370 Initialize session data
371 @return Bool
372 """
373 global SESSION
374 SESSION = session.SessionObject(os.environ, \
375 type='file', data_dir='/tmp')._session()
376 header(SESSION.cookie)
377 return True
378
381 """
382 Get and/or set the current session name
383 @param name Str
384 @return Str
385 """
386 pass
387
388
389 -def define(name, val = None):
390 """
391 THIS FUNCTION SHOULD BE DEPRECATED EVENTUALLY
392 Sets globals variable
393 @param name Str
394 @param val Number,Str
395 @return Bool
396 """
397 v = {'name':name}
398 if \
399 isinstance(val, int) or \
400 isinstance(val, float) or \
401 isinstance(val, bool) or \
402 val is None:
403 v['val'] = val
404 elif isinstance(val, str):
405 v['val'] = "'%s'" % val
406 else:
407 return false
408 out = ("%(name)s = %(val)s") % v
409 exec(out, globals())
410 return True
411
414 """
415 Base 64 encode
416 """
417 return base64.encodestring(data);
418
421 """
422 Base 64 encode
423 """
424 return base64.decodestring(data);
425
428 """
429 Gets error.
430 This does not mimic the exact behaviour of the
431 corresponding PHP function
432
433 @return Tuple
434 @returnprop Int 0
435 @returnprop Str 1
436 @returnprop Str 2
437 @returnprop Int 3
438 @returnprop Dict 4
439 @returnprop Type 5
440 """
441 err = sys.exc_info();
442 return (
443 E_ALL,
444 err[1],
445 "NOT-AVAILABLE",
446 err[2].tb_lineno,
447 globals(),
448 err[0]
449 )
450
453 """
454 List files and directories inside the specified path
455
456 @param path_ Str
457 @return Tuple
458 """
459 return os.listdir
460
463 """
464 Sort on func
465 @param item Iterable
466 @param func Function
467 @return Iterable
468 """
469 return sort(item, func)
470
474 """
475 Call user func
476 @param func Function
477 @param args Tuple,List
478 @return Unknown
479 """
480 if callable(func):
481 return func(*tuple(args))
482 else:
483 return eval(func)(*tuple(args))
484
487 """
488 Call user func
489 @param func Function
490 @param arg Mixed
491 @return Unknown
492 """
493 if callable(func):
494 return func(*arg)
495 else:
496 return eval(func)(*arg)
497
501 """
502 Array filter
503 @param item Iterable
504 @param func Function
505 @return Iterable
506 """
507 return filter(func, item)
508
511 """
512 GD image size
513 @param filename Str
514 @return
515 """
516 img = Image.open(filename)
517 (w,h) = img.size
518 t = "IMAGETYPE_%S" % img.format
519 a = "width=\"%d\" height=\"%d\"" % img.size
520 return (w,h,t,a)
521
522
523 -def explode(delim, val, limit = None):
524 """
525 Splits string on delim
526 @param delim Str
527 @param val Str
528 @return Str
529 """
530 if limit != None:
531 return val.split(delim, limit)
532 else:
533 return val.split(delim)
534
537 """
538 Gets microtime
539 @return Str
540 """
541 (sec, usec) = str(time.time()).split('.')
542 return " ".join(['.' + usec, sec])
543
546 """
547 CHecks file is writeable
548 @param filename Str
549 @return Bool
550 """
551 return os.access(filename, os.W_OK)
552
555 """
556 Checks file is directory
557 @param filename Str
558 @param inplace Bool
559 @param empty_source Bool
560 @return Bool
561 """
562 return os.path.isdir(filename)
563
564
565 -def array_merge(a1, a2, inplace=False, empty_source=False):
566 """
567 Merges lists
568 @param a1 Dict,List
569 @param a2 Dict,List
570 @return Dict,List
571 """
572 if inplace:
573 out = a1
574 else:
575 out = copy.deepcopy(a1)
576 if empty_source:
577 for i in range(len(out)):
578 out.pop()
579 for k in a2:
580 out[k] = a2[k]
581 return out
582
585 """
586 Get keys
587 @param item Dict
588 @return List
589 """
590 return item.keys()
591
594 """
595 Has key
596 @param item Str
597 @param item Dict
598 @return Bool
599 """
600 return item.has_key(name);
601
602
603 -def isset(obj, val = None, searchGlobal = False, data = {}):
604 """
605 Check variable existance
606 @param obj Dict,List,Object
607 @param val Str,Int
608 @param searchGlobal Bool
609 """
610 sVal = None
611
612 if val is None:
613 return (obj is not None)
614
615 else:
616
617 if isinstance(obj, dict):
618
619 if searchGlobal:
620 sVal = array_merge(obj, globals())
621 else:
622 sVal = obj
623 if sVal.has_key(val):
624 data['val'] = obj[val]
625 data['msg'] = "Is Dict, Has Key, Globals: %s" % str(sVal)
626 return True
627 else:
628 data['val'] = None
629 data['msg'] = "Is Dict, Has Not Key, Globals: %s" % str(sVal)
630 return False
631
632 elif isinstance(obj, list) or isinstance(obj, tuple):
633 if (val < len(obj)):
634 data['val'] = obj[val]
635 data['msg'] = "Is Index, Has Key, Globals: %s" % str(sVal)
636 return True
637 else:
638 data['val'] = None
639 data['msg'] = "Is Index, Has Not Key, Globals: %s" % str(sVal)
640 return False
641
642 elif isinstance(obj, object):
643 if hasattr(obj, val):
644 data['val'] = getattr(obj, val)
645 data['msg'] = "Is Object, Has Key, Globals: %s" % str(sVal)
646 return True
647 else:
648 data['val'] = None
649 data['msg'] = "Is Object, Has Not Key, Globals: %s" % str(sVal)
650 return False
651
652 else:
653 data['Val'] = None
654 data['msg'] = "Is Unknown, Has Not Key Globals: %s" % str(sVal)
655 return False
656
659 """
660 Get time
661 @return Int
662 """
663 return time.time()
664
667 """
668 In array
669 @param val Str,Int
670 @param obj List,Dict,Object
671 @return Bool
672 """
673 return (val in obj)
674
677 """
678 Fills array
679 @param start Int
680 @param cnt Int
681 @param val Str
682 @return Dict
683 """
684 r = {}
685 i = start
686 while i <= (start + cnt):
687 r[i] = val
688 i += 1
689 return r
690
693 """
694 Shifts array
695 @param item List,Dict,Tuple
696 @return Mixed
697 """
698 if isinstance(item, list):
699 if len(item) > 0:
700 return item.pop(0)
701 else:
702 return None
703 elif isinstance(item, dict):
704 k = item.keys()
705 if len(k) > 0:
706 return item.pop(k[0])
707 else:
708 return None
709 else:
710 return None
711
714 """
715 Triggers error
716
717 @param data Str
718 """
719 print data
720 flush()
721 exit
722
725 """
726 Function exists
727 @param obj Dict,List,Object
728 @param val Str
729 @return Bool
730 """
731 if not isinstance(scope, dict):
732 return (hasattr(scope, val) and callable(getattr(scope, val)))
733 else:
734 return (scope.has_key(val) and callable(scope[val]))
735
738 """
739 html special chars
740 @param val Str
741 @return Str
742 """
743 out = ""
744 for i in range(0, len(val)):
745 num = ord(unicode(val[i]))
746 if htmlentitydefs.codepoint2name.has_key(num):
747 out += "&%s;" % htmlentitydefs.codepoint2name[num]
748 else:
749 out += val[i]
750 return out
751
755 """
756 Checks for empty
757 @param obj Any
758 @return Bool
759 """
760 return (not val)
761
762
763 -def strtr(text, items):
764 """
765 Translate characters
766 Inspired by snippet from Xavier Defrang
767 @see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
768 """
769 regex = re.compile("(%s)" % "|".join(map(re.escape, items.keys())))
770 out = regex.sub(lambda mo: items[mo.string[mo.start():mo.end()]], text)
771 return out
772
775 """
776 Check if uploaded file
777 @param filename Str
778 @return Bool
779 """
780 return True
781
785 """
786 Implodes
787 @param delim Str
788 @param items List
789 @return Str
790 """
791 return delim.join(items)
792
795 """
796 Array slice
797 @param items List,Dict
798 @param a1 Int
799 @param a2 Int
800 @return Mixed
801 """
802 if (a2 is None):
803 return items[a1:]
804 else:
805 return items[a1:a2]
806
807
808 -def rtrim(val, chars = None):
809 """
810 R Trim
811 @param val Str
812 @return Str
813 """
814 if chars != None:
815 return val.rstrip(chars)
816 else:
817 return val.rstrip()
818
819
820 -def ltrim(val, chars = None):
821 """
822 L trim
823 @param val Str
824 @return Str
825 """
826 if chars != None:
827 return val.lstrip(chars)
828 else:
829 return val.lstrip()
830
833 """
834 Check regular file
835 @param filename String
836 @return Bool
837 """
838 return os.path.isfile(filename)
839
842 """
843 Check file exists
844 @param filename Str
845 @return Bool
846 """
847 return os.path.exists(filename)
848
849
850 -def include(filename, scope = None):
851 """
852 Includes file
853 @param filename Str
854 @param scope Dict
855 @return Bool
856 """
857 if (scope != None):
858 execfile(filename, scope)
859 else:
860 execfile(filename, globals())
861 return True
862
865 """
866 Url decoder
867 @param val Str
868 @return Str
869 """
870 return urllib.unquote_plus(val)
871
874 """
875 Parse url
876 Urlparse doesnt support 'mysql' or 'mysqli' schemes
877 so, we need to add a fix for this.
878 @param url
879 @return Dict
880 """
881 scheme = url[0:url.find("://")]
882 if scheme not in (\
883 'file', 'ftp', 'gopher', 'hd1', 'http', 'https', \
884 'imap', 'mailto', 'mms', \
885 'news', 'nntp', 'prospero', 'rsync', 'rtsp', 'rtspu', \
886 'sftp', 'shttp', \
887 'sip', 'sips', 'snews', 'svn', 'svn+ssh', \
888 'telnet', 'wais'):
889 no_scheme = True
890 url = url.replace(scheme, 'http', 1)
891 else:
892 no_scheme = False
893 u = urlparse.urlparse(url)
894 hasuser = u.netloc.find('@')
895 d = {
896 'scheme' : (scheme if no_scheme else u.scheme),
897 'path' : u.path,
898 'query' : u.query,
899 'fragment' : u.fragment,
900 'user' : (u.username if u.username != None else ''),
901 'pass' : (u.password if u.password != None else ''),
902 'port' : (u.port if u.port != None else port),
903 'host' : u.netloc[((hasuser + 1) if (hasuser >= 0) else 0):]
904 }
905 return d
906
907
908 -def print_r(data, ret = False):
909 """
910 Recursive pretty printer
911 @param data Any
912 @param ret Bool
913 @return Bool,Str
914 """
915 if \
916 type(data).__name__ == 'instance' or \
917 isinstance(data, dict) or \
918 isinstance(data, list) or \
919 isinstance(data, tuple):
920 d = data
921 else:
922 try:
923 d = dict(data)
924 except:
925 try:
926 d = list(data)
927 except:
928 try:
929 d = tuple(data)
930 except:
931 d = data
932 if ret:
933 return pprint.PrettyPrinter().pformat(d)
934 else:
935 pprint.PrettyPrinter().pprint(d)
936 return True
937
941 """
942 Cast to object
943 @param dic Dict
944 @return Object
945 """
946 out = stdClass()
947 for i in dic:
948 setattr(out, i, dic[i])
949 return out
950
952 """
953 Cast to array
954 @param obj Object
955 @return Dict
956 """
957 out = {}
958 mag = '__'
959 for i in dir(obj):
960 if i[0:2] != mag and i[-2:] != mag:
961 out[i] = getattr(obj, i)
962 return out;
963
966 """
967 Get strlen
968 @param val Str
969 @return Int
970 """
971 return len(val)
972
975 """
976 Reverses list
977 @param items List
978 @return List
979 """
980 rItems = copy.deepcopy(items)
981 rItems.reverse()
982 return rItems
983
987 """
988 Escapes regular expression
989 @param val Str
990 @param delim Any
991 Not used
992 @return Str
993 """
994 return re.escape(val)
995
998 """
999 Convert PHP preg_match to Python matcher
1000 @param pat Str
1001 @param subject Str
1002 @param match Dict
1003 @return Dict
1004 @returnprop List match
1005 """
1006 if match != None:
1007 Reference.check(match)
1008 reg = __preg_setup(pat)
1009 searcher = reg.search(subject)
1010 if searcher is None:
1011 return 0
1012 else:
1013 g = list(searcher.groups())
1014 g.insert(0, ''.join(g))
1015 if match != None:
1016 for v in g:
1017 match.append( v )
1018 return len(g)
1019
1022 """
1023 Preg Match all
1024 @param pat Str
1025 @param subject Str
1026 @param &matches Reference
1027 @return Int
1028 """
1029 if matches != None:
1030 Reference.check(matches)
1031 reg = __preg_setup(pat)
1032 g = list( reg.finditer(subject) )
1033 if len(g) > 0:
1034 out = range(len(g[0].groups()))
1035 for i in range(len(out)):
1036 out[i] = []
1037 for j in g:
1038 out[i].append(j.group(i))
1039 array_merge(matches, out, True, True)
1040 return len(g)
1041 else:
1042 out = [[]]
1043 array_merge(matches, out, True, True)
1044 return 0
1045
1046
1047 -def uniqid(prefix = None, more_entropy = False):
1048 """
1049 Returns unique id
1050 @param prefix Str
1051 @param more_entropy Bool
1052 @return Str
1053 """
1054 out = ''
1055 num = (23 if more_entropy else 13)
1056 if prefix != None:
1057 random.seed(prefix)
1058 for i in range(0, num):
1059 out += random.choice(\
1060 'abcdefghijklmnopqrstuvwxyz' + \
1061 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + \
1062 '0123456789')
1063 return out
1064
1065
1066 -def mt_rand(min = 0, max = sys.maxint):
1067 """
1068 Random
1069 @param min Int
1070 @param max Int
1071 @return Int
1072 """
1073 return random.randint(min, max)
1074
1075
1076 """
1077 str replace wrapper
1078 @param pat Str
1079 @param rep Str
1080 @param subject Str
1081 @return Str
1082 """
1084 out = subject
1085 if isinstance(pat, list):
1086 repIsStr = isinstance(rep, list)
1087 for i in pat:
1088 if repIsStr:
1089 repStr = rep
1090 else:
1091 repStr = rep[i]
1092 out = __str_replace_str(pat[i], repStr, out)
1093 else:
1094 out = __str_replace_str(pat, rep, subject)
1095 return out
1096
1100 """
1101 preg_replace wrapper
1102 @param pat Str
1103 @param replace Str
1104 @param subject Str
1105 @return Str
1106 """
1107 out = subject
1108 if isinstance(pat, list):
1109 repIsStr = isinstance(rep, list)
1110 for i in pat:
1111 if repIsStr:
1112 repStr = rep
1113 else:
1114 repStr = rep[i]
1115 out = __preg_replace_str(pat[i], repStr, out)
1116 else:
1117 out = __preg_replace_str(pat, rep, subject)
1118 return out
1119
1122 """
1123 dir name
1124 @param path Str
1125 @return Str
1126 """
1127 return os.path.dirname(path)
1128
1129
1130 -def trim(val, chars = None):
1131 """
1132 trim whitespace
1133 @param val Str
1134 @return Str
1135 """
1136 if chars != None:
1137 return val.strip(chars)
1138 else:
1139 return val.strip()
1140
1143 """
1144 Gets array count
1145 @param item List,Dict
1146 @return Int
1147 """
1148 return len(item)
1149
1150 -def static(func, prop, val = None):
1151 """
1152 Sets a static var
1153 """
1154 if not hasattr(func, prop):
1155 setattr(func, prop, val)
1156 return False
1157 else:
1158 return True
1159
1162 """
1163 Determines whether or not is numeric
1164 @param val Any
1165 @return Bool
1166 """
1167 if \
1168 isinstance(val, int) or \
1169 isinstance(val, float):
1170 return True
1171 elif \
1172 isinstance(val, str) and \
1173 val.isdigit():
1174 return True
1175 else:
1176 return False
1177
1181 """
1182 Determines if string
1183 @param Any
1184 @return Bool
1185 """
1186 return (
1187 isinstance(val, unicode) or \
1188 isinstance(val, str)
1189 )
1190
1194 """
1195 Determines if "array"
1196 @param Any
1197 @return Bool
1198 """
1199 return (
1200 isinstance(val, tuple) or \
1201 isinstance(val, dict) or \
1202 isinstance(val, list)
1203 )
1204
1206 """
1207 Determnes if object
1208 """
1209 return isinstance(val, object)
1210
1213 """
1214 Is null
1215 @param val Any
1216 """
1217 return (val is None)
1218
1219
1220 -def strpos(haystack, needle):
1221 """
1222 Gets str pos
1223 @param haystack Str
1224 @param needle Str
1225 @return Int,Bool
1226 """
1227 pos = haystack.find(needle)
1228 if pos < 0:
1229 return False
1230 else:
1231 return pos
1232
1235 """
1236 Pretends to set an ini
1237 Actually just sets a global
1238 @param name Str
1239 @param val Str,Number,None,Bool
1240 @return Bool
1241 """
1242 define(name.replace('.', '_'), val)
1243 return True
1244
1247 """
1248 serializer
1249 @param obj Any
1250 @return Str
1251 """
1252 return pickle.dumps(obj)
1253
1256 """
1257 unserializer
1258 @param val Str
1259 @return Obj
1260 """
1261 return pickle.loads(val)
1262
1263
1264 -def defined(val, scope = globals()):
1265 """
1266 Checks for defined var
1267 """
1268 return isset(scope, val)
1269
1270
1271 -def gmdate(format, stamp = None):
1272 """
1273 GMT date
1274 @param format Str
1275 @param stamp Int
1276 @return Str
1277 """
1278 if stamp is None:
1279 stamp = time.time()
1280 dt = datetime.datetime.utcfromtimestamp(stamp)
1281 return dt.strftime(format)
1282
1285 """
1286 Strip slashes
1287 @param val Str
1288 @retun Str
1289 """
1290 return val.replace('\\', '')
1291
1294 """
1295 Add slashes
1296 @param val Str
1297 @return Str
1298 """
1299 return re.escape(val)
1300
1303 """
1304 md5
1305 @param val Str
1306 @return Str
1307 """
1308 return hashlib.md5(val).hexdigest()
1309
1311 """
1312 decompress
1313 @param val Str
1314 @return Str
1315 """
1316 return zlib.decompress(val)
1317
1320 """
1321 compress
1322 @param val Str
1323 @return Str
1324 """
1325 return zlib.compress(val)
1326
1330 """
1331 Pops item
1332 @param item
1333 @return Mixed
1334 """
1335 return item.pop()
1336
1340 """
1341 prepares pattern for python regex
1342 @param pat Str
1343 @return _sre.SRE_Pattern
1344 Regular Expression object
1345 """
1346 delim = pat[0]
1347 flg = 0
1348 pat = pat.lstrip(delim)
1349 i = len(pat) - 1
1350 while True:
1351 if i < 1:
1352 break
1353 else:
1354 if pat[i] == delim:
1355 pat = pat[0:len(pat)-1]
1356 break
1357 else:
1358 flg = flg | (eval('re.' + pat[i].upper(), globals()))
1359 pat = pat[0:len(pat)-1]
1360 i = i - 1
1361 return re.compile(pat, flg)
1362
1365 """
1366 str replace real
1367 @param pat Str
1368 @param rep Str
1369 @param subject Str
1370 @return Str
1371 """
1372 return subject.replace(pat, rep)
1373
1377 """
1378 Real preg replace
1379 @param pat Str
1380 @param replace Str
1381 @param subject Str
1382 @return Str
1383 """
1384 reg = __preg_setup(pat)
1385
1386 if callable(rep):
1387 def __callback(match):
1388 match_list = list(match.groups())
1389 match_list.insert(0, subject)
1390 match_list = tuple(match_list)
1391 o = rep(match_list)
1392 return o
1393 return reg.sub(__callback, subject)
1394
1395 else:
1396 return reg.sub(rep, subject)
1397
1398
1399
1400
1401
1402
1403 __init()
1404