OSDN Git Service

First version
[st-ro/stro.git] / src / map / guild.c
1 // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
2 // For more information, see LICENCE in the main folder
3
4 #include "../common/cbasetypes.h"
5 #include "../common/timer.h"
6 #include "../common/nullpo.h"
7 #include "../common/malloc.h"
8 #include "../common/mapindex.h"
9 #include "../common/showmsg.h"
10 #include "../common/ers.h"
11 #include "../common/strlib.h"
12 #include "../common/utils.h"
13
14 #include "map.h"
15 #include "guild.h"
16 #include "storage.h"
17 #include "battle.h"
18 #include "npc.h"
19 #include "pc.h"
20 #include "instance.h"
21 #include "intif.h"
22 #include "channel.h"
23 #include "log.h"
24 #include "trade.h"
25
26 #include <stdlib.h>
27
28
29 static DBMap* guild_db; // int guild_id -> struct guild*
30 static DBMap* castle_db; // int castle_id -> struct guild_castle*
31 static DBMap* guild_expcache_db; // uint32 char_id -> struct guild_expcache*
32 static DBMap* guild_infoevent_db; // int guild_id -> struct eventlist*
33
34 struct eventlist {
35         char name[EVENT_NAME_LENGTH];
36         struct eventlist *next;
37 };
38
39 //Constant related to the flash of the Guild EXP cache
40 #define GUILD_SEND_XY_INTERVAL  5000 // Interval of sending coordinates and HP
41 #define GUILD_PAYEXP_INTERVAL 10000 //Interval (maximum survival time of the cache, in milliseconds)
42 #define GUILD_PAYEXP_LIST 8192 //The maximum number of cache
43
44 //Guild EXP cache
45 struct guild_expcache {
46         int guild_id, account_id, char_id;
47         uint64 exp;
48 };
49 static struct eri *expcache_ers; //For handling of guild exp payment.
50
51 #define MAX_GUILD_SKILL_REQUIRE 5
52 struct{
53         int id;
54         int max;
55         struct{
56                 short id;
57                 short lv;
58         }need[MAX_GUILD_SKILL_REQUIRE];
59 } guild_skill_tree[MAX_GUILDSKILL];
60
61 int guild_payexp_timer(int tid, unsigned int tick, int id, intptr_t data);
62 static int guild_send_xy_timer(int tid, unsigned int tick, int id, intptr_t data);
63
64 /* guild flags cache */
65 struct npc_data **guild_flags;
66 unsigned short guild_flags_count;
67
68 /**
69  * Get guild skill index in guild_skill_tree
70  * @param skill_id
71  * @return Index in skill_tree or -1
72  **/
73 static short guild_skill_get_index(uint16 skill_id) {
74         if (!SKILL_CHK_GUILD(skill_id))
75                 return -1;
76         skill_id -= GD_SKILLBASE;
77         if (skill_id >= MAX_GUILDSKILL)
78                 return -1;
79         return skill_id;
80 }
81
82 /*==========================================
83  * Retrieves and validates the sd pointer for this guild member [Skotlex]
84  *------------------------------------------*/
85 static TBL_PC* guild_sd_check(int guild_id, uint32 account_id, uint32 char_id) {
86         TBL_PC* sd = map_id2sd(account_id);
87
88         if (!(sd && sd->status.char_id == char_id))
89                 return NULL;
90
91         if (sd->status.guild_id != guild_id)
92         {       //If player belongs to a different guild, kick him out.
93                 intif_guild_leave(guild_id,account_id,char_id,0,"** Guild Mismatch **");
94                 return NULL;
95         }
96
97         return sd;
98 }
99
100 // Modified [Komurka]
101 int guild_skill_get_max (int id) {
102         if ((id = guild_skill_get_index(id)) < 0)
103                 return 0;
104         return guild_skill_tree[id].max;
105 }
106
107 // Retrieve skill_lv learned by guild
108 int guild_checkskill(struct guild *g, int id) {
109         if ((id = guild_skill_get_index(id)) < 0)
110                 return 0;
111         return g->skill[id].lv;
112 }
113
114 /*==========================================
115  * guild_skill_tree.txt reading - from jA [Komurka]
116  *------------------------------------------*/
117 static bool guild_read_guildskill_tree_db(char* split[], int columns, int current) {// <skill id>,<max lv>,<req id1>,<req lv1>,<req id2>,<req lv2>,<req id3>,<req lv3>,<req id4>,<req lv4>,<req id5>,<req lv5>
118         int k, skill_id = atoi(split[0]);
119         short idx = -1;
120
121         if ((idx = guild_skill_get_index(skill_id)) < 0) {
122                 ShowError("guild_read_guildskill_tree_db: Invalid Guild skill '%s'.\n", split[1]);
123                 return false;
124         }
125
126         guild_skill_tree[idx].id = skill_id;
127         guild_skill_tree[idx].max = atoi(split[1]);
128
129         if( guild_skill_tree[idx].id == GD_GLORYGUILD && battle_config.require_glory_guild && guild_skill_tree[idx].max == 0 )  {// enable guild's glory when required for emblems
130                 guild_skill_tree[idx].max = 1;
131         }
132
133         for( k = 0; k < MAX_GUILD_SKILL_REQUIRE; k++ )  {
134                 guild_skill_tree[idx].need[k].id = atoi(split[k*2+2]);
135                 guild_skill_tree[idx].need[k].lv = atoi(split[k*2+3]);
136         }
137
138         return true;
139 }
140
141 /*==========================================
142  * Guild skill check - from jA [Komurka]
143  *------------------------------------------*/
144 int guild_check_skill_require(struct guild *g,int id) {
145         uint8 i;
146         short idx = -1;
147
148         if(g == NULL)
149                 return 0;
150
151         if ((idx = guild_skill_get_index(id)) < 0)
152                 return 0;
153
154         for(i=0;i<MAX_GUILD_SKILL_REQUIRE;i++)
155         {
156                 if(guild_skill_tree[idx].need[i].id == 0) break;
157                 if(guild_skill_tree[idx].need[i].lv > guild_checkskill(g,guild_skill_tree[idx].need[i].id))
158                         return 0;
159         }
160         return 1;
161 }
162
163 static bool guild_read_castledb(char* str[], int columns, int current) {// <castle id>,<map name>,<castle name>,<castle event>[,<reserved/unused switch flag>]
164         struct guild_castle *gc;
165         int mapindex = mapindex_name2id(str[1]);
166
167         if (map_mapindex2mapid(mapindex) < 0) // Map not found or on another map-server
168                 return false;
169
170         CREATE(gc, struct guild_castle, 1);
171         gc->castle_id = atoi(str[0]);
172         gc->mapindex = mapindex;
173         safestrncpy(gc->castle_name, trim(str[2]), sizeof(gc->castle_name));
174         safestrncpy(gc->castle_event, trim(str[3]), sizeof(gc->castle_event));
175
176         idb_put(castle_db,gc->castle_id,gc);
177         return true;
178 }
179
180 /// lookup: guild id -> guild*
181 struct guild* guild_search(int guild_id) {
182         return (struct guild*)idb_get(guild_db,guild_id);
183 }
184
185 /// lookup: guild name -> guild*
186 struct guild* guild_searchname(char* str) {
187         struct guild* g;
188         DBIterator *iter = db_iterator(guild_db);
189
190         for( g = (struct guild*)dbi_first(iter); dbi_exists(iter); g = (struct guild*)dbi_next(iter) ) {
191                 if( strcmpi(g->name, str) == 0 )
192                         break;
193         }
194         dbi_destroy(iter);
195
196         return g;
197 }
198
199 /// lookup: castle id -> castle*
200 struct guild_castle* guild_castle_search(int gcid) {
201         return (struct guild_castle*)idb_get(castle_db,gcid);
202 }
203
204 /// lookup: map index -> castle*
205 struct guild_castle* guild_mapindex2gc(short mapindex) {
206         struct guild_castle* gc;
207         DBIterator *iter = db_iterator(castle_db);
208
209         for( gc = (struct guild_castle*)dbi_first(iter); dbi_exists(iter); gc = (struct guild_castle*)dbi_next(iter) ) {
210                 if( gc->mapindex == mapindex )
211                         break;
212         }
213         dbi_destroy(iter);
214
215         return gc;
216 }
217
218 /// lookup: map name -> castle*
219 struct guild_castle* guild_mapname2gc(const char* mapname) {
220         return guild_mapindex2gc(mapindex_name2id(mapname));
221 }
222
223 struct map_session_data* guild_getavailablesd(struct guild* g) {
224         int i;
225
226         nullpo_retr(NULL, g);
227
228         ARR_FIND( 0, g->max_member, i, g->member[i].sd != NULL );
229         return( i < g->max_member ) ? g->member[i].sd : NULL;
230 }
231
232 /// lookup: player AID/CID -> member index
233 int guild_getindex(struct guild *g,uint32 account_id,uint32 char_id) {
234         int i;
235
236         if( g == NULL )
237                 return -1;
238
239         ARR_FIND( 0, g->max_member, i, g->member[i].account_id == account_id && g->member[i].char_id == char_id );
240         return( i < g->max_member ) ? i : -1;
241 }
242
243 /// lookup: player sd -> member position
244 int guild_getposition(struct map_session_data* sd) {
245         int i;
246         struct guild *g;
247
248         nullpo_retr( -1, g = sd->guild );
249
250         ARR_FIND( 0, g->max_member, i, g->member[i].account_id == sd->status.account_id && g->member[i].char_id == sd->status.char_id );
251         return( i < g->max_member ) ? g->member[i].position : -1;
252 }
253
254 //Creation of member information
255 void guild_makemember(struct guild_member *m,struct map_session_data *sd) {
256         nullpo_retv(sd);
257
258         memset(m,0,sizeof(struct guild_member));
259         m->account_id   = sd->status.account_id;
260         m->char_id              = sd->status.char_id;
261         m->hair                 = sd->status.hair;
262         m->hair_color   = sd->status.hair_color;
263         m->gender               = sd->status.sex;
264         m->class_               = sd->status.class_;
265         m->lv                   = sd->status.base_level;
266 //      m->exp                  = 0;
267 //      m->exp_payper   = 0;
268         m->online               = 1;
269         m->position             = MAX_GUILDPOSITION-1;
270         memcpy(m->name,sd->status.name,NAME_LENGTH);
271         return;
272 }
273
274 /**
275  * Server cache to be flushed to inter the Guild EXP
276  * @see DBApply
277  */
278 int guild_payexp_timer_sub(DBKey key, DBData *data, va_list ap) {
279         int i;
280         struct guild_expcache *c;
281         struct guild *g;
282
283         c = (struct guild_expcache *)db_data2ptr(data);
284
285         if (
286                 (g = guild_search(c->guild_id)) == NULL ||
287                 (i = guild_getindex(g, c->account_id, c->char_id)) < 0
288         ) {
289                 ers_free(expcache_ers, c);
290                 return 0;
291         }
292
293         if (g->member[i].exp > UINT64_MAX - c->exp)
294                 g->member[i].exp = UINT64_MAX;
295         else
296                 g->member[i].exp+= c->exp;
297
298         intif_guild_change_memberinfo(g->guild_id,c->account_id,c->char_id,
299                 GMI_EXP,&g->member[i].exp,sizeof(g->member[i].exp));
300         c->exp=0;
301
302         ers_free(expcache_ers, c);
303         return 0;
304 }
305
306 int guild_payexp_timer(int tid, unsigned int tick, int id, intptr_t data) {
307         guild_expcache_db->clear(guild_expcache_db,guild_payexp_timer_sub);
308         return 0;
309 }
310
311 /**
312  * Taken from party_send_xy_timer_sub. [Skotlex]
313  * @see DBApply
314  */
315 int guild_send_xy_timer_sub(DBKey key, DBData *data, va_list ap) {
316         struct guild *g = (struct guild *)db_data2ptr(data);
317         int i;
318
319         nullpo_ret(g);
320
321         if( !g->connect_member ) {
322                 // no members connected to this guild so do not iterate
323                 return 0;
324         }
325
326         for(i=0;i<g->max_member;i++){
327                 struct map_session_data* sd = g->member[i].sd;
328                 if( sd != NULL && sd->fd && (sd->guild_x != sd->bl.x || sd->guild_y != sd->bl.y) && !sd->bg_id ) {
329                         clif_guild_xy(sd);
330                         sd->guild_x = sd->bl.x;
331                         sd->guild_y = sd->bl.y;
332                 }
333         }
334         return 0;
335 }
336
337 //Code from party_send_xy_timer [Skotlex]
338 static int guild_send_xy_timer(int tid, unsigned int tick, int id, intptr_t data) {
339         guild_db->foreach(guild_db,guild_send_xy_timer_sub,tick);
340         return 0;
341 }
342
343 int guild_send_dot_remove(struct map_session_data *sd) {
344         if (sd->status.guild_id)
345                 clif_guild_xy_remove(sd);
346         return 0;
347 }
348 //------------------------------------------------------------------------
349
350 int guild_create(struct map_session_data *sd, const char *name) {
351         char tname[NAME_LENGTH];
352         struct guild_member m;
353         nullpo_ret(sd);
354
355         safestrncpy(tname, name, NAME_LENGTH);
356         trim(tname);
357
358         if( !tname[0] )
359                 return 0; // empty name
360
361         if( sd->status.guild_id ) {
362                 // already in a guild
363                 clif_guild_created(sd,1);
364                 return 0;
365         }
366         if( battle_config.guild_emperium_check && pc_search_inventory(sd,ITEMID_EMPERIUM) == -1 ) {
367                 // item required
368                 clif_guild_created(sd,3);
369                 return 0;
370         }
371
372         guild_makemember(&m,sd);
373         m.position=0;
374         intif_guild_create(name,&m);
375         return 1;
376 }
377
378 //Whether or not to create guild
379 int guild_created(uint32 account_id,int guild_id) {
380         struct map_session_data *sd=map_id2sd(account_id);
381
382         if(sd==NULL)
383                 return 0;
384         if(!guild_id) {
385                 clif_guild_created(sd, 2); // Creation failure (presence of the same name Guild)
386                 return 0;
387         }
388
389         sd->status.guild_id = guild_id;
390         clif_guild_created(sd,0);
391         if(battle_config.guild_emperium_check){
392                 int index = pc_search_inventory(sd,ITEMID_EMPERIUM);
393
394                 if( index > 0 )
395                         pc_delitem(sd,index,1,0,0,LOG_TYPE_CONSUME);    //emperium consumption
396         }
397         return 0;
398 }
399
400 //Information request
401 int guild_request_info(int guild_id) {
402         return intif_guild_request_info(guild_id);
403 }
404
405 //Information request with event
406 int guild_npc_request_info(int guild_id,const char *event) {
407         if( guild_search(guild_id) ) {
408                 if( event && *event )
409                         npc_event_doall(event);
410
411                 return 0;
412         }
413
414         if( event && *event ) {
415                 struct eventlist *ev;
416                 DBData prev;
417                 ev=(struct eventlist *)aCalloc(sizeof(struct eventlist),1);
418                 safestrncpy(ev->name,event,EVENT_NAME_LENGTH);
419                 //The one in the db (if present) becomes the next event from this.
420                 if (guild_infoevent_db->put(guild_infoevent_db, db_i2key(guild_id), db_ptr2data(ev), &prev))
421                         ev->next = (struct eventlist *)db_data2ptr(&prev);
422         }
423
424         return guild_request_info(guild_id);
425 }
426
427 /**
428  * Close trade window if party member is kicked when trade a party bound item
429  * @param sd
430  **/
431 static void guild_trade_bound_cancel(struct map_session_data *sd) {
432 #ifdef BOUND_ITEMS
433         nullpo_retv(sd);
434         if (sd->state.isBoundTrading&(1<<BOUND_GUILD))
435                 trade_tradecancel(sd);
436 #else
437         ;
438 #endif
439 }
440
441 //Confirmation of the character belongs to guild
442 int guild_check_member(struct guild *g) {
443         int i;
444         struct map_session_data *sd;
445         struct s_mapiterator* iter;
446
447         nullpo_ret(g);
448
449         iter = mapit_getallusers();
450         for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) ) {
451                 if( sd->status.guild_id != g->guild_id )
452                         continue;
453
454                 i = guild_getindex(g,sd->status.account_id,sd->status.char_id);
455                 if (i < 0) {
456                         sd->guild = NULL;
457                         sd->status.guild_id=0;
458                         sd->guild_emblem_id=0;
459                         ShowWarning("guild: check_member %d[%s] is not member\n",sd->status.account_id,sd->status.name);
460                 }
461         }
462         mapit_free(iter);
463
464         return 0;
465 }
466
467 //Delete association with guild_id for all characters
468 int guild_recv_noinfo(int guild_id) {
469         struct map_session_data *sd;
470         struct s_mapiterator* iter;
471
472         iter = mapit_getallusers();
473         for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) ) {
474                 if( sd->status.guild_id == guild_id )
475                         sd->status.guild_id = 0; // erase guild
476         }
477         mapit_free(iter);
478
479         return 0;
480 }
481
482 //Get and display information for all member
483 int guild_recv_info(struct guild *sg) {
484         struct guild *g,before;
485         int i,bm,m;
486         DBData data;
487         struct map_session_data *sd;
488         bool guild_new = false;
489
490         nullpo_ret(sg);
491
492         if((g = guild_search(sg->guild_id))==NULL) {
493                 guild_new = true;
494                 g=(struct guild *)aCalloc(1,sizeof(struct guild));
495                 idb_put(guild_db,sg->guild_id,g);
496                 before=*sg;
497                 //Perform the check on the user because the first load
498                 guild_check_member(sg);
499                 if ((sd = map_nick2sd(sg->master,false)) != NULL) {
500                         //If the guild master is online the first time the guild_info is received,
501                         //that means he was the first to join, so apply guild skill blocking here.
502                         if( battle_config.guild_skill_relog_delay )
503                                 guild_block_skill(sd, battle_config.guild_skill_relog_delay);
504
505                         //Also set the guild master flag.
506                         sd->guild = g;
507                         sd->state.gmaster_flag = 1;
508                         clif_name_area(&sd->bl); // [LuzZza]
509                         clif_guild_masterormember(sd);
510                 }
511         } else {
512                 before=*g;
513         }
514         memcpy(g,sg,sizeof(struct guild));
515
516         if(g->max_member > MAX_GUILD) {
517                 ShowError("guild_recv_info: Received guild with %d members, but MAX_GUILD is only %d. Extra guild-members have been lost!\n", g->max_member, MAX_GUILD);
518                 g->max_member = MAX_GUILD;
519         }
520
521         for(i=bm=m=0;i<g->max_member;i++){
522                 if(g->member[i].account_id>0){
523                         sd = g->member[i].sd = guild_sd_check(g->guild_id, g->member[i].account_id, g->member[i].char_id);
524                         if (sd) clif_name_area(&sd->bl); // [LuzZza]
525                         m++;
526                 }else
527                         g->member[i].sd=NULL;
528                 if(before.member[i].account_id>0)
529                         bm++;
530         }
531
532         for (i = 0; i < g->max_member; i++) { //Transmission of information at all members
533                 sd = g->member[i].sd;
534                 if( sd==NULL )
535                         continue;
536                 sd->guild = g;
537                 if(channel_config.ally_tmpl.name && (channel_config.ally_tmpl.opt&CHAN_OPT_AUTOJOIN)) {
538                         channel_gjoin(sd,3); //make all member join guildchan+allieschan
539                 }
540
541                 if (before.guild_lv != g->guild_lv || bm != m ||
542                         before.max_member != g->max_member) {
543                         clif_guild_basicinfo(sd); //Submit basic information
544                         clif_guild_emblem(sd, g); //Submit emblem
545                 }
546
547                 if (bm != m) { //Send members information
548                         clif_guild_memberlist(g->member[i].sd);
549                 }
550
551                 if (before.skill_point != g->skill_point)
552                         clif_guild_skillinfo(sd); //Submit information skills
553
554                 if (guild_new) { // Send information and affiliation if unsent
555                         clif_guild_belonginfo(sd);
556                         clif_guild_notice(sd);
557                         sd->guild_emblem_id = g->emblem_id;
558                 }
559                 if (g->instance_id != 0)
560                         instance_reqinfo(sd, g->instance_id);
561         }
562
563         //Occurrence of an event
564         if (guild_infoevent_db->remove(guild_infoevent_db, db_i2key(sg->guild_id), &data)) {
565                 struct eventlist *ev = (struct eventlist *)db_data2ptr(&data), *ev2;
566                 while(ev) {
567                         npc_event_do(ev->name);
568                         ev2=ev->next;
569                         aFree(ev);
570                         ev=ev2;
571                 }
572         }
573
574         return 0;
575 }
576
577 /*=============================================
578  * Player sd send a guild invatation to player tsd to join his guild
579  *--------------------------------------------*/
580 int guild_invite(struct map_session_data *sd, struct map_session_data *tsd) {
581         struct guild *g;
582         int i;
583
584         nullpo_ret(sd);
585
586         g=sd->guild;
587
588         if(tsd==NULL || g==NULL)
589                 return 0;
590
591         if( (i=guild_getposition(sd))<0 || !(g->position[i].mode&0x0001) )
592                 return 0; //Invite permission.
593
594         if(!battle_config.invite_request_check) {
595         if (tsd->party_invite > 0 || tsd->trade_partner || tsd->adopt_invite) { //checking if there no other invitation pending
596                         clif_guild_inviteack(sd,0);
597                         return 0;
598                 }
599         }
600
601         if (!tsd->fd) { //You can't invite someone who has already disconnected.
602                 clif_guild_inviteack(sd,1);
603                 return 0;
604         }
605
606         if(tsd->status.guild_id>0 ||
607                 tsd->guild_invite>0 ||
608                 map_flag_gvg2(tsd->bl.m))
609         {       //Can't invite people inside castles. [Skotlex]
610                 clif_guild_inviteack(sd,0);
611                 return 0;
612         }
613
614         //search an empty spot in guild
615         ARR_FIND( 0, g->max_member, i, g->member[i].account_id == 0 );
616         if(i==g->max_member){
617                 clif_guild_inviteack(sd,3);
618                 return 0;
619         }
620
621         tsd->guild_invite=sd->status.guild_id;
622         tsd->guild_invite_account=sd->status.account_id;
623
624         clif_guild_invite(tsd,g);
625         return 0;
626 }
627
628 /// Guild invitation reply.
629 /// flag: 0:rejected, 1:accepted
630 int guild_reply_invite(struct map_session_data* sd, int guild_id, int flag) {
631         struct map_session_data* tsd;
632
633         nullpo_ret(sd);
634
635         // subsequent requests may override the value
636         if( sd->guild_invite != guild_id )
637                 return 0; // mismatch
638
639         // look up the person who sent the invite
640         //NOTE: this can be NULL because the person might have logged off in the meantime
641         tsd = map_id2sd(sd->guild_invite_account);
642
643         if ( sd->status.guild_id > 0 ) {
644         // [Paradox924X]
645          // Already in another guild.
646                 if ( tsd ) clif_guild_inviteack(tsd,0);
647                 return 0;
648         } else if( flag == 0 ) {// rejected
649                 sd->guild_invite = 0;
650                 sd->guild_invite_account = 0;
651                 if( tsd ) clif_guild_inviteack(tsd,1);
652         } else {// accepted
653                 struct guild_member m;
654                 struct guild* g;
655                 int i;
656
657                 if( (g=guild_search(guild_id)) == NULL ) {
658                         sd->guild_invite = 0;
659                         sd->guild_invite_account = 0;
660                         return 0;
661                 }
662
663                 ARR_FIND( 0, g->max_member, i, g->member[i].account_id == 0 );
664                 if( i == g->max_member ) {
665                         sd->guild_invite = 0;
666                         sd->guild_invite_account = 0;
667                         if( tsd ) clif_guild_inviteack(tsd,3);
668                         return 0;
669                 }
670
671                 guild_makemember(&m,sd);
672                 intif_guild_addmember(guild_id, &m);
673                 //TODO: send a minimap update to this player
674         }
675
676         return 0;
677 }
678
679 //Invoked when a player joins.
680 //- If guild is not in memory, it is requested
681 //- Otherwise sd pointer is set up.
682 //- Player must be authed and must belong to a guild before invoking this method
683 void guild_member_joined(struct map_session_data *sd) {
684         struct guild* g;
685         int i;
686         g=guild_search(sd->status.guild_id);
687         if (!g) {
688                 guild_request_info(sd->status.guild_id);
689                 return;
690         }
691         if (strcmp(sd->status.name,g->master) == 0) {   // set the Guild Master flag
692                 sd->state.gmaster_flag = 1;
693                 // prevent Guild Skills from being used directly after relog
694                 if( battle_config.guild_skill_relog_delay )
695                         guild_block_skill(sd, battle_config.guild_skill_relog_delay);
696         }
697         i = guild_getindex(g, sd->status.account_id, sd->status.char_id);
698         if (i == -1)
699                 sd->status.guild_id = 0;
700         else {
701                 g->member[i].sd = sd;
702                 sd->guild = g;
703
704                 if (g->instance_id != 0)
705                         instance_reqinfo(sd, g->instance_id);
706                 if( channel_config.ally_tmpl.name != NULL && (channel_config.ally_tmpl.opt&CHAN_OPT_AUTOJOIN) ) {
707                         channel_gjoin(sd,3);
708                 }
709         }
710 }
711
712 /*==========================================
713  * Add a player to a given guild_id
714  *----------------------------------------*/
715 int guild_member_added(int guild_id,uint32 account_id,uint32 char_id,int flag) {
716         struct map_session_data *sd= map_id2sd(account_id),*sd2;
717         struct guild *g;
718
719         if( (g=guild_search(guild_id))==NULL )
720                 return 0;
721
722         if(sd==NULL || sd->guild_invite==0){
723         // cancel if player not present or invalide guild_id invitation
724                 if (flag == 0) {
725                         ShowError("guild: member added error %d is not online\n",account_id);
726                         intif_guild_leave(guild_id,account_id,char_id,0,"** Data Error **");
727                 }
728                 return 0;
729         }
730         sd2 = map_id2sd(sd->guild_invite_account);
731         sd->guild_invite = 0;
732         sd->guild_invite_account = 0;
733
734         if (flag == 1) { //failure
735                 if( sd2!=NULL )
736                         clif_guild_inviteack(sd2,3);
737                 return 0;
738         }
739
740         //if all ok add player to guild
741         sd->status.guild_id = g->guild_id;
742         sd->guild_emblem_id = g->emblem_id;
743         sd->guild = g;
744         //Packets which were sent in the previous 'guild_sent' implementation.
745         clif_guild_belonginfo(sd);
746         clif_guild_notice(sd);
747
748         //TODO: send new emblem info to others
749
750         if( sd2!=NULL )
751                 clif_guild_inviteack(sd2,2);
752
753         //Next line commented because it do nothing, look at guild_recv_info [LuzZza]
754         //clif_charnameupdate(sd); //Update display name [Skotlex]
755
756         if (g->instance_id != 0)
757                 instance_reqinfo(sd, g->instance_id);
758
759         return 0;
760 }
761
762 /*==========================================
763  * Player request leaving a given guild_id
764  *----------------------------------------*/
765 int guild_leave(struct map_session_data* sd, int guild_id, uint32 account_id, uint32 char_id, const char* mes) {
766         struct guild *g;
767
768         nullpo_ret(sd);
769
770         g = sd->guild;
771
772         if(g==NULL)
773                 return 0;
774
775         if(sd->status.account_id!=account_id ||
776                 sd->status.char_id!=char_id || sd->status.guild_id!=guild_id ||
777                 map_flag_gvg2(sd->bl.m))
778                 return 0;
779
780         guild_trade_bound_cancel(sd);
781         intif_guild_leave(sd->status.guild_id, sd->status.account_id, sd->status.char_id,0,mes);
782         return 0;
783 }
784
785 /*==========================================
786  * Request remove a player to a given guild_id
787  *----------------------------------------*/
788 int guild_expulsion(struct map_session_data* sd, int guild_id, uint32 account_id, uint32 char_id, const char* mes) {
789         struct map_session_data *tsd;
790         struct guild *g;
791         int i,ps;
792
793         nullpo_ret(sd);
794
795         g = sd->guild;
796
797         if(g==NULL)
798                 return 0;
799
800         if(sd->status.guild_id!=guild_id)
801                 return 0;
802
803         if( (ps=guild_getposition(sd))<0 || !(g->position[ps].mode&0x0010) )
804                 return 0;       //Expulsion permission
805
806         //Can't leave inside guild castles.
807         if ((tsd = map_id2sd(account_id)) &&
808                 tsd->status.char_id == char_id &&
809                 map_flag_gvg2(tsd->bl.m))
810                 return 0;
811
812         // find the member and perform expulsion
813         i = guild_getindex(g, account_id, char_id);
814         if( i != -1 && strcmp(g->member[i].name,g->master) != 0 ) { //Can't expel the GL!
815                 if (tsd)
816                         guild_trade_bound_cancel(tsd);
817                 intif_guild_leave(g->guild_id,account_id,char_id,1,mes);
818         }
819
820         return 0;
821 }
822
823 /**
824 * A confirmation from inter-serv that player is kicked successfully
825 * @param guild_Id
826 * @param account_id
827 * @param char_id
828 * @param flag
829 * @param name
830 * @param mes
831 */
832 int guild_member_withdraw(int guild_id, uint32 account_id, uint32 char_id, int flag, const char* name, const char* mes) {
833         int i;
834         struct guild* g = guild_search(guild_id);
835         struct map_session_data* sd = map_charid2sd(char_id);
836         struct map_session_data* online_member_sd;
837
838         if(g == NULL)
839                 return 0; // no such guild (error!)
840
841         i = guild_getindex(g, account_id, char_id);
842         if( i == -1 )
843                 return 0; // not a member (inconsistency!)
844
845 #ifdef BOUND_ITEMS
846         //Guild bound item check
847         guild_retrieveitembound(char_id,account_id,guild_id);
848 #endif
849
850         online_member_sd = guild_getavailablesd(g);
851         if(online_member_sd == NULL)
852                 return 0; // noone online to inform
853
854
855         if(!flag)
856                 clif_guild_leave(online_member_sd, name, mes);
857         else
858                 clif_guild_expulsion(online_member_sd, name, mes, account_id);
859
860         // remove member from guild
861         memset(&g->member[i],0,sizeof(struct guild_member));
862         clif_guild_memberlist(online_member_sd);
863
864         // update char, if online
865         if(sd != NULL && sd->status.guild_id == guild_id) {
866                 // do stuff that needs the guild_id first, BEFORE we wipe it
867                 if (sd->state.storage_flag == 2) //Close the guild storage.
868                         storage_guild_storageclose(sd);
869                 guild_send_dot_remove(sd);
870                 channel_pcquit(sd,3); //leave guild and ally chan
871                 sd->status.guild_id = 0;
872                 sd->guild = NULL;
873                 sd->guild_emblem_id = 0;
874
875                 if (g->instance_id) {
876                         int16 m = sd->bl.m;
877
878                         if (map[m].instance_id) { // User was on the instance map
879                                 if (map[m].save.map)
880                                         pc_setpos(sd, map[m].save.map, map[m].save.x, map[m].save.y, CLR_TELEPORT);
881                                 else
882                                         pc_setpos(sd, sd->status.save_point.map, sd->status.save_point.x, sd->status.save_point.y, CLR_TELEPORT);
883                         }
884                 }
885
886                 clif_name_area(&sd->bl); //Update display name [Skotlex]
887                 status_change_end(&sd->bl,SC_LEADERSHIP,INVALID_TIMER);
888                 status_change_end(&sd->bl,SC_GLORYWOUNDS,INVALID_TIMER);
889                 status_change_end(&sd->bl,SC_SOULCOLD,INVALID_TIMER);
890                 status_change_end(&sd->bl,SC_HAWKEYES,INVALID_TIMER);
891                 //@TODO: Send emblem update to self and people around
892         }
893         return 0;
894 }
895
896 #ifdef BOUND_ITEMS
897 /**
898 * Retrieve guild bound items from kicked member
899 * @param char_id
900 * @param account_id
901 * @param guild_id
902 */
903 void guild_retrieveitembound(uint32 char_id, uint32 account_id, int guild_id) {
904         TBL_PC *sd = map_charid2sd(char_id);
905         if (sd) { //Character is online
906                 int idxlist[MAX_INVENTORY];
907                 int j;
908                 j = pc_bound_chk(sd,BOUND_GUILD,idxlist);
909                 if (j) {
910                         struct s_storage* stor = guild2storage(sd->status.guild_id);
911                         struct guild *g = guild_search(guild_id);
912                         int i;
913                         if (stor && stor->status) { //Someone is in guild storage, close them
914                                 for (i = 0; i < g->max_member; i++) {
915                                         TBL_PC *pl_sd = g->member[i].sd;
916                                         if (pl_sd && pl_sd->state.storage_flag == 2)
917                                                 storage_guild_storageclose(pl_sd);
918                                 }
919                         }
920                         for (i = 0; i < j; i++) { //Loop the matching items, gstorage_additem takes care of opening storage
921                                 if (stor)
922                                         storage_guild_additem(sd,stor,&sd->inventory.u.items_inventory[idxlist[i]],sd->inventory.u.items_inventory[idxlist[i]].amount);
923                                 pc_delitem(sd,idxlist[i],sd->inventory.u.items_inventory[idxlist[i]].amount,0,4,LOG_TYPE_GSTORAGE);
924                         }
925                         storage_guild_storageclose(sd); //Close and save the storage
926                 }
927         } else { //Character is offline, ask char server to do the job
928                 struct s_storage* stor = guild2storage2(guild_id);
929                 struct guild *g = guild_search(guild_id);
930                 nullpo_retv(g);
931                 if (stor && stor->status) { //Someone is in guild storage, close them
932                         int i;
933                         for (i = 0; i < g->max_member; i++) {
934                                 TBL_PC *pl_sd = g->member[i].sd;
935                                 if (pl_sd && pl_sd->state.storage_flag == 2)
936                                         storage_guild_storageclose(pl_sd);
937                         }
938                 }
939                 intif_itembound_guild_retrieve(char_id,account_id,guild_id);
940         }
941 }
942 #endif
943
944 int guild_send_memberinfoshort(struct map_session_data *sd,int online) { // cleaned up [LuzZza]
945         struct guild *g;
946
947         nullpo_ret(sd);
948
949         if(sd->status.guild_id <= 0)
950                 return 0;
951
952         if(!(g = sd->guild))
953                 return 0;
954
955         intif_guild_memberinfoshort(g->guild_id,
956                 sd->status.account_id,sd->status.char_id,online,sd->status.base_level,sd->status.class_);
957
958         if(!online){
959                 int i=guild_getindex(g,sd->status.account_id,sd->status.char_id);
960                 if(i>=0)
961                         g->member[i].sd=NULL;
962                 else
963                         ShowError("guild_send_memberinfoshort: Failed to locate member %d:%d in guild %d!\n", sd->status.account_id, sd->status.char_id, g->guild_id);
964                 return 0;
965         }
966
967         if(sd->state.connect_new) {     //Note that this works because it is invoked in parse_LoadEndAck before connect_new is cleared.
968                 clif_guild_belonginfo(sd);
969                 sd->guild_emblem_id = g->emblem_id;
970         }
971         return 0;
972 }
973
974 int guild_recv_memberinfoshort(int guild_id,uint32 account_id,uint32 char_id,int online,int lv,int class_) { // cleaned up [LuzZza]
975
976         int i,alv,c,idx=-1,om=0,oldonline=-1;
977         struct guild *g = guild_search(guild_id);
978
979         if(g == NULL)
980                 return 0;
981
982         for(i=0,alv=0,c=0,om=0;i<g->max_member;i++){
983                 struct guild_member *m=&g->member[i];
984                 if(!m->account_id) continue;
985                 if(m->account_id==account_id && m->char_id==char_id ){
986                         oldonline=m->online;
987                         m->online=online;
988                         m->lv=lv;
989                         m->class_=class_;
990                         idx=i;
991                 }
992                 alv+=m->lv;
993                 c++;
994                 if(m->online)
995                         om++;
996         }
997
998         if(idx == -1 || c == 0) {
999         //Treat char_id who doesn't match guild_id (not found as member)
1000                 struct map_session_data *sd = map_id2sd(account_id);
1001                 if(sd && sd->status.char_id == char_id) {
1002                         sd->status.guild_id=0;
1003                         sd->guild_emblem_id=0;
1004                 }
1005                 ShowWarning("guild: not found member %d,%d on %d[%s]\n",        account_id,char_id,guild_id,g->name);
1006                 return 0;
1007         }
1008
1009         g->average_lv=alv/c;
1010         g->connect_member=om;
1011
1012         //Ensure validity of pointer (ie: player logs in/out, changes map-server)
1013         g->member[idx].sd = guild_sd_check(guild_id, account_id, char_id);
1014
1015         if(oldonline!=online)
1016                 clif_guild_memberlogin_notice(g, idx, online);
1017
1018         if(!g->member[idx].sd)
1019                 return 0;
1020
1021         //Send XY dot updates. [Skotlex]
1022         //Moved from guild_send_memberinfoshort [LuzZza]
1023         for(i=0; i < g->max_member; i++) {
1024
1025                 if(!g->member[i].sd || i == idx ||
1026                         g->member[i].sd->bl.m != g->member[idx].sd->bl.m)
1027                         continue;
1028
1029                 clif_guild_xy_single(g->member[idx].sd->fd, g->member[i].sd);
1030                 clif_guild_xy_single(g->member[i].sd->fd, g->member[idx].sd);
1031         }
1032
1033         return 0;
1034 }
1035
1036 /*====================================================
1037  * Send a message to whole guild
1038  *---------------------------------------------------*/
1039 int guild_send_message(struct map_session_data *sd,const char *mes,int len) {
1040         nullpo_ret(sd);
1041
1042         if(sd->status.guild_id==0)
1043                 return 0;
1044         intif_guild_message(sd->status.guild_id,sd->status.account_id,mes,len);
1045         guild_recv_message(sd->status.guild_id,sd->status.account_id,mes,len);
1046
1047         // Chat logging type 'G' / Guild Chat
1048         log_chat(LOG_CHAT_GUILD, sd->status.guild_id, sd->status.char_id, sd->status.account_id, mapindex_id2name(sd->mapindex), sd->bl.x, sd->bl.y, NULL, mes);
1049
1050         return 0;
1051 }
1052
1053 /*====================================================
1054  * Guild receive a message, will be displayed to whole member
1055  *---------------------------------------------------*/
1056 int guild_recv_message(int guild_id,uint32 account_id,const char *mes,int len) {
1057         struct guild *g;
1058         if( (g=guild_search(guild_id))==NULL)
1059                 return 0;
1060         clif_guild_message(g,account_id,mes,len);
1061         return 0;
1062 }
1063
1064 /*====================================================
1065  * Member changing position in guild
1066  *---------------------------------------------------*/
1067 int guild_change_memberposition(int guild_id,uint32 account_id,uint32 char_id,short idx) {
1068         return intif_guild_change_memberinfo(guild_id,account_id,char_id,GMI_POSITION,&idx,sizeof(idx));
1069 }
1070
1071 /*====================================================
1072  * Notification of new position for member
1073  *---------------------------------------------------*/
1074 int guild_memberposition_changed(struct guild *g,int idx,int pos) {
1075         nullpo_ret(g);
1076
1077         g->member[idx].position=pos;
1078         clif_guild_memberpositionchanged(g,idx);
1079
1080         // Update char position in client [LuzZza]
1081         if(g->member[idx].sd != NULL)
1082                 clif_name_area(&g->member[idx].sd->bl);
1083         return 0;
1084 }
1085
1086 /*====================================================
1087  * Change guild title or member
1088  *---------------------------------------------------*/
1089 int guild_change_position(int guild_id,int idx,
1090         int mode,int exp_mode,const char *name) {
1091         struct guild_position p;
1092
1093         exp_mode = cap_value(exp_mode, 0, battle_config.guild_exp_limit);
1094         //Mode 0x01 <- Invite
1095         //Mode 0x10 <- Expel.
1096         p.mode=mode&0x11;
1097         p.exp_mode=exp_mode;
1098         safestrncpy(p.name,name,NAME_LENGTH);
1099         return intif_guild_position(guild_id,idx,&p);
1100 }
1101
1102 /*====================================================
1103  * Notification of member has changed his guild title
1104  *---------------------------------------------------*/
1105 int guild_position_changed(int guild_id,int idx,struct guild_position *p) {
1106         struct guild *g=guild_search(guild_id);
1107         int i;
1108         if(g==NULL)
1109                 return 0;
1110         memcpy(&g->position[idx],p,sizeof(struct guild_position));
1111         clif_guild_positionchanged(g,idx);
1112
1113         // Update char name in client [LuzZza]
1114         for(i=0;i<g->max_member;i++)
1115                 if(g->member[i].position == idx && g->member[i].sd != NULL)
1116                         clif_name_area(&g->member[i].sd->bl);
1117         return 0;
1118 }
1119
1120 /*====================================================
1121  * Change guild notice
1122  *---------------------------------------------------*/
1123 int guild_change_notice(struct map_session_data *sd,int guild_id,const char *mes1,const char *mes2) {
1124         nullpo_ret(sd);
1125
1126         if(guild_id!=sd->status.guild_id)
1127                 return 0;
1128         return intif_guild_notice(guild_id,mes1,mes2);
1129 }
1130
1131 /*====================================================
1132  * Notification of guild has changed his notice
1133  *---------------------------------------------------*/
1134 int guild_notice_changed(int guild_id,const char *mes1,const char *mes2) {
1135         int i;
1136         struct guild *g=guild_search(guild_id);
1137         if(g==NULL)
1138                 return 0;
1139
1140         memcpy(g->mes1,mes1,MAX_GUILDMES1);
1141         memcpy(g->mes2,mes2,MAX_GUILDMES2);
1142
1143         for(i=0;i<g->max_member;i++){
1144                 struct map_session_data *sd = g->member[i].sd;
1145                 if(sd != NULL)
1146                         clif_guild_notice(sd);
1147         }
1148         return 0;
1149 }
1150
1151 /*====================================================
1152  * Change guild emblem
1153  *---------------------------------------------------*/
1154 int guild_change_emblem(struct map_session_data *sd,int len,const char *data) {
1155         struct guild *g;
1156         nullpo_ret(sd);
1157
1158         if (battle_config.require_glory_guild &&
1159                 !((g = sd->guild) && guild_checkskill(g, GD_GLORYGUILD)>0)) {
1160                 clif_skill_fail(sd,GD_GLORYGUILD,USESKILL_FAIL_LEVEL,0);
1161                 return 0;
1162         }
1163
1164         return intif_guild_emblem(sd->status.guild_id,len,data);
1165 }
1166
1167 /*====================================================
1168  * Notification of guild emblem changed
1169  *---------------------------------------------------*/
1170 int guild_emblem_changed(int len,int guild_id,int emblem_id,const char *data) {
1171         int i;
1172         struct map_session_data *sd;
1173         struct guild *g=guild_search(guild_id);
1174         if(g==NULL)
1175                 return 0;
1176
1177         memcpy(g->emblem_data,data,len);
1178         g->emblem_len=len;
1179         g->emblem_id=emblem_id;
1180
1181         for(i=0;i<g->max_member;i++){
1182                 if((sd=g->member[i].sd)!=NULL){
1183                         sd->guild_emblem_id=emblem_id;
1184                         clif_guild_belonginfo(sd);
1185                         clif_guild_emblem(sd,g);
1186                         clif_guild_emblem_area(&sd->bl);
1187                 }
1188         }
1189         {// update guardians (mobs)
1190                 DBIterator* iter = db_iterator(castle_db);
1191                 struct guild_castle* gc;
1192                 for( gc = (struct guild_castle*)dbi_first(iter) ; dbi_exists(iter); gc = (struct guild_castle*)dbi_next(iter) )
1193                 {
1194                         if( gc->guild_id != guild_id )
1195                                 continue;
1196                         // update permanent guardians
1197                         for( i = 0; i < ARRAYLENGTH(gc->guardian); ++i )
1198                         {
1199                                 TBL_MOB* md = (gc->guardian[i].id ? map_id2md(gc->guardian[i].id) : NULL);
1200                                 if( md == NULL || md->guardian_data == NULL )
1201                                         continue;
1202                                 md->guardian_data->emblem_id = emblem_id;
1203                                 clif_guild_emblem_area(&md->bl);
1204                         }
1205                         // update temporary guardians
1206                         for( i = 0; i < gc->temp_guardians_max; ++i )
1207                         {
1208                                 TBL_MOB* md = (gc->temp_guardians[i] ? map_id2md(gc->temp_guardians[i]) : NULL);
1209                                 if( md == NULL || md->guardian_data == NULL )
1210                                         continue;
1211                                 md->guardian_data->emblem_id = emblem_id;
1212                                 clif_guild_emblem_area(&md->bl);
1213                         }
1214                 }
1215                 dbi_destroy(iter);
1216         }
1217         {// update npcs (flags or other npcs that used flagemblem to attach to this guild)
1218                 for( i = 0; i < guild_flags_count; i++ ) {
1219                         if( guild_flags[i] && guild_flags[i]->u.scr.guild_id == guild_id ) {
1220                                 clif_guild_emblem_area(&guild_flags[i]->bl);
1221                         }
1222                 }
1223         }
1224         return 0;
1225 }
1226
1227 /**
1228  * @see DBCreateData
1229  */
1230 static DBData create_expcache(DBKey key, va_list args) {
1231         struct guild_expcache *c;
1232         struct map_session_data *sd = va_arg(args, struct map_session_data*);
1233
1234         c = ers_alloc(expcache_ers, struct guild_expcache);
1235         c->guild_id = sd->status.guild_id;
1236         c->account_id = sd->status.account_id;
1237         c->char_id = sd->status.char_id;
1238         c->exp = 0;
1239         return db_ptr2data(c);
1240 }
1241
1242 /*====================================================
1243  * Return taxed experience from player sd to guild
1244  *---------------------------------------------------*/
1245 unsigned int guild_payexp(struct map_session_data *sd,unsigned int exp) {
1246         struct guild *g;
1247         struct guild_expcache *c;
1248         int per;
1249
1250         nullpo_ret(sd);
1251
1252         if (!exp) return 0;
1253
1254         if (sd->status.guild_id == 0 ||
1255                 (g = sd->guild) == NULL ||
1256                 (per = guild_getposition(sd)) < 0 ||
1257                 (per = g->position[per].exp_mode) < 1)
1258                 return 0;
1259
1260
1261         if (per < 100)
1262                 exp = exp * per / 100;
1263         //Otherwise tax everything.
1264
1265         c = (struct guild_expcache *)db_data2ptr(guild_expcache_db->ensure(guild_expcache_db, db_i2key(sd->status.char_id), create_expcache, sd));
1266
1267         if (c->exp > UINT64_MAX - exp)
1268                 c->exp = UINT64_MAX;
1269         else
1270                 c->exp += exp;
1271
1272         return exp;
1273 }
1274
1275 /*====================================================
1276  * Player sd pay a tribute experience to his guild
1277  * Add this experience to guild exp
1278  * [Celest]
1279  *---------------------------------------------------*/
1280 int guild_getexp(struct map_session_data *sd,int exp) {
1281         struct guild_expcache *c;
1282         nullpo_ret(sd);
1283
1284         if (sd->status.guild_id == 0 || sd->guild == NULL)
1285                 return 0;
1286
1287         c = (struct guild_expcache *)db_data2ptr(guild_expcache_db->ensure(guild_expcache_db, db_i2key(sd->status.char_id), create_expcache, sd));
1288         if (c->exp > UINT64_MAX - exp)
1289                 c->exp = UINT64_MAX;
1290         else
1291                 c->exp += exp;
1292         return exp;
1293 }
1294
1295 /*====================================================
1296  * Ask to increase guildskill skill_id
1297  *---------------------------------------------------*/
1298 void guild_skillup(struct map_session_data* sd, uint16 skill_id) {
1299         struct guild* g;
1300         short idx = guild_skill_get_index(skill_id);
1301         short max = 0;
1302
1303         nullpo_retv(sd);
1304
1305         if (idx == -1)
1306                 return;
1307
1308         if( sd->status.guild_id == 0 || (g=sd->guild) == NULL || // no guild
1309                 strcmp(sd->status.name, g->master) ) // not the guild master
1310                 return;
1311
1312         max = guild_skill_get_max(skill_id);
1313
1314         if( g->skill_point > 0 &&
1315                 g->skill[idx].id != 0 &&
1316                 g->skill[idx].lv < max )
1317                 intif_guild_skillup(g->guild_id, skill_id, sd->status.account_id, max);
1318 }
1319
1320 /*====================================================
1321  * Notification of guildskill skill_id increase request
1322  *---------------------------------------------------*/
1323 int guild_skillupack(int guild_id,uint16 skill_id,uint32 account_id) {
1324         struct map_session_data *sd = map_id2sd(account_id);
1325         struct guild *g = guild_search(guild_id);
1326         int i;
1327         short idx = guild_skill_get_index(skill_id);
1328
1329         if (g == NULL || idx == -1)
1330                 return 0;
1331         if (sd != NULL) {
1332                 int lv = g->skill[idx].lv;
1333                 int range = skill_get_range(skill_id, lv);
1334                 clif_skillup(sd,skill_id,lv,range,1);
1335
1336                 /* Guild Aura handling */
1337                 switch( skill_id ) {
1338                         case GD_LEADERSHIP:
1339                         case GD_GLORYWOUNDS:
1340                         case GD_SOULCOLD:
1341                         case GD_HAWKEYES:
1342                                         guild_guildaura_refresh(sd,skill_id,g->skill[idx].lv);
1343                                 break;
1344                 }
1345         }
1346
1347         // Inform all members
1348         for (i = 0; i < g->max_member; i++)
1349                 if ((sd = g->member[i].sd) != NULL)
1350                         clif_guild_skillinfo(sd);
1351
1352         return 0;
1353 }
1354
1355 void guild_guildaura_refresh(struct map_session_data *sd, uint16 skill_id, uint16 skill_lv) {
1356         struct skill_unit_group* group = NULL;
1357         sc_type type = status_skill2sc(skill_id);
1358         if( !(battle_config.guild_aura&(is_agit_start()?2:1)) &&
1359                         !(battle_config.guild_aura&(map_flag_gvg2(sd->bl.m)?8:4)) )
1360                 return;
1361         if( !skill_lv )
1362                 return;
1363         if( sd->sc.data[type] && (group = skill_id2group(sd->sc.data[type]->val4)) ) {
1364                 skill_delunitgroup(group);
1365                 status_change_end(&sd->bl,type,INVALID_TIMER);
1366         }
1367         group = skill_unitsetting(&sd->bl,skill_id,skill_lv,sd->bl.x,sd->bl.y,0);
1368         if( group )
1369                 sc_start4(NULL,&sd->bl,type,100,(battle_config.guild_aura&16)?0:skill_lv,0,0,group->group_id,600000);//duration doesn't matter these status never end with val4
1370         return;
1371 }
1372
1373 /*====================================================
1374  * Count number of relations the guild has.
1375  * Flag:
1376  *      0 = allied
1377  *      1 = enemy
1378  *---------------------------------------------------*/
1379 int guild_get_alliance_count(struct guild *g,int flag) {
1380         int i,c;
1381
1382         nullpo_ret(g);
1383
1384         for(i=c=0;i<MAX_GUILDALLIANCE;i++){
1385                 if(     g->alliance[i].guild_id>0 &&
1386                         g->alliance[i].opposition==flag )
1387                         c++;
1388         }
1389         return c;
1390 }
1391
1392 // Blocks all guild skills which have a common delay time.
1393 void guild_block_skill(struct map_session_data *sd, int time) {
1394         uint16 skill_id[] = { GD_BATTLEORDER, GD_REGENERATION, GD_RESTORE, GD_EMERGENCYCALL };
1395         int i;
1396         for (i = 0; i < 4; i++)
1397                 skill_blockpc_start(sd, skill_id[i], time);
1398 }
1399
1400 /*====================================================
1401  * Check relation between guild_id1 and guild_id2.
1402  * Flag:
1403  *      0 = allied
1404  *      1 = enemy
1405  * Returns true if yes.
1406  *---------------------------------------------------*/
1407 int guild_check_alliance(int guild_id1, int guild_id2, int flag) {
1408         struct guild *g;
1409         int i;
1410
1411         g = guild_search(guild_id1);
1412         if (g == NULL)
1413                 return 0;
1414
1415         ARR_FIND( 0, MAX_GUILDALLIANCE, i, g->alliance[i].guild_id == guild_id2 && g->alliance[i].opposition == flag );
1416         return( i < MAX_GUILDALLIANCE ) ? 1 : 0;
1417 }
1418
1419 /*====================================================
1420  * Player sd, asking player tsd an alliance between their 2 guilds
1421  *---------------------------------------------------*/
1422 int guild_reqalliance(struct map_session_data *sd,struct map_session_data *tsd) {
1423         struct guild *g[2];
1424         int i;
1425
1426         if(is_agit_start()) {   // Disable alliance creation during woe [Valaris]
1427                 clif_displaymessage(sd->fd,msg_txt(sd,676)); //"Alliances cannot be made during Guild Wars!"
1428                 return 0;
1429         }       // end addition [Valaris]
1430
1431
1432         nullpo_ret(sd);
1433
1434         if(tsd==NULL || tsd->status.guild_id<=0)
1435                 return 0;
1436
1437         // Check, is tsd guild master, if not - cancel alliance. [f0und3r]
1438         if (battle_config.guild_alliance_onlygm && !tsd->state.gmaster_flag) {
1439                 clif_guild_allianceack(sd, 5);
1440                 return 0;
1441         }
1442
1443         g[0]=sd->guild;
1444         g[1]=tsd->guild;
1445
1446         if(g[0]==NULL || g[1]==NULL)
1447                 return 0;
1448
1449         // Prevent creation alliance with same guilds [LuzZza]
1450         if(sd->status.guild_id == tsd->status.guild_id)
1451                 return 0;
1452
1453         if( guild_get_alliance_count(g[0],0) >= battle_config.max_guild_alliance ) {
1454                 clif_guild_allianceack(sd,4);
1455                 return 0;
1456         }
1457         if( guild_get_alliance_count(g[1],0) >= battle_config.max_guild_alliance ) {
1458                 clif_guild_allianceack(sd,3);
1459                 return 0;
1460         }
1461
1462         if( tsd->guild_alliance>0 ){
1463                 clif_guild_allianceack(sd,1);
1464                 return 0;
1465         }
1466
1467     for (i = 0; i < MAX_GUILDALLIANCE; i++) { // check if already allied
1468                 if(     g[0]->alliance[i].guild_id==tsd->status.guild_id &&
1469                         g[0]->alliance[i].opposition==0){
1470                         clif_guild_allianceack(sd,0);
1471                         return 0;
1472                 }
1473         }
1474
1475         tsd->guild_alliance=sd->status.guild_id;
1476         tsd->guild_alliance_account=sd->status.account_id;
1477
1478         clif_guild_reqalliance(tsd,sd->status.account_id,g[0]->name);
1479         return 0;
1480 }
1481
1482 /*====================================================
1483  * Player sd, answer to player tsd (account_id) for an alliance request
1484  *---------------------------------------------------*/
1485 int guild_reply_reqalliance(struct map_session_data *sd,uint32 account_id,int flag) {
1486         struct map_session_data *tsd;
1487
1488         nullpo_ret(sd);
1489         tsd= map_id2sd( account_id );
1490         if (!tsd) { //Character left? Cancel alliance.
1491                 clif_guild_allianceack(sd,3);
1492                 return 0;
1493         }
1494
1495         if (sd->guild_alliance != tsd->status.guild_id) // proposed guild_id alliance doesn't match tsd guildid
1496                 return 0;
1497
1498         if (flag == 1) { // consent
1499                 int i;
1500
1501         struct guild *g, *tg; // Reconfirm the number of alliance
1502                 g=sd->guild;
1503                 tg=tsd->guild;
1504
1505                 if(g==NULL || guild_get_alliance_count(g,0) >= battle_config.max_guild_alliance){
1506                         clif_guild_allianceack(sd,4);
1507                         clif_guild_allianceack(tsd,3);
1508                         return 0;
1509                 }
1510                 if(tg==NULL || guild_get_alliance_count(tg,0) >= battle_config.max_guild_alliance){
1511                         clif_guild_allianceack(sd,3);
1512                         clif_guild_allianceack(tsd,4);
1513                         return 0;
1514                 }
1515
1516                 for(i=0;i<MAX_GUILDALLIANCE;i++){
1517                         if(g->alliance[i].guild_id==tsd->status.guild_id &&
1518                                 g->alliance[i].opposition==1)
1519                                 intif_guild_alliance( sd->status.guild_id,tsd->status.guild_id,
1520                                         sd->status.account_id,tsd->status.account_id,9 );
1521                 }
1522                 for(i=0;i<MAX_GUILDALLIANCE;i++){
1523                         if(tg->alliance[i].guild_id==sd->status.guild_id &&
1524                                 tg->alliance[i].opposition==1)
1525                                 intif_guild_alliance( tsd->status.guild_id,sd->status.guild_id,
1526                                         tsd->status.account_id,sd->status.account_id,9 );
1527                 }
1528
1529         // inform other servers
1530                 intif_guild_alliance( sd->status.guild_id,tsd->status.guild_id,
1531                         sd->status.account_id,tsd->status.account_id,0 );
1532                 return 0;
1533         } else { // deny
1534                 sd->guild_alliance=0;
1535                 sd->guild_alliance_account=0;
1536                 if(tsd!=NULL)
1537                         clif_guild_allianceack(tsd,3);
1538         }
1539         return 0;
1540 }
1541
1542 /*====================================================
1543  * Player sd asking to break alliance with guild guild_id
1544  *---------------------------------------------------*/
1545 int guild_delalliance(struct map_session_data *sd,int guild_id,int flag) {
1546         nullpo_ret(sd);
1547
1548         if(is_agit_start()) {   // Disable alliance breaking during woe [Valaris]
1549                 clif_displaymessage(sd->fd,msg_txt(sd,677)); //"Alliances cannot be broken during Guild Wars!"
1550                 return 0;
1551         }       // end addition [Valaris]
1552
1553         intif_guild_alliance( sd->status.guild_id,guild_id,sd->status.account_id,0,flag|8 );
1554         return 0;
1555 }
1556
1557 /*====================================================
1558  * Player sd, asking player tsd a formal enemy relation between their 2 guilds
1559  *---------------------------------------------------*/
1560 int guild_opposition(struct map_session_data *sd,struct map_session_data *tsd) {
1561         struct guild *g;
1562         int i;
1563
1564         nullpo_ret(sd);
1565
1566         g=sd->guild;
1567         if(g==NULL || tsd==NULL)
1568                 return 0;
1569
1570         // Prevent creation opposition with same guilds [LuzZza]
1571         if(sd->status.guild_id == tsd->status.guild_id)
1572                 return 0;
1573
1574         if( guild_get_alliance_count(g,1) >= battle_config.max_guild_alliance ) {
1575                 clif_guild_oppositionack(sd,1);
1576                 return 0;
1577         }
1578
1579         for (i = 0; i < MAX_GUILDALLIANCE; i++) { // checking relations
1580                 if(g->alliance[i].guild_id==tsd->status.guild_id){
1581                         if (g->alliance[i].opposition == 1) { // check if not already hostile
1582                                 clif_guild_oppositionack(sd,2);
1583                                 return 0;
1584                         }
1585                         if(is_agit_start()) // Prevent the changing of alliances to oppositions during WoE.
1586                                 return 0;
1587                         //Change alliance to opposition.
1588                         intif_guild_alliance( sd->status.guild_id,tsd->status.guild_id,
1589                                 sd->status.account_id,tsd->status.account_id,8 );
1590                 }
1591         }
1592
1593         // inform other serv
1594         intif_guild_alliance( sd->status.guild_id,tsd->status.guild_id,
1595                         sd->status.account_id,tsd->status.account_id,1 );
1596         return 0;
1597 }
1598
1599 /*====================================================
1600  * Notification of a relationship between 2 guilds
1601  *---------------------------------------------------*/
1602 int guild_allianceack(int guild_id1,int guild_id2,uint32 account_id1,uint32 account_id2,int flag,const char *name1,const char *name2)
1603 {
1604         struct guild *g[2];
1605         int guild_id[2];
1606         const char *guild_name[2];
1607         struct map_session_data *sd[2];
1608         int j,i;
1609
1610         guild_id[0] = guild_id1;
1611         guild_id[1] = guild_id2;
1612         guild_name[0] = name1;
1613         guild_name[1] = name2;
1614         sd[0] = map_id2sd(account_id1);
1615         sd[1] = map_id2sd(account_id2);
1616
1617         g[0]=guild_search(guild_id1);
1618         g[1]=guild_search(guild_id2);
1619
1620         if(sd[0]!=NULL && (flag&0x0f)==0){
1621                 sd[0]->guild_alliance=0;
1622                 sd[0]->guild_alliance_account=0;
1623         }
1624
1625         if (flag & 0x70) { // failure
1626                 for(i=0;i<2-(flag&1);i++)
1627                         if( sd[i]!=NULL )
1628                                 clif_guild_allianceack(sd[i],((flag>>4)==i+1)?3:4);
1629                 return 0;
1630         }
1631
1632         if (!(flag & 0x08)) { // new relationship
1633                 for(i=0;i<2-(flag&1);i++) {
1634                         if(g[i]!=NULL) {
1635                                 ARR_FIND( 0, MAX_GUILDALLIANCE, j, g[i]->alliance[j].guild_id == 0 );
1636                                 if( j < MAX_GUILDALLIANCE ) {
1637                                         g[i]->alliance[j].guild_id=guild_id[1-i];
1638                                         memcpy(g[i]->alliance[j].name,guild_name[1-i],NAME_LENGTH);
1639                                         g[i]->alliance[j].opposition=flag&1;
1640                                 }
1641                         }
1642                 }
1643         } else { // remove relationship
1644                 for(i=0;i<2-(flag&1);i++) {
1645                         if(g[i]!=NULL) {
1646                                 for(j=0;j<g[i]->max_member;j++) channel_pcquit(g[i]->member[j].sd,2); //leave all alliance chan
1647                                 ARR_FIND( 0, MAX_GUILDALLIANCE, j, g[i]->alliance[j].guild_id == guild_id[1-i] && g[i]->alliance[j].opposition == (flag&1) );
1648                                 if( j < MAX_GUILDALLIANCE )
1649                                         g[i]->alliance[j].guild_id = 0;
1650                         }
1651                 if (sd[i] != NULL) // notify players
1652                                 clif_guild_delalliance(sd[i],guild_id[1-i],(flag&1));
1653                 }
1654         }
1655
1656         if ((flag & 0x0f) == 0) { // alliance notification
1657                 if( sd[1]!=NULL )
1658                         clif_guild_allianceack(sd[1],2);
1659         } else if ((flag & 0x0f) == 1) { // enemy notification
1660                 if( sd[0]!=NULL )
1661                         clif_guild_oppositionack(sd[0],0);
1662         }
1663
1664
1665         for (i = 0; i < 2 - (flag & 1); i++) { // Retransmission of the relationship list to all members
1666                 if(g[i]!=NULL)
1667                         for(j=0;j<g[i]->max_member;j++) {
1668                                 struct map_session_data *sd_mem = g[i]->member[j].sd;
1669                                 if( sd_mem!=NULL){
1670                                         clif_guild_allianceinfo(sd_mem);
1671
1672                                         // join ally channel
1673                                         if( channel_config.ally_tmpl.name != NULL && (channel_config.ally_tmpl.opt&CHAN_OPT_AUTOJOIN) ) {
1674                                                 channel_gjoin(sd_mem,2);
1675                                         }
1676                                 }
1677                         }
1678         }
1679         return 0;
1680 }
1681
1682 /**
1683  * Notification for the guild disbanded
1684  * @see DBApply
1685  */
1686 int guild_broken_sub(DBKey key, DBData *data, va_list ap) {
1687         struct guild *g = (struct guild *)db_data2ptr(data);
1688         int guild_id=va_arg(ap,int);
1689         int i,j;
1690         struct map_session_data *sd=NULL;
1691
1692         nullpo_ret(g);
1693
1694         for(i=0;i<MAX_GUILDALLIANCE;i++){       // Destroy all relationships
1695                 if(g->alliance[i].guild_id==guild_id){
1696                         for(j=0;j<g->max_member;j++)
1697                                 if( (sd=g->member[j].sd)!=NULL )
1698                                         clif_guild_delalliance(sd,guild_id,g->alliance[i].opposition);
1699                         intif_guild_alliance(g->guild_id, guild_id,0,0,g->alliance[i].opposition|8);
1700                         g->alliance[i].guild_id=0;
1701                 }
1702         }
1703         return 0;
1704 }
1705
1706 /**
1707  * Invoked on Castles when a guild is broken. [Skotlex]
1708  * @see DBApply
1709  */
1710 int castle_guild_broken_sub(DBKey key, DBData *data, va_list ap)
1711 {
1712         struct guild_castle *gc = (struct guild_castle *)db_data2ptr(data);
1713         int guild_id = va_arg(ap, int);
1714
1715         nullpo_ret(gc);
1716
1717         if (gc->guild_id == guild_id) {
1718                 char name[EVENT_NAME_LENGTH];
1719                 // We call castle_event::OnGuildBreak of all castles of the guild
1720                 // You can set all castle_events in the 'db/castle_db.txt'
1721                 safesnprintf(name, EVENT_NAME_LENGTH, "%s::%s", gc->castle_event, script_config.guild_break_event_name);
1722                 npc_event_do(name);
1723
1724                 //Save the new 'owner', this should invoke guardian clean up and other such things.
1725                 guild_castledatasave(gc->castle_id, 1, 0);
1726         }
1727         return 0;
1728 }
1729
1730 //Invoked on /breakguild "Guild name"
1731 int guild_broken(int guild_id,int flag) {
1732         struct guild *g = guild_search(guild_id);
1733         int i;
1734
1735         if (flag != 0 || g == NULL)
1736                 return 0;
1737
1738         for (i = 0; i < g->max_member; i++){    // Destroy all relationships
1739                 struct map_session_data *sd = g->member[i].sd;
1740                 if(sd != NULL){
1741                         if(sd->state.storage_flag == 2)
1742                                 storage_guild_storage_quit(sd,1);
1743                         sd->status.guild_id=0;
1744                         sd->guild = NULL;
1745                         sd->state.gmaster_flag = 0;
1746                         clif_guild_broken(g->member[i].sd,0);
1747                         clif_name_area(&sd->bl); // [LuzZza]
1748                         status_change_end(&sd->bl,SC_LEADERSHIP,INVALID_TIMER);
1749                         status_change_end(&sd->bl,SC_GLORYWOUNDS,INVALID_TIMER);
1750                         status_change_end(&sd->bl,SC_SOULCOLD,INVALID_TIMER);
1751                         status_change_end(&sd->bl,SC_HAWKEYES,INVALID_TIMER);
1752                 }
1753         }
1754
1755         guild_db->foreach(guild_db,guild_broken_sub,guild_id);
1756         castle_db->foreach(castle_db,castle_guild_broken_sub,guild_id);
1757         storage_guild_delete(guild_id);
1758         if( channel_config.ally_tmpl.name != NULL ) {
1759                 channel_delete(g->channel,false);
1760         }
1761         idb_remove(guild_db,guild_id);
1762         return 0;
1763 }
1764
1765 /** Changes the Guild Master to the specified player. [Skotlex]
1766 * @param guild_id
1767 * @param sd New guild master
1768 */
1769 int guild_gm_change(int guild_id, uint32 char_id) {
1770         struct guild *g;
1771         char *name;
1772         int i;
1773
1774         g = guild_search(guild_id);
1775
1776         nullpo_ret(g);
1777
1778         ARR_FIND(0, MAX_GUILD, i, g->member[i].char_id == char_id);
1779         
1780         if( i == MAX_GUILD ){
1781                 // Not part of the guild
1782                 return 0;
1783         }
1784
1785         name = g->member[i].name;
1786
1787         if (strcmp(g->master, name) == 0) //Nothing to change.
1788                 return 0;
1789
1790         //Notify servers that master has changed.
1791         intif_guild_change_gm(guild_id, name, strlen(name)+1);
1792         return 1;
1793 }
1794
1795 /** Notification from Char server that a guild's master has changed. [Skotlex]
1796 * @param guild_id
1797 * @param account_id
1798 * @param char_id
1799 */
1800 int guild_gm_changed(int guild_id, uint32 account_id, uint32 char_id, time_t time) {
1801         struct guild *g;
1802         struct guild_member gm;
1803         int pos, i;
1804
1805         g=guild_search(guild_id);
1806
1807         if (!g)
1808                 return 0;
1809
1810         for(pos=0; pos<g->max_member && !(
1811                 g->member[pos].account_id==account_id &&
1812                 g->member[pos].char_id==char_id);
1813                 pos++);
1814
1815         if (pos == 0 || pos == g->max_member) return 0;
1816
1817         memcpy(&gm, &g->member[pos], sizeof (struct guild_member));
1818         memcpy(&g->member[pos], &g->member[0], sizeof(struct guild_member));
1819         memcpy(&g->member[0], &gm, sizeof(struct guild_member));
1820
1821         g->member[pos].position = g->member[0].position;
1822         g->member[0].position = 0; //Position 0: guild Master.
1823         strcpy(g->master, g->member[0].name);
1824
1825         if (g->member[pos].sd && g->member[pos].sd->fd) {
1826                 clif_displaymessage(g->member[pos].sd->fd, msg_txt(g->member[pos].sd,678)); //"You no longer are the Guild Master."
1827                 g->member[pos].sd->state.gmaster_flag = 0;
1828                 clif_name_area(&g->member[pos].sd->bl);
1829         }
1830
1831         if (g->member[0].sd && g->member[0].sd->fd) {
1832                 clif_displaymessage(g->member[0].sd->fd, msg_txt(g->member[pos].sd,679)); //"You have become the Guild Master!"
1833                 g->member[0].sd->state.gmaster_flag = 1;
1834                 clif_name_area(&g->member[0].sd->bl);
1835                 //Block his skills to prevent abuse.
1836                 if (battle_config.guild_skill_relog_delay)
1837                         guild_block_skill(g->member[0].sd, battle_config.guild_skill_relog_delay);
1838         }
1839
1840         // announce the change to all guild members
1841         for( i = 0; i < g->max_member; i++ ) {
1842                 if( g->member[i].sd && g->member[i].sd->fd ) {
1843                         clif_guild_basicinfo(g->member[i].sd);
1844                         clif_guild_memberlist(g->member[i].sd);
1845                         clif_guild_belonginfo(g->member[i].sd); // Update clientside guildmaster flag
1846                 }
1847         }
1848
1849         // Store changing time
1850         g->last_leader_change = time;
1851
1852         return 1;
1853 }
1854
1855 /** Disband a guild
1856 * @param sd Player who breaks the guild
1857 * @param name Guild name
1858 */
1859 int guild_break(struct map_session_data *sd,char *name) {
1860         struct guild *g;
1861         struct unit_data *ud;
1862         int i;
1863 #ifdef BOUND_ITEMS
1864         int j;
1865         int idxlist[MAX_INVENTORY];
1866 #endif
1867
1868         nullpo_ret(sd);
1869
1870         if ((g=sd->guild)==NULL)
1871                 return 0;
1872         if (strcmp(g->name,name) != 0)
1873                 return 0;
1874         if (!sd->state.gmaster_flag)
1875                 return 0;
1876         for (i = 0; i < g->max_member; i++) {
1877                 if(     g->member[i].account_id>0 && (
1878                         g->member[i].account_id!=sd->status.account_id ||
1879                         g->member[i].char_id!=sd->status.char_id ))
1880                         break;
1881         }
1882         if (i < g->max_member) {
1883                 clif_guild_broken(sd,2);
1884                 return 0;
1885         }
1886
1887         if (g->instance_id)
1888                 instance_destroy(g->instance_id);
1889
1890         /* Regardless of char server allowing it, we clear the guild master's auras */
1891         if ((ud = unit_bl2ud(&sd->bl))) {
1892                 int count = 0;
1893                 struct skill_unit_group *group[4];
1894
1895                 for(i = 0; i < MAX_SKILLUNITGROUP && ud->skillunit[i]; i++) {
1896                         switch(ud->skillunit[i]->skill_id) {
1897                                 case GD_LEADERSHIP:
1898                                 case GD_GLORYWOUNDS:
1899                                 case GD_SOULCOLD:
1900                                 case GD_HAWKEYES:
1901                                         if(count == 4)
1902                                                 ShowWarning("guild_break: '%s' got more than 4 guild aura instances! (%d)\n",sd->status.name,ud->skillunit[i]->skill_id);
1903                                         else
1904                                                 group[count++] = ud->skillunit[i];
1905                                         break;
1906                         }
1907                 }
1908                 for (i = 0; i < count; i++)
1909                         skill_delunitgroup(group[i]);
1910         }
1911
1912 #ifdef BOUND_ITEMS
1913         //Guild bound item check - Removes the bound flag
1914         j = pc_bound_chk(sd,BOUND_GUILD,idxlist);
1915         for(i = 0; i < j; i++)
1916                 pc_delitem(sd,idxlist[i],sd->inventory.u.items_inventory[idxlist[i]].amount,0,1,LOG_TYPE_BOUND_REMOVAL);
1917 #endif
1918
1919         intif_guild_break(g->guild_id);
1920         return 1;
1921 }
1922
1923 /**
1924  * Creates a list of guild castle IDs to be requested
1925  * from char-server.
1926  */
1927 void guild_castle_map_init(void) {
1928         int num = db_size(castle_db);
1929
1930         if (num > 0) {
1931                 struct guild_castle* gc = NULL;
1932                 int *castle_ids, *cursor;
1933                 DBIterator* iter = NULL;
1934
1935                 CREATE(castle_ids, int, num);
1936                 cursor = castle_ids;
1937                 iter = db_iterator(castle_db);
1938                 for (gc = (struct guild_castle*)dbi_first(iter); dbi_exists(iter); gc = (struct guild_castle*)dbi_next(iter)) {
1939                         *(cursor++) = gc->castle_id;
1940                 }
1941                 dbi_destroy(iter);
1942                 if (intif_guild_castle_dataload(num, castle_ids))
1943                         ShowStatus("Requested '"CL_WHITE"%d"CL_RESET"' guild castles from char-server...\n", num);
1944                 aFree(castle_ids);
1945         }
1946 }
1947
1948 /**
1949  * Setter function for members of guild_castle struct.
1950  * Handles all side-effects, like updating guardians.
1951  * Sends updated info to char-server for saving.
1952  * @param castle_id Castle ID
1953  * @param index Type of data to change
1954  * @param value New value
1955  */
1956 int guild_castledatasave(int castle_id, int index, int value) {
1957         struct guild_castle *gc = guild_castle_search(castle_id);
1958
1959         if (gc == NULL) {
1960                 ShowWarning("guild_castledatasave: guild castle '%d' not found\n", castle_id);
1961                 return 0;
1962         }
1963
1964         switch (index) {
1965         case 1: // The castle's owner has changed? Update or remove Guardians too. [Skotlex]
1966         {
1967                 int i;
1968                 gc->guild_id = value;
1969                 for (i = 0; i < MAX_GUARDIANS; i++){
1970                         struct mob_data *gd;
1971                         if (gc->guardian[i].visible && (gd = map_id2md(gc->guardian[i].id)) != NULL)
1972                                 mob_guardian_guildchange(gd);
1973                 }
1974                 break;
1975         }
1976         case 2:
1977                 gc->economy = value; break;
1978         case 3: // defense invest change -> recalculate guardian hp
1979         {
1980                 int i;
1981                 gc->defense = value;
1982                 for (i = 0; i < MAX_GUARDIANS; i++){
1983                         struct mob_data *gd;
1984                         if (gc->guardian[i].visible && (gd = map_id2md(gc->guardian[i].id)) != NULL)
1985                                 status_calc_mob(gd, SCO_NONE);
1986                 }
1987                 break;
1988         }
1989         case 4:
1990                 gc->triggerE = value; break;
1991         case 5:
1992                 gc->triggerD = value; break;
1993         case 6:
1994                 gc->nextTime = value; break;
1995         case 7:
1996                 gc->payTime = value; break;
1997         case 8:
1998                 gc->createTime = value; break;
1999         case 9:
2000                 gc->visibleC = value; break;
2001         default:
2002                 if (index > 9 && index <= 9+MAX_GUARDIANS) {
2003                         gc->guardian[index-10].visible = value;
2004                         break;
2005                 }
2006                 ShowWarning("guild_castledatasave: index = '%d' is out of allowed range\n", index);
2007                 return 0;
2008         }
2009
2010         if (!intif_guild_castle_datasave(castle_id, index, value)) {
2011                 guild_castle_reconnect(castle_id, index, value);
2012         }
2013         return 0;
2014 }
2015
2016 void guild_castle_reconnect_sub(void *key, void *data, va_list ap) {
2017         int castle_id = GetWord((int)__64BPRTSIZE(key), 0);
2018         int index = GetWord((int)__64BPRTSIZE(key), 1);
2019         intif_guild_castle_datasave(castle_id, index, *(int *)data);
2020         aFree(data);
2021 }
2022
2023 /**
2024  * Saves pending guild castle data changes when char-server is
2025  * disconnected.
2026  * On reconnect pushes all changes to char-server for saving.
2027  * @param castle_id
2028  * @param index
2029  * @param value
2030  */
2031 void guild_castle_reconnect(int castle_id, int index, int value) {
2032         static struct linkdb_node *gc_save_pending = NULL;
2033
2034         if (castle_id < 0) { // char-server reconnected
2035                 linkdb_foreach(&gc_save_pending, guild_castle_reconnect_sub);
2036                 linkdb_final(&gc_save_pending);
2037         } else {
2038                 int *data;
2039                 CREATE(data, int, 1);
2040                 *data = value;
2041                 linkdb_replace(&gc_save_pending, (void*)__64BPRTSIZE((MakeDWord(castle_id, index))), data);
2042         }
2043 }
2044
2045 /** Load castle data then invoke OnAgitInit* on last
2046 * @param len
2047 * @param gc Guild Castle data
2048 */
2049 int guild_castledataloadack(int len, struct guild_castle *gc) {
2050         int i;
2051         int n = (len-4) / sizeof(struct guild_castle);
2052         int ev;
2053
2054         nullpo_ret(gc);
2055
2056         //Last owned castle in the list invokes ::OnAgitInit
2057         for( i = n-1; i >= 0 && !(gc[i].guild_id); --i );
2058         ev = i; // offset of castle or -1
2059
2060         if( ev < 0 ) { //No castles owned, invoke OnAgitInit as it is.
2061                 npc_event_doall( script_config.agit_init_event_name );
2062                 npc_event_doall( script_config.agit_init2_event_name );
2063                 npc_event_doall( script_config.agit_init3_event_name );
2064         } else // load received castles into memory, one by one
2065         for( i = 0; i < n; i++, gc++ ) {
2066                 struct guild_castle *c = guild_castle_search(gc->castle_id);
2067                 if (!c) {
2068                         ShowError("guild_castledataloadack: castle id=%d not found.\n", gc->castle_id);
2069                         continue;
2070                 }
2071
2072                 // update map-server castle data with new info
2073                 memcpy(&c->guild_id, &gc->guild_id, sizeof(struct guild_castle) - offsetof(struct guild_castle, guild_id));
2074
2075                 if( c->guild_id ) {
2076                         if( i != ev )
2077                                 guild_request_info(c->guild_id);
2078                         else { // last owned one
2079                                 char event_name[EVENT_NAME_LENGTH];
2080
2081                                 snprintf( event_name, EVENT_NAME_LENGTH, "::%s", script_config.agit_init_event_name );
2082                                 guild_npc_request_info(c->guild_id, event_name);
2083                                 snprintf( event_name, EVENT_NAME_LENGTH, "::%s", script_config.agit_init2_event_name );
2084                                 guild_npc_request_info(c->guild_id, event_name);
2085                                 snprintf( event_name, EVENT_NAME_LENGTH, "::%s", script_config.agit_init3_event_name );
2086                                 guild_npc_request_info(c->guild_id, event_name);
2087                         }
2088                 }
2089         }
2090         ShowStatus("Received '"CL_WHITE"%d"CL_RESET"' guild castles from char-server.\n", n);
2091         return 0;
2092 }
2093
2094 /**
2095  * Start WoE:FE and triggers all npc OnAgitStart
2096  */
2097 bool guild_agit_start(void){
2098         if( agit_flag ){
2099                 return false;
2100         }
2101
2102         agit_flag = true;
2103
2104         npc_event_runall( script_config.agit_start_event_name );
2105
2106         return true;
2107 }
2108
2109 /**
2110  * End WoE:FE and triggers all npc OnAgitEnd
2111  */
2112 bool guild_agit_end(void){
2113         if( !agit_flag ){
2114                 return false;
2115         }
2116
2117         agit_flag = false;
2118
2119         npc_event_runall( script_config.agit_end_event_name );
2120
2121         return true;
2122 }
2123
2124 /**
2125  * Start WoE:SE and triggers all npc OnAgitStart2
2126  */
2127 bool guild_agit2_start(void){
2128         if( agit2_flag ){
2129                 return false;
2130         }
2131
2132         agit2_flag = true;
2133
2134         npc_event_runall( script_config.agit_start2_event_name );
2135
2136         return true;
2137 }
2138
2139 /**
2140  * End WoE:SE and triggers all npc OnAgitEnd2
2141  */
2142 bool guild_agit2_end(void){
2143         if( !agit2_flag ){
2144                 return false;
2145         }
2146
2147         agit2_flag = false;
2148
2149         npc_event_runall( script_config.agit_end2_event_name );
2150
2151         return true;
2152 }
2153
2154 /**
2155  * Start WoE:TE and triggers all npc OnAgitStart3
2156  */
2157 bool guild_agit3_start(void){
2158         if( agit3_flag ){
2159                 return false;
2160         }
2161
2162         agit3_flag = true;
2163
2164         npc_event_runall( script_config.agit_start3_event_name );
2165
2166         return true;
2167 }
2168
2169 /**
2170  * End WoE:TE and triggers all npc OnAgitEnd3
2171  */
2172 bool guild_agit3_end(void){
2173         if( !agit3_flag ){
2174                 return false;
2175         }
2176
2177         agit3_flag = false;
2178
2179         npc_event_runall( script_config.agit_end3_event_name );
2180
2181         return true;
2182 }
2183
2184 // How many castles does this guild have?
2185 int guild_checkcastles(struct guild *g) {
2186         int nb_cas = 0;
2187         struct guild_castle* gc = NULL;
2188         DBIterator *iter = db_iterator(castle_db);
2189
2190         for (gc = (struct guild_castle*)dbi_first(iter); dbi_exists(iter); gc = (struct guild_castle*)dbi_next(iter)) {
2191                 if (gc->guild_id == g->guild_id) {
2192                         nb_cas++;
2193                 }
2194         }
2195         dbi_destroy(iter);
2196         return nb_cas;
2197 }
2198
2199 // Are these two guilds allied?
2200 bool guild_isallied(int guild_id, int guild_id2) {
2201         int i;
2202         struct guild* g = guild_search(guild_id);
2203         nullpo_ret(g);
2204
2205         ARR_FIND( 0, MAX_GUILDALLIANCE, i, g->alliance[i].guild_id == guild_id2 );
2206         return( i < MAX_GUILDALLIANCE && g->alliance[i].opposition == 0 );
2207 }
2208
2209 void guild_flag_add(struct npc_data *nd) {
2210         int i;
2211
2212         /* check */
2213         for( i = 0; i < guild_flags_count; i++ ) {
2214                 if( guild_flags[i] && guild_flags[i]->bl.id == nd->bl.id ) {
2215                         return;/* exists, most likely updated the id. */
2216                 }
2217         }
2218
2219         i = guild_flags_count;/* save the current slot */
2220         /* add */
2221         RECREATE(guild_flags,struct npc_data*,++guild_flags_count);
2222         /* save */
2223         guild_flags[i] = nd;
2224 }
2225
2226 void guild_flag_remove(struct npc_data *nd) {
2227         int i, cursor;
2228         if( guild_flags_count == 0 )
2229                 return;
2230         /* find it */
2231         for( i = 0; i < guild_flags_count; i++ ) {
2232                 if( guild_flags[i] && guild_flags[i]->bl.id == nd->bl.id ) {/* found */
2233                         guild_flags[i] = NULL;
2234                         break;
2235                 }
2236         }
2237
2238         /* compact list */
2239         for( i = 0, cursor = 0; i < guild_flags_count; i++ ) {
2240                 if( guild_flags[i] == NULL )
2241                         continue;
2242
2243                 if( cursor != i ) {
2244                         memmove(&guild_flags[cursor], &guild_flags[i], sizeof(struct npc_data*));
2245                 }
2246
2247                 cursor++;
2248         }
2249 }
2250
2251 /**
2252  * @see DBApply
2253  */
2254 static int eventlist_db_final(DBKey key, DBData *data, va_list ap) {
2255         struct eventlist *next = NULL;
2256         struct eventlist *current = (struct eventlist *)db_data2ptr(data);
2257         while (current != NULL) {
2258                 next = current->next;
2259                 aFree(current);
2260                 current = next;
2261         }
2262         return 0;
2263 }
2264
2265 /**
2266  * @see DBApply
2267  */
2268 static int guild_expcache_db_final(DBKey key, DBData *data, va_list ap) {
2269         ers_free(expcache_ers, db_data2ptr(data));
2270         return 0;
2271 }
2272
2273 /**
2274  * @see DBApply
2275  */
2276 static int guild_castle_db_final(DBKey key, DBData *data, va_list ap) {
2277         struct guild_castle* gc = (struct guild_castle *)db_data2ptr(data);
2278         if( gc->temp_guardians )
2279                 aFree(gc->temp_guardians);
2280         aFree(gc);
2281         return 0;
2282 }
2283
2284 /* called when scripts are reloaded/unloaded */
2285 void guild_flags_clear(void) {
2286         int i;
2287         for( i = 0; i < guild_flags_count; i++ ) {
2288                 if( guild_flags[i] )
2289                         guild_flags[i] = NULL;
2290         }
2291
2292         guild_flags_count = 0;
2293 }
2294
2295 void do_init_guild(void) {
2296         const char* dbsubpath[] = {
2297                 "",
2298                 "/"DBIMPORT,
2299         };
2300         int i;
2301         
2302         guild_db           = idb_alloc(DB_OPT_RELEASE_DATA);
2303         castle_db          = idb_alloc(DB_OPT_BASE);
2304         guild_expcache_db  = idb_alloc(DB_OPT_BASE);
2305         guild_infoevent_db = idb_alloc(DB_OPT_BASE);
2306         expcache_ers = ers_new(sizeof(struct guild_expcache),"guild.c::expcache_ers",ERS_OPT_NONE);
2307
2308         guild_flags_count = 0;
2309
2310         memset(guild_skill_tree,0,sizeof(guild_skill_tree));
2311         
2312         for(i=0; i<ARRAYLENGTH(dbsubpath); i++){
2313                 int n1 = strlen(db_path)+strlen(dbsubpath[i])+1;
2314                 char* dbsubpath1 = (char*)aMalloc(n1+1);
2315                 safesnprintf(dbsubpath1,n1+1,"%s%s",db_path,dbsubpath[i]);
2316                 
2317                 sv_readdb(dbsubpath1, "castle_db.txt", ',', 4, 4, -1, &guild_read_castledb, i);
2318                 sv_readdb(dbsubpath1, "guild_skill_tree.txt", ',', 2+MAX_GUILD_SKILL_REQUIRE*2, 2+MAX_GUILD_SKILL_REQUIRE*2, -1, &guild_read_guildskill_tree_db, i); //guild skill tree [Komurka]
2319                 
2320                 aFree(dbsubpath1);
2321         }
2322         
2323         add_timer_func_list(guild_payexp_timer,"guild_payexp_timer");
2324         add_timer_func_list(guild_send_xy_timer, "guild_send_xy_timer");
2325         add_timer_interval(gettick()+GUILD_PAYEXP_INTERVAL,guild_payexp_timer,0,0,GUILD_PAYEXP_INTERVAL);
2326         add_timer_interval(gettick()+GUILD_SEND_XY_INTERVAL,guild_send_xy_timer,0,0,GUILD_SEND_XY_INTERVAL);
2327 }
2328
2329 void do_final_guild(void) {
2330         DBIterator *iter = db_iterator(guild_db);
2331         struct guild *g;
2332
2333         for( g = (struct guild *)dbi_first(iter); dbi_exists(iter); g = (struct guild *)dbi_next(iter) ) {
2334                 channel_delete(g->channel,false);
2335         }
2336         dbi_destroy(iter);
2337
2338         db_destroy(guild_db);
2339         castle_db->destroy(castle_db,guild_castle_db_final);
2340         guild_expcache_db->destroy(guild_expcache_db,guild_expcache_db_final);
2341         guild_infoevent_db->destroy(guild_infoevent_db,eventlist_db_final);
2342         ers_destroy(expcache_ers);
2343
2344         aFree(guild_flags);/* never empty; created on boot */
2345 }