blob: 501f596ee5d0f213e555f4eb5606d100b44b1ca8 [file] [log] [blame]
MG Mud User88f12472016-06-24 23:31:02 +02001// MorgenGrauen MUDlib
2//
3// simul_efun.c -- simul efun's
4//
5// $Id: simul_efun.c 7408 2010-02-06 00:27:25Z Zesstra $
6#pragma strict_types,save_types,rtt_checks
7#pragma no_clone,no_shadow,no_inherit
8#pragma pedantic,range_check,warn_deprecated
9#pragma warn_empty_casts,warn_missing_return,warn_function_inconsistent
10
11// Absolute Pfade erforderlich - zum Zeitpunkt, wo der Master geladen
12// wird, sind noch keine Include-Pfade da ...
13
14#define SNOOPLOGFILE "SNOOP"
15#define ASNOOPLOGFILE "ARCH/SNOOP"
16
Zesstradf157462018-07-31 21:49:59 +020017public int mkdirp(string dir);
18
MG Mud User88f12472016-06-24 23:31:02 +020019#include "/secure/config.h"
20#include "/secure/wizlevels.h"
21#include "/sys/snooping.h"
22#include "/sys/language.h"
23#include "/sys/thing/properties.h"
24#include "/sys/wizlist.h"
25#include "/sys/erq.h"
26#include "/sys/lpctypes.h"
27#include "/sys/daemon.h"
28#include "/sys/player/base.h"
29#include "/sys/thing/description.h"
30#include "/sys/container.h"
31#include "/sys/defines.h"
32#include "/sys/telnet.h"
33#include "/sys/objectinfo.h"
34#include "/sys/files.h"
35#include "/sys/strings.h"
36#include "/sys/time.h"
37#include "/sys/lpctypes.h"
38#include "/sys/notify_fail.h"
39#include "/sys/tls.h"
40#include "/sys/input_to.h"
41#include "/sys/object_info.h"
42
43/* function prototypes
44 */
45string dtime(int wann);
46varargs int log_file(string file, string txt, int size_to_break);
47int query_wiz_level(mixed player);
48nomask varargs int snoop(object me, object you);
49varargs string country(mixed ip, string num);
50int query_wiz_grp(mixed wiz);
51public varargs object deep_present(mixed what, object ob);
52nomask int secure_level();
53nomask string secure_euid();
54public nomask int process_call();
55nomask mixed __create_player_dummy(string name);
56varargs string replace_personal(string str, mixed *obs, int caps);
57
58
59//replacements for dropped efuns in LD
60#if !__EFUN_DEFINED__(extract)
61varargs string extract(string str, int from, int to);
62#endif
63#if !__EFUN_DEFINED__(slice_array)
64varargs mixed slice_array(mixed array, int from, int to);
65#endif
66#if !__EFUN_DEFINED__(member_array)
67int member_array(mixed item, mixed arraystring);
68#endif
69
70// Include the different sub 'modules' of the simul_efun
71#include __DIR__"debug_info.c"
72#include __DIR__"enable_commands.c"
73#include __DIR__"hash.c"
74#include __DIR__"object_info.c"
75#include __DIR__"query_editing.c"
76#include __DIR__"query_idle.c"
77#include __DIR__"query_input_pending.c"
78#include __DIR__"query_ip_name.c"
79#include __DIR__"query_limits.c"
80#include __DIR__"query_load_average.c"
81#include __DIR__"query_mud_port.c"
82#include __DIR__"query_once_interactive.c"
83#include __DIR__"query_snoop.c"
84#include __DIR__"set_heart_beat.c"
85#if __BOOT_TIME__ < 1456261859
86#include __DIR__"set_prompt.c"
87#endif
88#include __DIR__"shadow.c"
89#include __DIR__"livings.c"
90#include __DIR__"comm.c"
Zesstra19d657d2017-01-29 21:40:38 +010091#include __DIR__"files.c"
Zesstra7b2fbe72017-06-17 19:05:06 +020092#include __DIR__"seteuid.c"
MG Mud User88f12472016-06-24 23:31:02 +020093
94#define TO efun::this_object()
95#define TI efun::this_interactive()
96#define TP efun::this_player()
97#define PO efun::previous_object(0)
98#define LEVEL(x) query_wiz_level(x)
99#define NAME(x) capitalize(getuid(x))
100
101#define DEBUG(x) if (find_player("zesstra")) \
102 tell_object(find_player("zesstra"),x)
103
104mixed dtime_cache = ({-1,""});
105
106#ifdef IOSTATS
107struct iostat_s {
108 string oname;
109 int time;
110 int size;
111};
112mixed saveo_stat = ({ 0,allocate(200, 0) });
113mixed restoreo_stat = ({ 0,allocate(200,0) });
114//mixed writefile_stat = ({ 0,allocate(100,(<iostat_s>)) });
115//mixed readfile_stat = ({ 0,allocate(100,(<iostat_s>)) });
116//mixed log_stat = ({ 0,allocate(100,(<iostat_s>)) });
117
118mixed ___iostats(int type) {
119 switch(type) {
120 case 1:
121 return saveo_stat;
122 case 2:
123 return restoreo_stat;
124/* case 3:
125 return writefile_stat;
126 case 4:
127 return readfile_stat;
128 case 5:
129 return log_stat;
130 */
131 }
132 return 0;
133}
134#endif
135
136// Nicht jeder Magier muss die simul_efun entsorgen koennen.
137string NotifyDestruct(object caller) {
138 if( (caller!=this_object() && !ARCH_SECURITY) || process_call() ) {
139 return "Du darfst das simul_efun Objekt nicht zerstoeren!\n";
140 }
141 return 0;
142}
143
144public nomask void remove_interactive( object ob )
145{
146 if ( objectp(ob) && previous_object()
147 && object_name(previous_object())[0..7] != "/secure/"
148 && ((previous_object() != ob
149 && (ob != this_player() || ob != this_interactive()))
150 || (previous_object() == ob
151 && (this_player() && this_player() != ob
152 || this_interactive() && this_interactive() != ob)) ) )
153
154 log_file( "PLAYERDEST",
155 sprintf( "%s: %O ausgeloggt von PO %O, TI %O, TP %O\n",
156 dtime(time()), ob, previous_object(),
157 this_interactive(), this_player() ) );
158
159 efun::remove_interactive(ob);
160}
161
162
163void ___updmaster()
164{
165 object ob;
166
167 //sollte nicht jeder duerfen.
168 if (process_call() || !ARCH_SECURITY)
169 raise_error("Illegal use of ___updmaster()!");
170
171 write("Removing old master ... ");
172 foreach(string file:
173 get_dir("/secure/master/*.c",GETDIR_NAMES|GETDIR_UNSORTED|GETDIR_PATH)) {
174 if (ob = find_object(file))
175 efun::destruct(ob);
176 }
177 efun::destruct(efun::find_object("/secure/master"));
178 write("done.\nLoading again ... ");
179 load_object("/secure/master");
180
181 write("done.\n");
182}
183
184varargs string country(mixed ip, string num) {
185 mixed ret;
186
187 if(ret = (string)"/p/daemon/iplookup"->country(num || ip)) {
188 return ret;
189 } else return "???";
190}
191
192
193// * Snoopen und was dazugehoert
194static object find_snooped(object who)
195{
196 object *u;
197 int i;
198
199 for (i=sizeof(u=users())-1;i>=0;i--)
200 if (who==efun::interactive_info(u[i], II_SNOOP_NEXT))
201 return u[i];
202 return 0;
203}
204
205private string Lcut(string str) {
206 return str[5..11]+str[18..];
207}
208
209nomask varargs int snoop( object me, object you )
210{
211 int ret;
212 object snooper0, snooper, snooper2, snooper3;
213
214 if( !objectp(me) || me == you || !PO )
215 return 0;
216
217 snooper0 = find_snooped(me);
218
219 if(you){
220 if ( PO != me && query_wiz_grp(me) >= query_wiz_grp(geteuid(PO)) )
221 return 0;
222
223 if ( query_wiz_grp(me) <= query_wiz_grp(you) &&
224 !(you->QueryAllowSnoop(me)) )
225 if ( !IS_DEPUTY(me) || IS_ARCH(you) )
226 return 0;
227
228 if ( (snooper = efun::interactive_info(you, II_SNOOP_NEXT)) &&
229 query_wiz_grp(snooper) >= query_wiz_grp(me) ){
230 if ( (int)snooper->QueryProp(P_SNOOPFLAGS) & SF_LOCKED )
231 return 0;
232
233 tell_object( snooper, sprintf( "%s snooped jetzt %s.\n",
234 me->name(WER), you->name(WER) ) );
235
236 snooper2 = me;
237
238 while ( snooper3 = interactive_info(snooper2, II_SNOOP_NEXT) ){
239 tell_object( snooper,
240 sprintf( "%s wird seinerseits von %s gesnooped.\n"
241 ,snooper2->name(WER),
242 snooper3->name(WEM) ) );
243 snooper2 = snooper3;
244 }
245
246 efun::snoop( snooper, snooper2 );
247
248 if ( efun::interactive_info(snooper2, II_SNOOP_NEXT) != snooper )
249 tell_object( snooper, sprintf( "Du kannst %s nicht snoopen.\n",
250 snooper2->name(WEN) ) );
251 else{
252 tell_object( snooper, sprintf( "Du snoopst jetzt %s.\n",
253 snooper2->name(WEN) ) );
254 if ( !IS_DEPUTY(snooper) ){
255 log_file( SNOOPLOGFILE, sprintf("%s: %O %O %O\n",
256 dtime(time()),
257 snooper,
258 snooper2,
259 environment(snooper2) ),
260 100000 );
261 if (snooper0)
262 CHMASTER->send( "Snoop", snooper,
263 sprintf( "%s *OFF* %s (%O)",
264 capitalize(getuid(snooper)),
265 capitalize(getuid(snooper0)),
266 environment(snooper0) ) );
267
268 CHMASTER->send( "Snoop", snooper,
269 sprintf("%s -> %s (%O)",
270 capitalize(getuid(snooper)),
271 capitalize(getuid(snooper2)),
272 environment(snooper2)));
273 }
274 else{
275 log_file( ASNOOPLOGFILE, sprintf( "%s: %O %O %O\n",
276 dtime(time()),
277 snooper,
278 snooper2,
279 environment(snooper2) )
280 ,100000 );
281 }
282 }
283 }
284 else
285 if (snooper)
286 if ( !me->QueryProp(P_SNOOPFLAGS) & SF_LOCKED ){
287 printf( "%s wird bereits von %s gesnooped. Benutze das "
288 "\"f\"-Flag, wenn du dennoch snoopen willst.\n",
289 you->name(WER), snooper->name(WEM) );
290 return 0;
291 }
292
293 ret = efun::snoop( me, you );
294
295 if ( !IS_DEPUTY(me) && efun::interactive_info(you, II_SNOOP_NEXT) == me){
296 log_file( SNOOPLOGFILE, sprintf( "%s: %O %O %O\n",
297 Lcut(dtime(time())),
298 me, you, environment(you) ),
299 100000 );
300
301 if (snooper0)
302 CHMASTER->send( "Snoop", me,
303 sprintf( "%s *OFF* %s (%O).",
304 capitalize(getuid(me)),
305 capitalize(getuid(snooper0)),
306 environment(snooper0) ) );
307
308 CHMASTER->send( "Snoop", me, sprintf( "%s -> %s (%O).",
309 capitalize(getuid(me)),
310 capitalize(getuid(you)),
311 environment(you) ) );
312 }
313 else{
314 if ( efun::interactive_info(you, II_SNOOP_NEXT) == me ){
315 log_file( ASNOOPLOGFILE, sprintf( "%s: %O %O %O\n",
316 Lcut(dtime(time())),
317 me, you, environment(you) ),
318 100000 );
319 }
320 }
321
322 if ( ret && query_wiz_grp(me) <= query_wiz_grp(you) &&
323 !IS_DEPUTY(me) )
324 tell_object( you, "*** " + NAME(me) + " snoopt Dich!\n" );
325
326 return ret;
327 }
328 else {
329 if ( (me == PO ||
330 query_wiz_grp(geteuid(PO)) > query_wiz_grp(me) ||
331 (query_wiz_grp(geteuid(PO)) == query_wiz_grp(me) &&
332 efun::interactive_info(PO, II_SNOOP_NEXT) == me)) && snooper0 ){
333 if ( !IS_DEPUTY(me) ){
334 log_file( SNOOPLOGFILE, sprintf( "%s: %O %O %O *OFF*\n",
335 Lcut(dtime(time())), me,
336 snooper0,
337 environment(snooper0) ),
338 100000 );
339
340 CHMASTER->send( "Snoop", me,
341 sprintf( "%s *OFF* %s (%O).",
342 capitalize(getuid(me)),
343 capitalize(getuid(snooper0)),
344 environment(snooper0) ) );
345 }
346 else{
347 log_file( ASNOOPLOGFILE, sprintf( "%s: %O %O %O *OFF*\n",
348 Lcut(dtime(time())), me,
349 snooper0,
350 environment(snooper0) ),
351 100000 );
352 }
353
354 return efun::snoop(me);
355 }
356 }
357 return 0;
358}
359
360
361
362// * Emulation des 'alten' explode durch das neue
363string *old_explode(string str, string del) {
364 int s, t;
365 string *strs;
366
367 if (!stringp(str)) {
368 set_this_object(previous_object());
369 raise_error(sprintf(
370 "Invalid argument 1 to old_explode()! Expected <string>, got: "
371 "%.30O\n",str));
372 }
373 if (!stringp(del)) {
374 set_this_object(previous_object());
375 raise_error(sprintf(
376 "Invalid argument 2 to old_explode()! Expected <string>, got: "
377 "%.30O\n",del));
378 }
379 if(del == "")
380 return ({str});
381 strs=efun::explode(str, del);
382 t=sizeof(strs)-1;
383 while(s<=t && strs[s++] == "");s--;
384 while(t>=0 && strs[t--] == "");t++;
385 if(s<=t)
386 return strs[s..t];
387 return ({});
388}
389
390int file_time(string path) {
391 mixed *v;
392
393 set_this_object(previous_object());
394 if (sizeof(v=get_dir(path,GETDIR_DATES))) return v[0];
395 return(0); //sonst
396}
397
MG Mud User88f12472016-06-24 23:31:02 +0200398// * Magier-Level abfragen
399int query_wiz_level(mixed player) {
400 return (int)"/secure/master"->query_wiz_level(player);
401}
402
403#ifdef __ALISTS__
404// * Element aus Alist loeschen (by key)
405mixed *remove_alist(mixed key,mixed *alist)
406{
407 int i,j;
408
409 if (!pointerp(alist) || !sizeof(alist))
410 return alist;
411 if (!pointerp(alist[0]))
412 {
413 if ((i=assoc(key,alist))<0)
414 return alist;
415 return alist[0..i-1]+alist[i+1..];
416 }
417 i = assoc(key,alist[0]);
418 if ((i=assoc(key,alist[0]))<0)
419 return alist;
420 alist=alist[0..];
421 for (j=sizeof(alist)-1;j>=0;j--)
422 alist[j]=alist[j][0..i-1]+alist[j][i+1..];
423 return alist;
424}
425
426// * Element aus Alist loeschen (by pos)
427mixed *exclude_alist(int i,mixed *alist)
428{
429 int j;
430 if (!pointerp(alist) || !sizeof(alist) || i<0)
431 return alist;
432 if (!pointerp(alist[0]))
433 return alist[0..i-1]+alist[i+1..];
434 alist=alist[0..]; /* Create PHYSICAL copy of alist */
435 for (j=sizeof(alist)-1;j>=0;j--)
436 alist[j]=alist[j][0..i-1]+alist[j][i+1..];
437 return alist; /* order_alist is NOT necessary - see /doc/LPC/alist */
438}
439#endif // __ALISTS__
440
441// * German version of ctime()
442#define TAGE ({"Son","Mon","Die","Mit","Don","Fre","Sam"})
443#define MONATE ({"Jan","Feb","Mar","Apr","Mai","Jun","Jul","Aug",\
444 "Sep","Okt","Nov","Dez"})
445string dtime(int wann) {
446
447 if (wann == dtime_cache[0])
448 return(dtime_cache[1]);
449
450 int *lt = localtime(wann);
451 return sprintf("%s, %2d. %s %d, %02d:%02d:%02d",
452 TAGE[lt[TM_WDAY]], lt[TM_MDAY], MONATE[lt[TM_MON]],
453 lt[TM_YEAR],lt[TM_HOUR], lt[TM_MIN], lt[TM_SEC]);
454}
455
456// wenn strftime im Driver nicht existiert, ist dies hier ein Alias auf dtime(),
457// zwar stimmt das Format dann nicht, aber die Mudlib buggt nicht und schreibt
458// ein ordentliches Datum/Uhrzeit.
459#if !__EFUN_DEFINED__(strftime)
460varargs string strftime(mixed fmt, int clock, int localized) {
461 if (intp(clock) && clock >= 0)
462 return dtime(clock);
463 else if (intp(fmt) && fmt >= 0)
464 return dtime(fmt);
465
466 return dtime(time());
467}
468#endif //!__EFUN_DEFINED__(strftime)
469
470// * Shutdown mit zusaetzlichem logging
471nomask int shutdown(string reason)
472{
473 string name;
474 string obname;
475 string output;
476
477 if (!reason)
478 return 0;
479 if ( !ARCH_SECURITY && getuid(previous_object())!=ROOTID &&
480 object_name(previous_object())!="/obj/shut" )
481 {
482 write("You have no permission to shut down the gamedriver!\n");
483 return 0;
484 }
485 if ((this_interactive())&&(name=getuid(this_interactive())))
486 {
487 name=capitalize(name);
488 filter(users(),#'tell_object,//'
489 capitalize(name)+" faehrt das Spiel herunter!\n");
490 }
491 else
492 name="ANONYMOUS";
493 if (previous_object()) obname=capitalize(getuid(previous_object()));
494 output=name;
495 if (obname && name!=obname) output=output+" ("+obname+")";
496 if (previous_object()&&object_name(previous_object())=="/obj/shut"){
497 output+=" faehrt das Spiel via Armageddon herunter.\n";
498 output=dtime(time())+": "+output;
499 log_file("GAME_LOG",output+"\n",-1);
500 efun::shutdown();
501 return 1;
502 }
503 output=ctime(time())+": "+output+" faehrt das Spiel herunter.\n";
504 output+=" Grund: "+reason;
505 log_file("GAME_LOG",output+"\n",-1);
506 efun::shutdown();
507 return 1;
508}
509
510// * lowerchar
511
512int lowerchar(int char) {
513 if (char<'A' || char>'Z') return char;
514 return char+32;
515}
516
517// * upperstring
518
519string upperstring(string s)
520{
521#if __EFUN_DEFINED__(upper_case)
522 return(upper_case(s));
523#else
524 int i;
525 if (!stringp(s)) return 0;
526 for (i=sizeof(s)-1;i>=0;i--) s[i]=((s[i]<'a'||s[i]>'z')?s[i]:s[i]-32);
527 return s;
528#endif
529}
530
531// * lowerstring
532
533string lowerstring(string s)
534{
535 if (!stringp(s)) return 0;
536 return lower_case(s);
537}
538
539
540// * GD version
541string version()
542{
543 return __VERSION__;
544}
545
546// * break_string
547// stretch() -- stretch a line to fill a given width
548private string stretch(string s, int width) {
549 int len=sizeof(s);
550 if (len==width) return s;
551
552 // reine Leerzeilen, direkt zurueckgeben
553 string trimmed=trim(s,TRIM_LEFT," ");
554 if (trimmed=="") return s;
555 int start_spaces = len - sizeof(trimmed);
556
557 string* words = explode(trimmed, " ");
558 // der letzte kriegt keine Spaces
559 int word_count=sizeof(words) - 1;
560 // wenn Zeile nur aus einem Wort, wird das Wort zurueckgegeben
561 if (!word_count)
562 return " "*start_spaces + words[0];
563
564 int space_count = width - len;
565
566 int space_per_word=(word_count+space_count) / word_count;
567 // Anz.Woerter mit Zusatz-Space
568 int rest=(word_count+space_count) % word_count;
569 // Rest-Spaces Verteilen
570 foreach (int pos : rest) words[pos]+=" ";
571 return (" "*start_spaces) + implode( words, " "*space_per_word );
572}
573
574// aus Geschwindigkeitsgruenden hat der Blocksatz fuer break_string eine
575// eigene Funktion bekommen:
576private varargs string block_string(string s, int width, int flags) {
577 // wenn BS_LEAVE_MY_LFS, aber kein BS_NO_PARINDENT, dann werden Zeilen mit
578 // einem Leerzeichen begonnen.
579 // BTW: Wenn !BS_LEAVE_MY_LFS, hat der Aufrufer bereits alle \n durch " "
580 // ersetzt.
581 if ( (flags & BS_LEAVE_MY_LFS)
582 && !(flags & BS_NO_PARINDENT))
583 {
584 s = " "+regreplace(s,"\n","\n ",1);
585 }
586
587 // sprintf fuellt die letzte Zeile auf die Feldbreite (hier also
588 // Zeilenbreite) mit Fuellzeichen auf, wenn sie NICHT mit \n umgebrochen
589 // ist. Es wird an die letzte Zeile aber kein Zeilenumbruch angehaengt.
590 // Eigentlich ist das Auffuellen doof, aber vermutlich ist es unnoetig, es
591 // wieder rueckgaengig zu machen.
592 s = sprintf( "%-*=s", width, s);
593
594 string *tmp=explode(s, "\n");
595 // Nur wenn s mehrzeilig ist, Blocksatz draus machen. Die letzte Zeile wird
596 // natuerlich nicht gedehnt. Sie ist dafuer schon von sprintf() aufgefuellt
597 // worden. BTW: Die letzte Zeile endet u.U. noch nicht mit einem \n (bzw.
598 // nur dann, wenn BS_LEAVE_MY_LFS und der uebergebene Text schon nen \n am
599 // Ende der letzten Zeile hat), das macht der Aufrufer...
600 if (sizeof(tmp) > 1)
601 return implode( map( tmp[0..<2], #'stretch/*'*/, width ), "\n" )
602 + "\n" + tmp[<1];
603
604 return s;
605}
606
607public varargs string break_string(string s, int w, mixed indent, int flags)
608{
609 if ( !s || s == "" ) return "";
610
611 if ( !w ) w=78;
612
613 if( intp(indent) )
614 indent = indent ? " "*indent : "";
615
616 int indentlen=stringp(indent) ? sizeof(indent) : 0;
617
618 if (indentlen>w) {
619 set_this_object(previous_object());
620 raise_error(sprintf("break_string: indent longer %d than width %d\n",
621 indentlen,w));
622 // w=((indentlen/w)+1)*w;
623 }
624
625 if (!(flags & BS_LEAVE_MY_LFS))
626 s=regreplace( s, "\n", " ", 1 );
627
628 if ( flags & BS_SINGLE_SPACE )
629 s = regreplace( s, "(^|\n| ) *", "\\1", 1 );
630
631 string prefix="";
632 if (indentlen && flags & BS_PREPEND_INDENT) {
633 if (indentlen+sizeof(s) > w ||
634 (flags & BS_LEAVE_MY_LFS) && strstr(s,"\n")>-1) {
635 prefix=indent+"\n";
636 indent=(flags & BS_NO_PARINDENT) ? "" : " ";
637 indentlen=sizeof(indent);
638 }
639 }
640
641 if ( flags & BS_BLOCK ) {
642 /*
643 s = implode( map( explode( s, "\n" ),
644 #'block_string, w, indentlen, flags),
645 "" );
646 */
647 s = block_string( s , w - indentlen, flags );
648 }
649 else {
650 s = sprintf("%-1.*=s",w-indentlen,s);
651 }
652 if ( s[<1] != '\n' ) s += "\n";
653
654 if ( !indentlen ) return prefix + s;
655
656 string indent2 = ( flags & BS_INDENT_ONCE ) ? (" "*indentlen) :indent;
657
658 return prefix + indent +
659 regreplace( s[0..<2], "\n", "\n"+indent2, 1 ) + "\n";
660 /*
661 string *buf;
662
663 buf = explode( s, "\n" );
664 return prefix + indent + implode( buf[0..<2], "\n"+indent2 ) + buf[<1] + "\n";
665 */
666}
667
668// * Elemente aus mapping loeschen - mapping vorher kopieren
669
670mapping m_copy_delete(mapping m, mixed key) {
671 return m_delete(copy(m), key);
672}
673
674// * times
675int last_reboot_time()
676{
677 return __BOOT_TIME__;
678}
679
680int first_boot_time()
681{
682 return 701517600;
683}
684
685int exist_days()
686{
687 return (((time()-first_boot_time())/8640)+5)/10;
688}
689
690// * uptime :)
691string uptime()
692{
693 int t;
694 int tmp;
695 string s;
696
697 t=time()-__BOOT_TIME__;
698 s="";
699 if (t>=86400)
700 s+=sprintf("%d Tag%s, ",tmp=t/86400,(tmp==1?"":"e"));
701 if (t>=3600)
702 s+=sprintf("%d Stunde%s, ",tmp=(t=t%86400)/3600,(tmp==1?"":"n"));
703 if (t>60)
704 s+=sprintf("%d Minute%s und ",tmp=(t=t%3600)/60,(tmp==1?"":"n"));
705 return s+sprintf("%d Sekunde%s",t=t%60,(t==1?"":"n"));
706}
707
708// * Was tun bei 'dangling' lfun-closures ?
709void dangling_lfun_closure() {
710 raise_error("dangling lfun closure\n");
711}
712
713// * Sperren ausser fuer master/simul_efun
714
715#if __EFUN_DEFINED__(set_environment)
716nomask void set_environment(object o1, object o2) {
717 raise_error("Available only for root\n");
718}
719#endif
720
721nomask void set_this_player(object pl) {
722 raise_error("Available only for root\n");
723}
724
725#if __EFUN_DEFINED__(export_uid)
726nomask void export_uid(object ob) {
727 raise_error("Available only for root\n");
728}
729#endif
730
731// * Jetzt auch closures
732int process_flag;
733
734public nomask int process_call()
735{
736 if (process_flag>0)
737 return process_flag;
738 else return(0);
739}
740
741private nomask string _process_string(string str,object po) {
742 set_this_object(po);
743 return(efun::process_string(str));
744}
745
746nomask string process_string( mixed str )
747{
748 string tmp, err;
749 int flag;
750
751 if ( closurep(str) ) {
752 set_this_object( previous_object() );
753 return funcall(str);
754 }
755 else if (str==0)
756 return((string)str);
757 else if ( !stringp(str) ) {
758 return to_string(str);
759 }
760
761 if ( !(flag = process_flag > time() - 60))
762 process_flag=time();
763
764 err = catch(tmp = funcall(#'_process_string,str,previous_object()); publish);
765
766 if ( !flag )
767 process_flag=0;
768
769 if (err) {
770 // Verarbeitung abbrechen
771 set_this_object(previous_object());
772 raise_error(err);
773 }
774 return tmp;
775}
776
777// 'mkdir -p' - erzeugt eine komplette Hierarchie von Verzeichnissen.
778// wenn das Verzeichnis angelegt wurde oder schon existiert, wird 1
779// zurueckgeliefert, sonst 0.
780// Wirft einen Fehler, wenn das angebene Verzeichnis nicht absolut ist!
781public int mkdirp(string dir) {
782 // wenn es nur keinen fuehrenden / gibt, ist das ein Fehler.
783 if (strstr(dir, "/") != 0)
784 raise_error("mkdirp(): Pfad ist nicht absolute.\n");
785 // cut off trailing /...
786 if (dir[<1]=='/')
787 dir = dir[0..<2];
788
789 int fstat = file_size(dir);
790 // wenn es schon existiert, tun wir einfach so, als haetten wir es angelegt.
791 if (fstat == FSIZE_DIR)
792 return 1;
793 // wenn schon ne Datei existiert, geht es nicht.
794 if (fstat != FSIZE_NOFILE)
795 return 0;
796 // wenn es nur einen / gibt (den fuehrenden), dann ist es ein
797 // toplevel-verzeichnis, was direkt angelegt wird.
798 if (strrstr(dir,"/")==0) {
799 return funcall(bind_lambda(#'efun::mkdir, previous_object()), dir);
800 }
801
802 // mkdir() nicht direkt rufen, sondern vorher als closure ans aufrufende
803 // Objekt binden. Sonst laeuft die Rechtepruefung in valid_write() im Master
804 // unter der Annahme, dass die simul_efun.c mit ihrer root id was will.
805
806 // jetzt rekursiv die Verzeichnishierarchie anlegen. Wenn das erfolgreich
807 // ist, dann koennen wir jetzt mit mkdir das tiefste Verzeichnis anlegen
808 if (mkdirp(dir[0..strrstr(dir,"/")-1]) == 1)
809 return funcall(bind_lambda(#'efun::mkdir, previous_object()), dir);
810}
811
812
813// * Properties ggfs. mitspeichern
814mixed save_object(mixed name)
815{
816 mapping properties;
817 mapping save;
818 mixed index, res;
819 int i;
Zesstraf84b6272013-01-26 00:14:12 +0100820 string oldpath;
MG Mud User88f12472016-06-24 23:31:02 +0200821
822 // nur Strings und 0 zulassen
823 if ((!stringp(name) || !sizeof(name)) &&
824 (!intp(name) || name!=0)) {
825 set_this_object(previous_object());
826 raise_error(sprintf(
827 "Only non-empty strings and 0 may be used as filename in "
828 "sefun::save_object()! Argument was %O\n",name));
829 }
830
Zesstraf84b6272013-01-26 00:14:12 +0100831 if (stringp(name)) {
832 // abs. Pfad erzeugen. *seufz*
833 if (name[0]!='/')
834 name = "/" + name;
Zesstraf84b6272013-01-26 00:14:12 +0100835 // automatisch in LIBDATADIR speichern
836 if (strstr(name,"/"LIBDATADIR"/") != 0) {
Zesstrad43edf72017-01-31 15:43:35 +0100837 oldpath = name;
Zesstraf84b6272013-01-26 00:14:12 +0100838 name = "/"LIBDATADIR + name;
839 // wenn das Verzeichnis nicht existiert, ggf. anlegen
840 string dir = name[0..strrstr(name,"/")-1];
841 if (file_size(dir) != FSIZE_DIR) {
842 if (mkdirp(dir) != 1)
843 raise_error("save_object(): kann Verzeichnis " + dir
844 + " nicht anlegen!");
845 }
846 }
847 }
848
MG Mud User88f12472016-06-24 23:31:02 +0200849 save = m_allocate(0, 2);
850 properties = (mapping)previous_object()->QueryProperties();
851
852 if(mappingp(properties))
853 {
854 // delete all entries in mapping properties without SAVE flag!
855 index = m_indices(properties);
856 for(i = sizeof(index)-1; i>=0;i--)
857 {
858 if(properties[index[i], F_MODE] & SAVE)
859 {
860 save[index[i]] = properties[index[i]];
861 save[index[i], F_MODE] =
862 properties[index[i], F_MODE] &
863 (~(SETMNOTFOUND|QUERYMNOTFOUND|QUERYCACHED|SETCACHED));
864 }
865 }
866 }
867 else save = ([]);
868
869 // save object!
870 previous_object()->_set_save_data(save);
871 // format: wie definiert in config.h
Zesstraf84b6272013-01-26 00:14:12 +0100872 if (stringp(name)) {
MG Mud User88f12472016-06-24 23:31:02 +0200873 res = funcall(bind_lambda(#'efun::save_object, previous_object()), name,
874 __LIB__SAVE_FORMAT_VERSION__);
Zesstraf84b6272013-01-26 00:14:12 +0100875 // wenn erfolgreich und noch nen Savefile existiert, was nicht unter
876 // /data/ liegt, wird das geloescht.
877 if (!res && oldpath
878 && file_size(oldpath+".o") >= 0)
879 rm(oldpath+".o");
880 }
MG Mud User88f12472016-06-24 23:31:02 +0200881 else
882 res = funcall(bind_lambda(#'efun::save_object, previous_object()),
883 __LIB__SAVE_FORMAT_VERSION__);
Zesstraf84b6272013-01-26 00:14:12 +0100884
MG Mud User88f12472016-06-24 23:31:02 +0200885 previous_object()->_set_save_data(0);
886
887#ifdef IOSTATS
888 // Stats...
889 struct iostat_s stat = (<iostat_s>);
890 stat->oname = object_name(previous_object());
891 stat->time = time();
892 //stat->size = (int)object_info(previous_object(),OINFO_MEMORY,
893 // OIM_TOTAL_DATA_SIZE);
894 if (stringp(name))
895 stat->size = file_size(name + ".o");
896 else
897 stat->sizeof(res);
898 //debug_message("saveo: "+saveo_stat[0]+"\n");
899 saveo_stat[1][saveo_stat[0]] = stat;
900 saveo_stat[0] = (saveo_stat[0] + 1) % sizeof(saveo_stat[1]);
901 //debug_message("saveo 2: "+saveo_stat[0]+"\n");
902#endif
903
904 return res;
905}
906
907// * Auch Properties laden
908int restore_object(string name)
909{
910 int result;
911 mixed index;
912 mixed save;
913 mapping properties;
914 int i;
915 closure cl;
916
Zesstra94381a42017-01-29 22:37:52 +0100917 if (sizeof(name) < 1)
918 {
919 set_this_object(previous_object());
920 raise_error("Bad arg 1 to restore_object(): expected non-empty "
921 "'string'.\n");
922 }
923
Zesstra87166e12017-01-29 20:12:37 +0100924 // Wenn name vermutlich ein Pfad (also nicht mit #x:y anfaengt)
925 if (name[0] != '#')
926 {
927 // abs. Pfad erzeugen *seufz*
Zesstra0fbf95d2017-01-29 21:48:02 +0100928 if (name[0]!='/')
Zesstra87166e12017-01-29 20:12:37 +0100929 name = "/" + name;
Zesstraf84b6272013-01-26 00:14:12 +0100930
Bugfixb9fa6e82017-04-28 14:42:27 +0200931 // .c am Ende loeschen, sonst wird das File ggf. nicht gefunden.
932 if(name[<2..]==".c")
933 name=name[..<3];
934
Zesstra87166e12017-01-29 20:12:37 +0100935 // wenn kein /data/ vorn steht, erstmal gucken, ob das Savefile unter
936 // /data/ existiert. Wenn ja, wird das geladen.
Zesstra0fbf95d2017-01-29 21:48:02 +0100937 if (strstr(name,"/"LIBDATADIR"/") != 0)
Zesstra87166e12017-01-29 20:12:37 +0100938 {
939 string path = "/"LIBDATADIR + name;
940 if (file_size(path + ".o") >= 0)
941 name = path;
942 }
Zesstraf84b6272013-01-26 00:14:12 +0100943 }
944
MG Mud User88f12472016-06-24 23:31:02 +0200945 // get actual property settings (by create())
946 properties = (mapping)previous_object()->QueryProperties();
947
948// DEBUG(sprintf("RESTORE %O\n",name));
949 // restore object
950 result=funcall(bind_lambda(#'efun::restore_object, previous_object()), name);
951 //'))
952 //_get_save_data liefert tatsaechlich mixed zurueck, wenn das auch immer ein
953 //mapping sein sollte.
954 save = (mixed)previous_object()->_get_save_data();
955 if(mappingp(save))
956 {
957 index = m_indices(save);
958 for(i = sizeof(index)-1; i>=0; i--)
959 {
960 properties[index[i]] = save[index[i]];
961 properties[index[i], F_MODE] = save[index[i], F_MODE]
962 &~(SETCACHED|QUERYCACHED);
963 }
964 }
965 else properties = ([]);
966
967 // restore properties
968 funcall(
969 bind_lambda(
970 unbound_lambda(({'arg}), //'})
971 ({#'call_other,({#'this_object}),
972 "SetProperties",'arg})),//')
973 previous_object()),properties);
974 previous_object()->_set_save_data(0);
975
976#ifdef IOSTATS
977 // Stats...
978 //debug_message("restoreo: "+restoreo_stat[0]+"\n");
979 struct iostat_s stat = (<iostat_s>);
980 stat->oname = object_name(previous_object());
981 stat->time = time();
982 //stat->size = (int)object_info(previous_object(),OINFO_MEMORY,
983 // OIM_TOTAL_DATA_SIZE);
984 stat->size = file_size(name + ".o");
985 restoreo_stat[1][restoreo_stat[0]] = stat;
986
987 restoreo_stat[0] = (restoreo_stat[0] + 1) % sizeof(restoreo_stat[1]);
988#endif
989
990 return result;
991}
992
993// * HB eines Objektes ein/ausschalten
994int set_object_heart_beat(object ob, int flag)
995{
996 if (objectp(ob))
997 return funcall(bind_lambda(#'efun::configure_object,ob), ob, OC_HEART_BEAT, flag);
998}
999
1000// * Magierlevelgruppen ermitteln
1001int query_wiz_grp(mixed wiz)
1002{
1003 int lev;
1004
1005 lev=query_wiz_level(wiz);
1006 if (lev<SEER_LVL) return 0;
1007 if (lev>=GOD_LVL) return lev;
1008 if (lev>=ARCH_LVL) return ARCH_GRP;
1009 if (lev>=ELDER_LVL) return ELDER_GRP;
1010 if (lev>=LORD_LVL) return LORD_GRP;
1011 if (lev>=SPECIAL_LVL) return SPECIAL_GRP;
1012 if (lev>=DOMAINMEMBER_LVL) return DOMAINMEMBER_GRP;
1013 if (lev>=WIZARD_LVL) return WIZARD_GRP;
1014 if (lev>=LEARNER_LVL) return LEARNER_GRP;
1015 return SEER_GRP;
1016}
1017
1018mixed *wizlist_info()
1019{
1020 if (ARCH_SECURITY || !extern_call())
1021 return efun::wizlist_info();
1022 return 0;
1023}
1024
1025// * wizlist ausgeben
1026varargs void wizlist(string name, int sortkey ) {
1027
1028 if (!name)
1029 {
1030 if (this_player())
1031 name = getuid(this_player());
1032 if (!name)
1033 return;
1034 }
1035
1036 // Schluessel darf nur in einem gueltigen Bereich sein
1037 if (sortkey<WL_NAME || sortkey>=WL_SIZE) sortkey=WL_COST;
1038
1039 mixed** wl = efun::wizlist_info();
1040 // nach <sortkey> sortieren
1041 wl = sort_array(wl, function int (mixed a, mixed b)
1042 {return a[sortkey] < b[sortkey]; } );
1043
1044 // Summe ueber alle Kommandos ermitteln.
1045 int total_cmd, i;
1046 int pos=-1;
1047 foreach(mixed entry : wl)
1048 {
1049 total_cmd += entry[WL_COMMANDS];
1050 if (entry[WL_NAME] == name)
1051 pos = i;
1052 ++i;
1053 }
1054
1055 if (pos < 0 && name != "ALL" && name != "TOP100")
1056 return;
1057
1058 if (name == "TOP100")
1059 {
1060 if (sizeof(wl) > 100)
1061 wl = wl[0..100];
1062 else
1063 wl = wl;
1064 }
1065 // um name herum schneiden
1066 else if (name != "ALL")
1067 {
1068 if (sizeof(wl) <= 21)
1069 wl = wl;
1070 else if (pos + 10 < sizeof(wl) && pos - 10 > 0)
1071 wl = wl[pos-10..pos+10];
1072 else if (pos <=21)
1073 wl = wl[0..20];
1074 else if (pos >= sizeof(wl) - 21)
1075 wl = wl[<21..];
1076 else
1077 wl = wl;
1078 }
1079
1080 write("\nWizard top score list\n\n");
1081 if (total_cmd == 0)
1082 total_cmd = 1;
1083 printf("%-20s %-6s %-3s %-17s %-6s %-6s %-6s\n",
1084 "EUID", "cmds", "%", "Costs", "HB", "Arrays","Mapp.");
1085 foreach(mixed e: wl)
1086 {
1087 printf("%-:20s %:6d %:2d%% [%:6dk,%:6dG] %:6d %:6d %:6d\n",
1088 e[WL_NAME], e[WL_COMMANDS], e[WL_COMMANDS] * 100 / total_cmd,
1089 e[WL_COST] / 1000, e[WL_TOTAL_GIGACOST],
1090 e[WL_HEART_BEATS], e[WL_ARRAY_TOTAL], e[WL_MAPPING_TOTAL]
1091 );
1092 }
1093 printf("\nTotal %7d (%d)\n\n", total_cmd, sizeof(wl));
1094}
1095
1096
1097// Ab hier folgen Hilfsfunktionen fuer call_out() bzw. fuer deren Begrenzung
1098
1099// ermittelt das Objekt des Callouts.
1100private object _call_out_obj( mixed call_out ) {
1101 return pointerp(call_out) ? call_out[0] : 0;
1102}
1103
1104private void _same_object( object ob, mapping m ) {
1105 // ist nicht so bloed, wie es aussieht, s. nachfolgede Verwendung von m
1106 if ( m[ob] )
1107 m[ob] += ({ ob });
1108 else
1109 m[ob] = ({ ob });
1110}
1111
1112// alle Objekte im Mapping m zusammenfassen, die den gleichen Loadname (Name der
1113// Blueprint) haben, also alle Clones der BP, die Callouts laufen haben.
1114// Objekte werden auch mehrfach erfasst, je nach Anzahl ihrer Callouts.
1115private void _same_path( object key, object *obs, mapping m ) {
1116 string path;
1117 if (!objectp(key) || !pointerp(obs)) return;
1118
1119 path = load_name(key);
1120
1121 if ( m[path] )
1122 m[path] += obs;
1123 else
1124 m[path] = obs;
1125}
1126
1127// key kann object oder string sein.
1128private int _too_many( mixed key, mapping m, int i ) {
1129 return sizeof(m[key]) >= i;
1130}
1131
1132// alle Objekte in obs zerstoeren und Fehlermeldung ausgeben. ACHTUNG: Die
1133// Objekte werden idR zu einer BP gehoeren, muessen aber nicht! In dem Fall
1134// wird auf der Ebene aber nur ein Objekt in der Fehlermeldung erwaehnt.
1135private void _destroy( mixed key, object *obs, string text, int uid ) {
1136 if (!pointerp(obs)) return;
1137 // Array mit unique Eintraege erzeugen.
1138 obs = m_indices( mkmapping(obs) );
1139 // Fehlermeldung auf der Ebene ausgeben, im catch() mit publish, damit es
1140 // auf der Ebene direkt scrollt, der backtrace verfuegbar ist (im
1141 // gegensatz zur Loesung mittels Callout), die Ausfuehrung aber weiter
1142 // laeuft.
1143 catch( efun::raise_error(
1144 sprintf( text,
1145 uid ? (string)master()->creator_file(key) : key,
1146 sizeof(obs), object_name(obs[<1]) ) );publish);
1147 // Und weg mit dem Kram...
1148 filter( obs, #'efun::destruct/*'*/ );
1149}
1150
1151// Alle Objekt einer UID im Mapping m mit UID als KEys zusammenfassen. Objekt
1152// sind dabei nicht unique.
1153private void _same_uid( string key, object *obs, mapping m, closure cf ) {
1154 string uid;
1155
1156 if ( !pointerp(obs) || !sizeof(obs) )
1157 return;
1158
1159 uid = funcall( cf, key );
1160
1161 if ( m[uid] )
1162 m[uid] += obs; // obs ist nen Array
1163 else
1164 m[uid] = obs;
1165}
1166
1167private int _log_call_out(mixed co)
1168{
1169 log_file("TOO_MANY_CALLOUTS",
1170 sprintf("%s::%O (%d)\n",object_name(co[0]),co[1],co[2]),
1171 200000);
1172 return 0;
1173}
1174
1175private int last_callout_log=0;
1176
1177nomask varargs void call_out( varargs mixed *args )
1178{
1179 mixed tmp, *call_outs;
1180
1181 // Bei >600 Callouts alle Objekte killen, die mehr als 30 Callouts laufen
1182 // haben.
1183 if ( efun::driver_info(DI_NUM_CALLOUTS) > 600
1184 && geteuid(previous_object()) != ROOTID )
1185 {
1186 // Log erzeugen...
1187 if (last_callout_log <
1188 efun::driver_info(DI_NUM_HEARTBEAT_TOTAL_CYCLES) - 10
1189 && get_eval_cost() > 200000)
1190 {
1191 last_callout_log = efun::driver_info(DI_NUM_HEARTBEAT_TOTAL_CYCLES);
1192 log_file("TOO_MANY_CALLOUTS",
1193 sprintf("\n%s: ############ Too many callouts: %d ##############\n",
1194 strftime("%y%m%d-%H%M%S"),
1195 efun::driver_info(DI_NUM_CALLOUTS)));
1196 filter(efun::call_out_info(), #'_log_call_out);
1197 }
1198 // Objekte aller Callouts ermitteln
1199 call_outs = map( efun::call_out_info(), #'_call_out_obj );
1200 mapping objectmap = ([]);
1201 filter( call_outs, #'_same_object, &objectmap );
1202 // Master nicht grillen...
1203 efun::m_delete( objectmap, master(1) );
1204 // alle Objekte raussuchen, die zuviele haben...
1205 mapping res = filter_indices( objectmap, #'_too_many, objectmap, 29 );
1206 // und ueber alle Keys gehen, an _destroy() werden Key und Array mit
1207 // Objekten uebergeben (in diesem Fall sind Keys und Array mit
1208 // Objekten jeweils das gleiche Objekt).
1209 if ( sizeof(res) )
1210 walk_mapping(res, #'_destroy, "CALL_OUT overflow by single "
1211 "object [%O]. Destructed %d objects. [%s]\n", 0 );
1212
1213 // Bei (auch nach dem ersten Aufraeumen noch) >800 Callouts alle
1214 // Objekte killen, die mehr als 50 Callouts laufen haben - und
1215 // diesmal zaehlen Clones nicht eigenstaendig! D.h. es werden alle
1216 // Clones einer BP gekillt, die Callouts laufen haben, falls alle
1217 // diese Objekte _zusammen_ mehr als 50 Callouts haben!
1218 if ( efun::driver_info(DI_NUM_CALLOUTS) > 800 ) {
1219 // zerstoerte Objekte von der letzten Aktion sind in objectmap nicht
1220 // mehr drin, da sie dort als Keys verwendet wurden.
1221 mapping pathmap=([]);
1222 // alle Objekt einer BP in res sortieren, BP-Name als Key, Arrays
1223 // von Objekten als Werte.
1224 walk_mapping( objectmap, #'_same_path, &pathmap);
1225 // alle BPs (und ihre Objekte) raussuchen, die zuviele haben...
1226 res = filter_indices( pathmap, #'_too_many/*'*/, pathmap, 50 );
1227 // und ueber alle Keys gehen, an _destroy() werden die Clones
1228 // uebergeben, die Callouts haben.
1229 if ( sizeof(res) )
1230 walk_mapping( res, #'_destroy/*'*/, "CALL_OUT overflow by file "
1231 "'%s'. Destructed %d objects. [%s]\n", 0 );
1232
1233 // Wenn beide Aufraeumarbeiten nichts gebracht haben und immer
1234 // noch >1000 Callouts laufen, werden diesmal alle Callouts
1235 // einer UID zusammengezaehlt.
1236 // Alle Objekte einer UID, die es in Summe aller ihrer Objekt mit
1237 // Callouts auf mehr als 100 Callouts bringt, werden geroestet.
1238 if (efun::driver_info(DI_NUM_CALLOUTS) > 1000)
1239 {
1240 // das nach BP-Namen vorgefilterte Mapping jetzt nach UIDs
1241 // zusammensortieren. Zerstoerte Clones filter _same_uid()
1242 // raus.
1243 mapping uidmap=([]);
1244 walk_mapping( pathmap, #'_same_uid, &uidmap,
1245 symbol_function( "creator_file",
1246 "/secure/master" ) );
1247 // In res nun UIDs als Keys und Arrays von Objekten als Werte.
1248 // Die rausfiltern, die mehr als 100 Objekte (non-unique, d.h.
1249 // 100 Callouts!) haben.
1250 res = filter_indices( uidmap, #'_too_many, uidmap, 100 );
1251 // und erneut ueber die Keys laufen und jeweils die Arrays mit
1252 // den Objekten zur Zerstoerung an _destroy()...
1253 if ( sizeof(res) )
1254 walk_mapping( res, #'_destroy, "CALL_OUT overflow by "
1255 "UID '%s'. Destructed %d objects. [%s]\n",
1256 1 );
1257 }
1258 }
1259 }
1260
1261 // Falls das aufrufende Objekt zerstoert wurde beim Aufraeumen
1262 if ( !previous_object() )
1263 return;
1264
1265 set_this_object( previous_object() );
1266 apply( #'efun::call_out, args );
1267 return;
1268}
1269
1270mixed call_out_info() {
1271
1272 object po = previous_object();
1273 mixed coi = efun::call_out_info();
1274
1275 // ungefilterten Output nur fuer bestimmte Objekte, Objekte in /std oder
1276 // /obj haben die BackboneID.
1277 if (query_wiz_level(getuid(po)) >= ARCH_LVL
1278 || (string)master()->creator_file(load_name(po)) == BACKBONEID ) {
1279 return coi;
1280 }
1281 else {
1282 return filter(coi, function mixed (mixed arr) {
1283 if (pointerp(arr) && arr[0]==po)
1284 return 1;
1285 else return 0; });
1286 }
1287}
1288
1289// * Zu einer closure das Objekt, an das sie gebunden ist, suchen
1290// NICHT das Objekt, was ggf. die lfun definiert!
1291mixed query_closure_object(closure c) {
1292 return
1293 CLOSURE_IS_UNBOUND_LAMBDA(get_type_info(c, 1)) ?
1294 0 :
1295 (to_object(c) || -1);
1296}
1297
1298// * Wir wollen nur EIN Argument ... ausserdem checks fuer den Netztotenraum
1299varargs void move_object(mixed what, mixed where)
1300{
1301 object po,tmp;
1302
1303 po=previous_object();
1304 if (!where)
1305 {
1306 where=what;
1307 what=po;
1308 }
1309 if (((stringp(where) && where==NETDEAD_ROOM ) ||
1310 (objectp(where) && where==find_object(NETDEAD_ROOM))) &&
1311 objectp(what) && object_name(what)!="/obj/sperrer")
1312 {
1313 if (!query_once_interactive(what))
1314 {
1315 what->remove();
1316 if (what) destruct(what);
1317 return;
1318 }
1319 if (living(what) || interactive(what))
1320 {
1321 log_file("NDEAD2",sprintf("TRYED TO MOVE TO NETDEAD: %O\n",what));
1322 return;
1323 }
1324 set_object_heart_beat(what,0);
1325 }
1326 tmp=what;
1327 while (tmp=environment(tmp))
1328 // Ja. Man ruft die _set_xxx()-Funktionen eigentlich nicht direkt auf.
1329 // Aber das Lichtsystem ist schon *so* rechenintensiv und gerade der
1330 // P_LAST_CONTENT_CHANGE-Cache wird *so* oft benoetigt, dass es mir
1331 // da um jedes bisschen Rechenzeit geht.
1332 // Der Zweck heiligt ja bekanntlich die Mittel. ;-)
1333 //
1334 // Tiamak
1335 tmp->_set_last_content_change();
1336 funcall(bind_lambda(#'efun::move_object,po),what,where);
1337 if (tmp=what)
1338 while (tmp=environment(tmp))
1339 tmp->_set_last_content_change();
1340}
1341
1342
1343void start_simul_efun() {
1344 mixed *info;
1345
1346 // Falls noch nicht getan, extra_wizinfo initialisieren
1347 if ( !pointerp(info = get_extra_wizinfo(0)) )
1348 set_extra_wizinfo(0, info = allocate(BACKBONE_WIZINFO_SIZE));
1349
1350 InitLivingData(info);
1351
1352 set_next_reset(10); // direkt mal aufraeumen
1353}
1354
1355protected void reset() {
1356 set_next_reset(7200);
1357 CleanLivingData();
1358}
1359
1360#if !__EFUN_DEFINED__(absolute_hb_count)
1361int absolute_hb_count() {
1362 return efun::driver_info(DI_NUM_HEARTBEAT_TOTAL_CYCLES);
1363}
1364#endif
1365
1366void __set_environment(object ob, mixed target)
1367{
1368 string path;
1369 object obj;
1370
1371 if (!objectp(ob))
1372 return;
1373 if (!IS_ARCH(geteuid(previous_object())) || !ARCH_SECURITY )
1374 return;
1375 if (objectp(target))
1376 {
1377 efun::set_environment(ob,target);
1378 return;
1379 }
1380 path=(string)MASTER->_get_path(target,this_interactive());
1381 if (stringp(path) && file_size(path+".c")>=0 &&
1382 !catch(load_object(path);publish) )
1383 {
1384 obj=find_object(path);
1385 efun::set_environment(ob,obj);
1386 return;
1387 }
1388}
1389
1390void _dump_wizlist(string file, int sortby) {
1391 int i;
1392 mixed *a;
1393
1394 if (!LORD_SECURITY)
1395 return;
1396 if (!master()->valid_write(file,geteuid(previous_object()),"write_file"))
1397 {
1398 write("NO WRITE PERMISSION\n");
1399 return;
1400 }
1401 a = wizlist_info();
1402 a = sort_array(a, lambda( ({'a,'b}),
1403 ({#'<,
1404 ({#'[,'a,sortby}),
1405 ({#'[,'b,sortby})
1406 })));
1407 rm(file);
1408 for (i=sizeof(a)-1;i>=0;i--)
1409 write_file(file,sprintf("%-11s: eval=%-8d cmds=%-6d HBs=%-5d array=%-5d mapping=%-7d\n",
1410 a[i][WL_NAME],a[i][WL_TOTAL_COST],a[i][WL_COMMANDS],a[i][WL_HEART_BEATS],
1411 a[i][WL_ARRAY_TOTAL],a[i][WL_CALL_OUT]));
1412}
1413
1414public varargs object deep_present(mixed what, object ob) {
1415
1416 if(!objectp(ob))
1417 ob=previous_object();
1418 // Wenn ein Objekt gesucht wird: Alle Envs dieses Objekts ermitteln und
1419 // schauen, ob in diesen ob vorkommt. Dann ist what in ob enthalten.
1420 if(objectp(what)) {
1421 object *envs=all_environment(what);
1422 // wenn ob kein Environment hat, ist es offensichtlich nicht in what
1423 // enthalten.
1424 if (!pointerp(envs)) return 0;
1425 if (member(envs, ob) != -1) return what;
1426 }
1427 // sonst wirds teurer, ueber alle Objekte im (deep) Inv laufen und per id()
1428 // testen. Dabei muss aber die gewuenschte Nr. ("flasche 3") abgeschnitten
1429 // werden und selber gezaehlt werden, welche das entsprechende Objekt ist.
1430 else if (stringp(what)) {
1431 int cnt;
1432 string newwhat;
1433 if(sscanf(what,"%s %d",newwhat,cnt)!=2)
1434 cnt=1;
1435 else
1436 what=newwhat;
1437 foreach(object invob: deep_inventory(ob)) {
1438 if (invob->id(what) && !--cnt)
1439 return invob;
1440 }
1441 }
1442 else {
1443 set_this_object(previous_object());
1444 raise_error(sprintf("Wrong argument 1 to deep_present(). "
1445 "Expected \"object\" or \"string\", got %.50O.\n",
1446 what));
1447 }
1448 return 0;
1449}
1450
1451mapping dump_ip_mapping()
1452{
1453 return 0;
1454}
1455
1456nomask void swap(object obj)
1457{
1458 write("Your are not allowed to swap objects by hand!\n");
1459 return;
1460}
1461
1462nomask varargs void garbage_collection(string str)
1463{
1464 if(previous_object()==0 || !IS_ARCH(geteuid(previous_object()))
1465 || !ARCH_SECURITY)
1466 {
1467 write("Call GC now and the mud will crash in 5-6 hours. DONT DO IT!\n");
1468 return;
1469 }
1470 else if (stringp(str))
1471 {
1472 return efun::garbage_collection(str);
1473 }
1474 else
1475 return efun::garbage_collection();
1476}
1477
1478varargs void notify_fail(mixed nf, int prio) {
1479 object po,oldo;
1480 int oldprio;
1481
1482 if (!PL || !objectp(po=previous_object())) return;
1483 if (!stringp(nf) && !closurep(nf)) {
1484 set_this_object(po);
1485 raise_error(sprintf(
1486 "Only strings and closures allowed for notify_fail! "
1487 "Argument was: %.50O...\n",nf));
1488 }
1489
1490 // falls ein Objekt bereits nen notify_fail() setzte, Prioritaeten abschaetzen
1491 // und vergleichen.
1492 if (objectp(oldo=query_notify_fail(1)) && po!=oldo) {
1493 if (!prio) {
1494 //Prioritaet dieses notify_fail() 'abschaetzen'
1495 if (po==PL) // Spieler-interne (soul-cmds)
1496 prio=NF_NL_OWN;
1497 else if (living(po))
1498 prio=NF_NL_LIVING;
1499 else if ((int)po->IsRoom())
1500 prio=NF_NL_ROOM;
1501 else
1502 prio=NF_NL_THING;
1503 }
1504 //Prioritaet des alten Setzers abschaetzen
1505 if (oldo==PL)
1506 oldprio=NF_NL_OWN;
1507 else if (living(oldo))
1508 oldprio=NF_NL_LIVING;
1509 else if ((int)oldo->IsRoom())
1510 oldprio=NF_NL_ROOM;
1511 else
1512 oldprio=NF_NL_THING;
1513 }
1514 else // wenn es noch kein Notify_fail gibt:
1515 oldprio=NF_NL_NONE;
1516
1517 //vergleichen und ggf. setzen
1518 if (prio >= oldprio) {
1519 set_this_object(po);
1520 efun::notify_fail(nf);
1521 }
1522
1523 return;
1524}
1525
1526void _notify_fail(string str)
1527{
1528 //query_notify_fail() benutzen, um das Objekt
1529 //des letzten notify_fail() zu ermitteln
1530 object o;
1531 if ((o=query_notify_fail(1)) && o!=previous_object())
1532 return;
1533 //noch kein notify_fail() fuer dieses Kommando gesetzt, auf gehts.
1534 set_this_object(previous_object());
1535 efun::notify_fail(str);
1536 return;
1537}
1538
1539string time2string( string format, int zeit )
1540{
1541 int i,ch,maxunit,dummy;
1542 string *parts, fmt;
1543
1544 int secs = zeit;
1545 int mins = (zeit/60);
1546 int hours = (zeit/3600);
1547 int days = (zeit/86400);
1548 int weeks = (zeit/604800);
1549 int months = (zeit/2419200);
1550 int abbr = 0;
1551
1552 parts = regexplode( format, "\(%\(-|\)[0-9]*[nwdhmsxNWDHMSX]\)|\(%%\)" );
1553
1554 for( i=1; i<sizeof(parts); i+=2 )
1555 {
1556 ch = parts[i][<1];
1557 switch( parts[i][<1] )
1558 {
1559 case 'x': case 'X':
1560 abbr = sscanf( parts[i], "%%%d", dummy ) && dummy==0;
1561 // NO break !
1562 case 'n': case 'N':
1563 maxunit |= 31;
1564 break;
1565 case 'w': case 'W':
1566 maxunit |= 15;
1567 break;
1568 case 'd': case 'D':
1569 maxunit |= 7;
1570 break;
1571 case 'h': case 'H':
1572 maxunit |= 3;
1573 break;
1574 case 'm': case 'M':
1575 maxunit |= 1;
1576 break;
1577 }
1578 }
1579 if( maxunit & 16 ) weeks %= 4;
1580 if( maxunit & 8 ) days %= 7;
1581 if( maxunit & 4 ) hours %= 24;
1582 if( maxunit & 2 ) mins %= 60;
1583 if( maxunit ) secs %= 60;
1584
1585 for( i=1; i<sizeof(parts); i+=2 )
1586 {
1587 fmt = parts[i][0..<2];
1588 ch = parts[i][<1];
1589 if( ch=='x' )
1590 {
1591 if (months > 0) ch='n';
1592 else if( weeks>0 ) ch='w';
1593 else if( days>0 ) ch='d';
1594 else if( hours>0 ) ch='h';
1595 else if(mins > 0) ch = 'm';
1596 else ch = 's';
1597 }
1598 else if( ch=='X' )
1599 {
1600 if (months > 0) ch='N';
1601 else if( weeks>0 ) ch='W';
1602 else if( days>0 ) ch='D';
1603 else if( hours>0 ) ch='H';
1604 else if(mins > 0) ch = 'M';
1605 else ch = 'S';
1606 }
1607
1608 switch( ch )
1609 {
1610 case 'n': parts[i] = sprintf( fmt+"d", months ); break;
1611 case 'w': parts[i] = sprintf( fmt+"d", weeks ); break;
1612 case 'd': parts[i] = sprintf( fmt+"d", days ); break;
1613 case 'h': parts[i] = sprintf( fmt+"d", hours ); break;
1614 case 'm': parts[i] = sprintf( fmt+"d", mins ); break;
1615 case 's': parts[i] = sprintf( fmt+"d", secs ); break;
1616 case 'N':
1617 if(abbr) parts[i] = "M";
1618 else parts[i] = sprintf( fmt+"s", (months==1) ? "Monat" : "Monate" );
1619 break;
1620 case 'W':
1621 if(abbr) parts[i] = "w"; else
1622 parts[i] = sprintf( fmt+"s", (weeks==1) ? "Woche" : "Wochen" );
1623 break;
1624 case 'D':
1625 if(abbr) parts[i] = "d"; else
1626 parts[i] = sprintf( fmt+"s", (days==1) ? "Tag" : "Tage" );
1627 break;
1628 case 'H':
1629 if(abbr) parts[i] = "h"; else
1630 parts[i] = sprintf( fmt+"s", (hours==1) ? "Stunde" : "Stunden" );
1631 break;
1632 case 'M':
1633 if(abbr) parts[i] = "m"; else
1634 parts[i] = sprintf( fmt+"s", (mins==1) ? "Minute" : "Minuten" );
1635 break;
1636 case 'S':
1637 if(abbr) parts[i] = "s"; else
1638 parts[i] = sprintf( fmt+"s", (secs==1) ? "Sekunde" : "Sekunden" );
1639 break;
1640 case '%':
1641 parts[i] = "%";
1642 break;
1643 }
1644 }
1645 return implode( parts, "" );
1646}
1647
1648nomask mixed __create_player_dummy(string name)
1649{
1650 string err;
1651 object ob;
1652 mixed m;
1653 //hat nen Scherzkeks die Blueprint bewegt?
1654 if ((ob=find_object("/secure/login")) && environment(ob))
1655 catch(destruct(ob);publish);
1656 err = catch(ob = clone_object("secure/login");publish);
1657 if (err)
1658 {
1659 write("Fehler beim Laden von /secure/login.c\n"+err+"\n");
1660 return 0;
1661 }
1662 if (objectp(m=(mixed)ob->new_logon(name))) netdead[name]=m;
1663 return m;
1664}
1665
1666nomask int secure_level()
1667{
1668 int *level;
1669 //kette der Caller durchlaufen, den niedrigsten Level in der Kette
1670 //zurueckgeben. Zerstoerte Objekte (Selbstzerstoerer) fuehren zur Rueckgabe
1671 //von 0.
1672 //caller_stack(1) fuegt dem Rueckgabearray this_interactive() hinzu bzw. 0,
1673 //wenn es keinen Interactive gibt. Die 0 fuehrt dann wie bei zerstoerten
1674 //Objekten zur Rueckgabe von 0, was gewuenscht ist, da es hier einen
1675 //INteractive geben muss.
1676 level=map(caller_stack(1),function int (object caller)
1677 {if (objectp(caller))
1678 return(query_wiz_level(geteuid(caller)));
1679 return(0); // kein Objekt da, 0.
1680 } );
1681 return(min(level)); //den kleinsten Wert im Array zurueckgeben (ggf. 0)
1682}
1683
1684nomask string secure_euid()
1685{
1686 string euid;
1687
1688 if (!this_interactive()) // Es muss einen interactive geben
1689 return 0;
1690 euid=geteuid(this_interactive());
1691 // ueber alle Caller iterieren. Wenn eines davon eine andere euid hat als
1692 // der Interactive und diese nicht die ROOTID ist, wird 0 zurueckgeben.
1693 // Ebenso, falls ein Selbstzerstoerer irgendwo in der Kette ist.
1694 foreach(object caller: caller_stack()) {
1695 if (!objectp(caller) ||
1696 (geteuid(caller)!=euid && geteuid(caller)!=ROOTID))
1697 return 0;
1698 }
1699 return euid; // 'sichere' euid zurueckgeben
1700}
1701
1702// INPUT_PROMPT und nen Leerprompt hinzufuegen, wenn keins uebergeben wird.
1703// Das soll dazu dienen, dass alle ggf. ein EOR am Promptende kriegen...
1704//#if __BOOT_TIME__ < 1360017213
1705varargs void input_to( mixed fun, int flags, varargs mixed *args )
1706{
1707 mixed *arr;
1708 int i;
1709
1710 if ( !this_player() || !previous_object() )
1711 return;
1712
1713 // TODO: input_to(...,INPUT_PROMPT, "", ...), wenn kein INPUT_PROMPT
1714 // vorkommt...
1715 if ( flags&INPUT_PROMPT ) {
1716 arr = ({ fun, flags }) + args;
1717 }
1718 else {
1719 // ggf. ein INPUT_PROMPT hinzufuegen und nen Leerstring als Prompt.
1720 flags |= INPUT_PROMPT;
1721 arr = ({ fun, flags, "" }) + args;
1722 }
1723
1724 // Arrays gegen flatten quoten.
1725 for ( i = sizeof(arr) - 1; i > 1; i-- )
1726 if ( pointerp(arr[i]) )
1727 arr[i] = quote(arr[i]);
1728
1729 apply( bind_lambda( unbound_lambda( ({}),
1730 ({ #'efun::input_to/*'*/ }) + arr ),
1731 previous_object() ) );
1732}
1733//#endif
1734
1735nomask int set_light(int i)
1736// erhoeht das Lichtlevel eines Objekts um i
1737// result: das Lichtlevel innerhalb des Objekts
1738{
1739 object ob, *inv;
1740 int lall, light, dark, tmp;
1741
1742 if (!(ob=previous_object())) return 0; // ohne das gehts nicht.
1743
1744 // aus kompatibilitaetsgruenden kann man auch den Lichtlevel noch setzen
1745 if (i!=0) ob->SetProp(P_LIGHT, ob->QueryProp(P_LIGHT)+i);
1746
1747 // Lichtberechnung findet eigentlich in der Mudlib statt.
1748 return (int)ob->QueryProp(P_INT_LIGHT);
1749}
1750
1751
1752public string iso2ascii( string str )
1753{
Zesstraf022da32017-01-31 12:42:26 +01001754 if ( !sizeof(str) )
MG Mud User88f12472016-06-24 23:31:02 +02001755 return "";
Zesstraf022da32017-01-31 12:42:26 +01001756 return convert_charset(str, "ISO-8859-15", "ASCII//TRANSLIT");
MG Mud User88f12472016-06-24 23:31:02 +02001757}
1758
1759
1760public varargs string CountUp( string *s, string sep, string lastsep )
1761{
1762 string ret;
1763
1764 if ( !pointerp(s) )
1765 return "";
1766
1767 if (!sep) sep = ", ";
1768 if (!lastsep) lastsep = " und ";
1769
1770 switch (sizeof(s)) {
1771 case 0: ret=""; break;
1772 case 1: ret=s[0]; break;
1773 default:
1774 ret = implode(s[0..<2], sep);
1775 ret += lastsep + s[<1];
1776 }
1777 return ret;
1778}
1779
1780nomask varargs int query_next_reset(object ob) {
1781
1782 // Typpruefung: etwas anderes als Objekte oder 0 sollen Fehler sein.
1783 if (ob && !objectp(ob))
1784 raise_error(sprintf("Bad arg 1 to query_next_reset(): got %.20O, "
1785 "expected object.\n",ob));
1786
1787 // Defaultobjekt PO, wenn 0 uebergeben.
1788 if ( !objectp(ob) )
1789 ob = previous_object();
1790
1791 return efun::object_info(ob, OI_NEXT_RESET_TIME);
1792}
1793
1794
MG Mud User88f12472016-06-24 23:31:02 +02001795
1796// ### Ersatzaufloesung in Strings ###
1797varargs string replace_personal(string str, mixed *obs, int caps) {
1798 int i;
1799 string *parts;
1800
1801 parts = regexplode(str, "@WE[A-SU]*[0-9]");
1802 i = sizeof(parts);
1803
Zesstra19102132016-09-01 22:50:36 +02001804 if (i>1)
1805 {
MG Mud User88f12472016-06-24 23:31:02 +02001806 int j, t;
1807 closure *name_cls;
1808
1809 t = j = sizeof(obs);
1810
1811 name_cls = allocate(j);
1812 while (j--)
1813 if (objectp(obs[j]))
1814 name_cls[j] = symbol_function("name", obs[j]);
1815 else if (stringp(obs[j]))
1816 name_cls[j] = obs[j];
1817
Zesstra19102132016-09-01 22:50:36 +02001818 while ((i-= 2)>0)
1819 {
MG Mud User88f12472016-06-24 23:31:02 +02001820 int ob_nr;
1821 // zu ersetzendes Token in Fall und Objektindex aufspalten
1822 ob_nr = parts[i][<1]-'1';
1823 if (ob_nr<0 || ob_nr>=t) {
1824 set_this_object(previous_object());
1825 raise_error(sprintf("replace_personal: using wrong object index %d\n",
1826 ob_nr));
1827 return implode(parts, "");
1828 }
1829
1830 // casus kann man schon hier entscheiden
1831 int casus;
1832 string part = parts[i];
1833 switch (part[3]) {
1834 case 'R': casus = WER; break;
1835 case 'S': casus = WESSEN; break;
1836 case 'M': casus = WEM; break;
1837 case 'N': casus = WEN; break;
1838 default: continue; // passt schon jetzt nicht in das Hauptmuster
1839 }
1840
1841 // und jetzt die einzelnen Keywords ohne fuehrendes "@WE", beendende Id
1842 mixed tmp;
1843 switch (part[3..<2]) {
1844 case "R": case "SSEN": case "M": case "N": // Name
1845 parts[i] = funcall(name_cls[ob_nr], casus, 1); break;
1846 case "RU": case "SSENU": case "MU": case "NU": // unbestimmt
1847 parts[i] = funcall(name_cls[ob_nr], casus); break;
1848 case "RQP": case "SSENQP": case "MQP": case "NQP": // Pronoun
1849 if (objectp(tmp = obs[ob_nr]))
1850 parts[i] = (string)tmp->QueryPronoun(casus);
1851 break;
1852 case "RQA": case "SSENQA": case "MQA": case "NQA": // Article
1853 if (objectp(tmp = obs[ob_nr]))
1854 tmp = (string)tmp->QueryArticle(casus, 1, 1);
1855 if (stringp(tmp) && !(tmp[<1]^' '))
1856 tmp = tmp[0..<2]; // Extra-Space wieder loeschen
1857 break;
1858 case "RQPPMS": case "SSENQPPMS": case "MQPPMS": case "NQPPMS":
1859 if (objectp(tmp = obs[ob_nr]))
1860 parts[i] = (string)tmp->QueryPossPronoun(MALE, casus, SINGULAR);
1861 break;
1862 case "RQPPFS": case "SSENQPPFS": case "MQPPFS": case "NQPPFS":
1863 if (objectp(tmp = obs[ob_nr]))
1864 parts[i] = (string)tmp->QueryPossPronoun(FEMALE, casus, SINGULAR);
1865 break;
1866 case "RQPPNS": case "SSENQPPNS": case "MQPPNS": case "NQPPNS":
1867 if (objectp(tmp = obs[ob_nr]))
1868 parts[i] = (string)tmp->QueryPossPronoun(NEUTER, casus, SINGULAR);
1869 break;
1870 case "RQPPMP": case "SSENQPPMP": case "MQPPMP": case "NQPPMP":
1871 if (objectp(tmp = obs[ob_nr]))
1872 parts[i] = (string)tmp->QueryPossPronoun(MALE, casus, PLURAL);
1873 break;
1874 case "RQPPFP": case "SSENQPPFP": case "MQPPFP": case "NQPPFP":
1875 if (objectp(tmp = obs[ob_nr]))
1876 parts[i] = (string)tmp->QueryPossPronoun(FEMALE, casus, PLURAL);
1877 break;
1878 case "RQPPNP": case "SSENQPPNP": case "MQPPNP": case "NQPPNP":
1879 if (objectp(tmp = obs[ob_nr]))
1880 parts[i] = (string)tmp->QueryPossPronoun(NEUTER, casus, PLURAL);
1881 break;
1882 default:
1883 continue;
1884 }
Zesstra19102132016-09-01 22:50:36 +02001885
MG Mud User88f12472016-06-24 23:31:02 +02001886 // wenn tmp ein String war, weisen wir es hier pauschal zu
1887 if (stringp(tmp))
1888 parts[i] = tmp;
1889
1890 // auf Wunsch wird nach Satzenden gross geschrieben
1891 if (caps)
Zesstra19102132016-09-01 22:50:36 +02001892 {
1893 // Wenn das vorhergehende parts[i] == "" ist, sind wir am Anfang vom
1894 // String und dies wird wie ein Satzende vorher behandelt.
1895 if (parts[i-1] == "")
MG Mud User88f12472016-06-24 23:31:02 +02001896 parts[i] = capitalize(parts[i]);
Zesstra19102132016-09-01 22:50:36 +02001897 else
1898 {
1899 switch (parts[i-1][<2..])
1900 {
1901 case ". ": case "! ": case "? ":
1902 case ".": case "!": case "?":
1903 case ".\n": case "!\n": case "?\n":
1904 case "\" ": case "\"\n":
1905 parts[i] = capitalize(parts[i]);
1906 break;
1907 }
MG Mud User88f12472016-06-24 23:31:02 +02001908 }
Zesstra19102132016-09-01 22:50:36 +02001909 }
MG Mud User88f12472016-06-24 23:31:02 +02001910 }
1911 return implode(parts, "");
1912 }
1913 return str;
1914}
1915
MG Mud User88f12472016-06-24 23:31:02 +02001916//replacements for dropped efuns in LD
1917#if !__EFUN_DEFINED__(extract)
1918deprecated varargs string extract(string str, int from, int to) {
1919
1920 if(!stringp(str)) {
1921 set_this_object(previous_object());
1922 raise_error(sprintf("Bad argument 1 to extract(): %O",str));
1923 }
1924 if (intp(from) && intp(to)) {
1925 if (from>=0 && to>=0)
1926 return(str[from .. to]);
1927 else if (from>=0 && to<0)
1928 return(str[from .. <abs(to)]);
1929 else if (from<0 && to>=0)
1930 return(str[<abs(from) .. to]);
1931 else
1932 return(str[<abs(from) .. <abs(to)]);
1933 }
1934 else if (intp(from)) {
1935 if (from>=0)
1936 return(str[from .. ]);
1937 else
1938 return(str[<abs(from) .. ]);
1939 }
1940 else {
1941 return(str);
1942 }
1943}
1944#endif // !__EFUN_DEFINED__(extract)
1945
1946#if !__EFUN_DEFINED__(slice_array)
1947deprecated varargs mixed slice_array(mixed array, int from, int to) {
1948
1949 if(!pointerp(array)) {
1950 set_this_object(previous_object());
1951 raise_error(sprintf("Bad argument 1 to slice_array(): %O",array));
1952 }
1953 if (intp(from) && intp(to)) {
1954 if (from>=0 && to>=0)
1955 return(array[from .. to]);
1956 else if (from>=0 && to<0)
1957 return(array[from .. <abs(to)]);
1958 else if (from<0 && to>=0)
1959 return(array[<abs(from) .. to]);
1960 else
1961 return(array[<abs(from) .. <abs(to)]);
1962 }
1963 else if (intp(from)) {
1964 if (from>=0)
1965 return(array[from .. ]);
1966 else
1967 return(array[<abs(from) .. ]);
1968 }
1969 else {
1970 return(array);
1971 }
1972}
1973#endif // !__EFUN_DEFINED__(slice_array)
1974
1975#if !__EFUN_DEFINED__(member_array)
1976deprecated int member_array(mixed item, mixed arraystring) {
1977
1978 if (pointerp(arraystring)) {
1979 return(efun::member(arraystring,item));
1980 }
1981 else if (stringp(arraystring)) {
1982 return(efun::member(arraystring,to_int(item)));
1983 }
1984 else {
1985 set_this_object(previous_object());
1986 raise_error(sprintf("Bad argument 1 to member_array(): %O",arraystring));
1987 }
1988}
1989#endif // !__EFUN_DEFINED__(member_array)
1990
1991// The digit at the i'th position is the number of bits set in 'i'.
1992string count_table =
1993 "0112122312232334122323342334344512232334233434452334344534454556";
1994int broken_count_bits( string s ) {
1995 int i, res;
1996 if( !stringp(s) || !(i=sizeof(s)) ) return 0;
1997 for( ; i-->0; ) {
1998 // We are counting 6 bits at a time using a precompiled table.
1999 res += count_table[(s[i]-' ')&63]-'0';
2000 }
2001 return res;
2002}
2003
2004#if !__EFUN_DEFINED__(count_bits)
2005int count_bits( string s ) {
2006 return(broken_count_bits(s));
2007}
2008#endif
2009
2010
2011// * Teile aus einem Array entfernen *** OBSOLETE
2012deprecated mixed *exclude_array(mixed *arr,int from,int to)
2013{
2014 if (to<from)
2015 to = from;
2016 return arr[0..from-1]+arr[to+1..];
2017}
2018