summaryrefslogtreecommitdiffabout
Side-by-side diff
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--gammu/emb/common/service/gsmmisc.c4
-rw-r--r--gammu/emb/common/service/gsmpbk.c17
-rw-r--r--gammu/emb/gammu/gammu.c2
-rw-r--r--kabc/addressbook.cpp148
-rw-r--r--kabc/addressbook.h2
-rw-r--r--kabc/addressee.cpp46
-rw-r--r--kabc/addressee.h1
-rw-r--r--kabc/phonenumber.cpp4
-rw-r--r--kaddressbook/kabcore.cpp86
-rw-r--r--libkdepim/ksyncprefsdialog.cpp11
10 files changed, 217 insertions, 104 deletions
diff --git a/gammu/emb/common/service/gsmmisc.c b/gammu/emb/common/service/gsmmisc.c
index 6959a22..1c6ec8b 100644
--- a/gammu/emb/common/service/gsmmisc.c
+++ b/gammu/emb/common/service/gsmmisc.c
@@ -1,262 +1,262 @@
/* (c) 2002-2004 by Marcin Wiacek */
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#ifdef WIN32
# include <io.h>
# include <fcntl.h>
#endif
#include "../misc/coding/coding.h"
#include "../gsmcomon.h"
#include "gsmmisc.h"
struct keys_table_position {
char whatchar;
int whatcode;
};
static struct keys_table_position Keys[] = {
{'m',GSM_KEY_MENU}, {'M',GSM_KEY_MENU},
{'n',GSM_KEY_NAMES}, {'N',GSM_KEY_NAMES},
{'p',GSM_KEY_POWER}, {'P',GSM_KEY_POWER},
{'u',GSM_KEY_UP}, {'U',GSM_KEY_UP},
{'d',GSM_KEY_DOWN}, {'D',GSM_KEY_DOWN},
{'+',GSM_KEY_INCREASEVOLUME}, {'-',GSM_KEY_DECREASEVOLUME},
{'1',GSM_KEY_1}, {'2',GSM_KEY_2}, {'3',GSM_KEY_3},
{'4',GSM_KEY_4}, {'5',GSM_KEY_5}, {'6',GSM_KEY_6},
{'7',GSM_KEY_7}, {'8',GSM_KEY_8}, {'9',GSM_KEY_9},
{'*',GSM_KEY_ASTERISK}, {'0',GSM_KEY_0}, {'#',GSM_KEY_HASH},
{'g',GSM_KEY_GREEN}, {'G',GSM_KEY_GREEN},
{'r',GSM_KEY_RED}, {'R',GSM_KEY_RED},
{' ',0}
};
GSM_Error MakeKeySequence(char *text, GSM_KeyCode *KeyCode, int *Length)
{
int i,j;
unsigned char key;
for (i=0;i<(int)(strlen(text));i++) {
key = text[i];
KeyCode[i] = GSM_KEY_NONE;
j = 0;
while (Keys[j].whatchar!=' ') {
if (Keys[j].whatchar==key) {
KeyCode[i]=Keys[j].whatcode;
break;
}
j++;
}
if (KeyCode[i] == GSM_KEY_NONE) {
*Length = i;
return ERR_NOTSUPPORTED;
}
}
*Length = i;
return ERR_NONE;
}
GSM_Error GSM_ReadFile(char *FileName, GSM_File *File)
{
int i = 1000;
FILE *file;
struct stat fileinfo;
if (FileName[0] == 0x00) return ERR_UNKNOWN;
file = fopen(FileName,"rb");
if (file == NULL) return ERR_CANTOPENFILE;
free(File->Buffer);
File->Buffer = NULL;
File->Used = 0;
while (i == 1000) {
File->Buffer = realloc(File->Buffer,File->Used + 1000);
i = fread(File->Buffer+File->Used,1,1000,file);
File->Used = File->Used + i;
}
File->Buffer = realloc(File->Buffer,File->Used);
fclose(file);
File->ModifiedEmpty = true;
if (stat(FileName,&fileinfo) == 0) {
File->ModifiedEmpty = false;
dbgprintf("File info read correctly\n");
//st_mtime is time of last modification of file
Fill_GSM_DateTime(&File->Modified, fileinfo.st_mtime);
File->Modified.Year = File->Modified.Year + 1900;
dbgprintf("FileTime: %02i-%02i-%04i %02i:%02i:%02i\n",
File->Modified.Day,File->Modified.Month,File->Modified.Year,
File->Modified.Hour,File->Modified.Minute,File->Modified.Second);
}
return ERR_NONE;
}
static void GSM_JADFindLine(GSM_File File, char *Name, char *Value)
{
unsigned char Line[2000];
int Pos = 0;
Value[0] = 0;
while (1) {
MyGetLine(File.Buffer, &Pos, Line, File.Used);
if (strlen(Line) == 0) break;
if (!strncmp(Line,Name,strlen(Name))) {
Pos = strlen(Name);
while (Line[Pos] == 0x20) Pos++;
strcpy(Value,Line+Pos);
return;
}
}
}
GSM_Error GSM_JADFindData(GSM_File File, char *Vendor, char *Name, char *JAR, char *Version, int *Size)
{
char Size2[200];
GSM_JADFindLine(File, "MIDlet-Vendor:", Vendor);
if (Vendor[0] == 0x00) return ERR_FILENOTSUPPORTED;
dbgprintf("Vendor: \"%s\"\n",Vendor);
GSM_JADFindLine(File, "MIDlet-Name:", Name);
if (Name[0] == 0x00) return ERR_FILENOTSUPPORTED;
dbgprintf("Name: \"%s\"\n",Name);
GSM_JADFindLine(File, "MIDlet-Jar-URL:", JAR);
if (JAR[0] == 0x00) return ERR_FILENOTSUPPORTED;
dbgprintf("JAR file URL: \"%s\"\n",JAR);
GSM_JADFindLine(File, "MIDlet-Jar-Size:", Size2);
*Size = -1;
if (Size2[0] == 0x00) return ERR_FILENOTSUPPORTED;
dbgprintf("JAR size: \"%s\"\n",Size2);
(*Size) = atoi(Size2);
GSM_JADFindLine(File, "MIDlet-Version:", Version);
dbgprintf("Version: \"%s\"\n",Version);
return ERR_NONE;
}
void GSM_IdentifyFileFormat(GSM_File *File)
{
File->Type = GSM_File_Other;
if (File->Used > 2) {
if (memcmp(File->Buffer, "BM",2)==0) {
File->Type = GSM_File_Image_BMP;
} else if (memcmp(File->Buffer, "GIF",3)==0) {
File->Type = GSM_File_Image_GIF;
} else if (File->Buffer[0] == 0x00 && File->Buffer[1] == 0x00) {
File->Type = GSM_File_Image_WBMP;
} else if (memcmp(File->Buffer+1, "PNG",3)==0) {
File->Type = GSM_File_Image_PNG;
} else if (File->Buffer[0] == 0xFF && File->Buffer[1] == 0xD8) {
File->Type = GSM_File_Image_JPG;
} else if (memcmp(File->Buffer, "MThd",4)==0) {
File->Type = GSM_File_Sound_MIDI;
} else if (File->Buffer[0] == 0x00 && File->Buffer[1] == 0x02) {
File->Type = GSM_File_Sound_NRT;
}
}
}
void SaveVCALDateTime(char *Buffer, int *Length, GSM_DateTime *Date, char *Start)
{
if (Start != NULL) {
*Length+=sprintf(Buffer+(*Length), "%s:",Start);
}
*Length+=sprintf(Buffer+(*Length), "%04d%02d%02dT%02d%02d%02d%c%c",
Date->Year, Date->Month, Date->Day,
Date->Hour, Date->Minute, Date->Second,13,10);
}
void ReadVCALDateTime(char *Buffer, GSM_DateTime *dt)
{
char year[5]="", month[3]="", day[3]="", hour[3]="", minute[3]="", second[3]="";
memset(dt,0,sizeof(dt));
strncpy(year, Buffer, 4);
strncpy(month, Buffer+4, 2);
strncpy(day, Buffer+6, 2);
strncpy(hour, Buffer+9, 2);
strncpy(minute, Buffer+11, 2);
strncpy(second, Buffer+13, 2);
/* FIXME: Should check ranges... */
dt->Year = atoi(year);
dt->Month = atoi(month);
dt->Day = atoi(day);
dt->Hour = atoi(hour);
dt->Minute = atoi(minute);
dt->Second = atoi(second);
/* FIXME */
dt->Timezone = 0;
}
void SaveVCALText(char *Buffer, int *Length, char *Text, char *Start)
{
char buffer[1000];
if (UnicodeLength(Text) != 0) {
- EncodeUTF8QuotedPrintable(buffer,Text);
+ EncodeUTF8(buffer,Text);
if (UnicodeLength(Text)==strlen(buffer)) {
*Length+=sprintf(Buffer+(*Length), "%s:%s%c%c",Start,DecodeUnicodeString(Text),13,10);
} else {
- *Length+=sprintf(Buffer+(*Length), "%s;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:%s%c%c",Start,buffer,13,10);
+ *Length+=sprintf(Buffer+(*Length), "%s:%s%c%c",Start,buffer,13,10);
}
}
}
bool ReadVCALText(char *Buffer, char *Start, char *Value)
{
unsigned char buff[200];
Value[0] = 0x00;
Value[1] = 0x00;
strcpy(buff,Start);
strcat(buff,":");
if (!strncmp(Buffer,buff,strlen(buff))) {
EncodeUnicode(Value,Buffer+strlen(Start)+1,strlen(Buffer)-(strlen(Start)+1));
dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value));
return true;
}
/* SE T68i */
strcpy(buff,Start);
strcat(buff,";ENCODING=QUOTED-PRINTABLE:");
if (!strncmp(Buffer,buff,strlen(buff))) {
DecodeUTF8QuotedPrintable(Value,Buffer+strlen(Start)+27,strlen(Buffer)-(strlen(Start)+27));
dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value));
return true;
}
strcpy(buff,Start);
strcat(buff,";CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:");
if (!strncmp(Buffer,buff,strlen(buff))) {
DecodeUTF8QuotedPrintable(Value,Buffer+strlen(Start)+41,strlen(Buffer)-(strlen(Start)+41));
dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value));
return true;
}
strcpy(buff,Start);
strcat(buff,";CHARSET=UTF-8:");
if (!strncmp(Buffer,buff,strlen(buff))) {
DecodeUTF8(Value,Buffer+strlen(Start)+15,strlen(Buffer)-(strlen(Start)+15));
dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value));
return true;
}
strcpy(buff,Start);
strcat(buff,";CHARSET=UTF-7:");
if (!strncmp(Buffer,buff,strlen(buff))) {
DecodeUTF7(Value,Buffer+strlen(Start)+15,strlen(Buffer)-(strlen(Start)+15));
dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value));
return true;
}
return false;
}
/* How should editor hadle tabs in this file? Add editor commands here.
* vim: noexpandtab sw=8 ts=8 sts=8:
*/
diff --git a/gammu/emb/common/service/gsmpbk.c b/gammu/emb/common/service/gsmpbk.c
index 05e5cb9..f7cf7d7 100644
--- a/gammu/emb/common/service/gsmpbk.c
+++ b/gammu/emb/common/service/gsmpbk.c
@@ -1,370 +1,371 @@
/* (c) 2001-2003 by Marcin Wiacek,... */
#include <string.h>
#include "../misc/coding/coding.h"
#include "gsmpbk.h"
#include "gsmmisc.h"
unsigned char *GSM_PhonebookGetEntryName (GSM_MemoryEntry *entry)
{
/* We possibly store here "LastName, FirstName" so allocate enough memory */
static char dest[(GSM_PHONEBOOK_TEXT_LENGTH*2+2+1)*2];
static char split[] = { '\0', ',', '\0', ' ', '\0', '\0'};
int i;
int first = -1, last = -1, name = -1;
int len = 0;
for (i = 0; i < entry->EntriesNum; i++) {
switch (entry->Entries[i].EntryType) {
case PBK_Text_LastName:
last = i;
break;
case PBK_Text_FirstName:
first = i;
break;
case PBK_Text_Name:
name = i;
break;
default:
break;
}
}
if (name != -1) {
CopyUnicodeString(dest, entry->Entries[name].Text);
} else {
if (last != -1 && first != -1) {
len = UnicodeLength(entry->Entries[last].Text);
CopyUnicodeString(dest, entry->Entries[last].Text);
CopyUnicodeString(dest + 2*len, split);
CopyUnicodeString(dest + 2*len + 4, entry->Entries[first].Text);
} else if (last != -1) {
CopyUnicodeString(dest, entry->Entries[last].Text);
} else if (first != -1) {
CopyUnicodeString(dest, entry->Entries[first].Text);
} else {
return NULL;
}
}
return dest;
}
void GSM_PhonebookFindDefaultNameNumberGroup(GSM_MemoryEntry *entry, int *Name, int *Number, int *Group)
{
int i;
*Name = -1;
*Number = -1;
*Group = -1;
for (i = 0; i < entry->EntriesNum; i++) {
switch (entry->Entries[i].EntryType) {
case PBK_Number_General : if (*Number == -1) *Number = i; break;
case PBK_Text_Name : if (*Name == -1) *Name = i; break;
case PBK_Caller_Group : if (*Group == -1) *Group = i; break;
default : break;
}
}
if ((*Number) == -1) {
for (i = 0; i < entry->EntriesNum; i++) {
switch (entry->Entries[i].EntryType) {
case PBK_Number_Mobile:
case PBK_Number_Work:
case PBK_Number_Fax:
case PBK_Number_Home:
case PBK_Number_Pager:
case PBK_Number_Other:
*Number = i;
break;
default:
break;
}
if (*Number != -1) break;
}
}
if ((*Name) == -1) {
for (i = 0; i < entry->EntriesNum; i++) {
if (entry->Entries[i].EntryType != PBK_Text_LastName) continue;
*Name = i;
break;
}
}
if ((*Name) == -1) {
for (i = 0; i < entry->EntriesNum; i++) {
if (entry->Entries[i].EntryType != PBK_Text_FirstName) continue;
*Name = i;
break;
}
}
}
void GSM_EncodeVCARD(char *Buffer, int *Length, GSM_MemoryEntry *pbk, bool header, GSM_VCardVersion Version)
{
int Name, Number, Group, i;
bool ignore;
GSM_PhonebookFindDefaultNameNumberGroup(pbk, &Name, &Number, &Group);
if (Version == Nokia_VCard10) {
if (header) *Length+=sprintf(Buffer+(*Length),"BEGIN:VCARD%c%c",13,10);
if (Name != -1) {
*Length+=sprintf(Buffer+(*Length),"N:%s%c%c",DecodeUnicodeString(pbk->Entries[Name].Text),13,10);
}
if (Number != -1) {
*Length +=sprintf(Buffer+(*Length),"TEL:%s%c%c",DecodeUnicodeString(pbk->Entries[Number].Text),13,10);
}
if (header) *Length+=sprintf(Buffer+(*Length),"END:VCARD%c%c",13,10);
} else if (Version == Nokia_VCard21) {
if (header) *Length+=sprintf(Buffer+(*Length),"BEGIN:VCARD%c%cVERSION:2.1%c%c",13,10,13,10);
if (Name != -1) {
SaveVCALText(Buffer, Length, pbk->Entries[Name].Text, "N");
}
for (i=0; i < pbk->EntriesNum; i++) {
if (i != Name) {
ignore = false;
switch(pbk->Entries[i].EntryType) {
case PBK_Text_Name :
case PBK_Date :
case PBK_Caller_Group :
ignore = true;
break;
case PBK_Number_General :
*Length+=sprintf(Buffer+(*Length),"TEL");
- if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF");
+ (*Length)+=sprintf(Buffer+(*Length),";PREF");
break;
case PBK_Number_Mobile :
*Length+=sprintf(Buffer+(*Length),"TEL");
- if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF");
+ //if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF");
*Length+=sprintf(Buffer+(*Length),";CELL");
break;
case PBK_Number_Work :
*Length+=sprintf(Buffer+(*Length),"TEL");
- if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF");
- *Length+=sprintf(Buffer+(*Length),";WORK;VOICE");
+ //if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF");
+ *Length+=sprintf(Buffer+(*Length),";WORK");
break;
case PBK_Number_Fax :
*Length+=sprintf(Buffer+(*Length),"TEL");
- if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF");
+ //if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF");
*Length+=sprintf(Buffer+(*Length),";FAX");
break;
case PBK_Number_Home :
*Length+=sprintf(Buffer+(*Length),"TEL");
- if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF");
- *Length+=sprintf(Buffer+(*Length),";HOME;VOICE");
+ //if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF");
+ *Length+=sprintf(Buffer+(*Length),";HOME");
break;
case PBK_Text_Note :
*Length+=sprintf(Buffer+(*Length),"NOTE");
break;
case PBK_Text_Postal :
/* Don't ask why. Nokia phones save postal address
* double - once like LABEL, second like ADR
*/
- SaveVCALText(Buffer, Length, pbk->Entries[i].Text, "LABEL");
+ //SaveVCALText(Buffer, Length, pbk->Entries[i].Text, "LABEL");
*Length+=sprintf(Buffer+(*Length),"ADR");
break;
case PBK_Text_Email :
case PBK_Text_Email2 :
*Length+=sprintf(Buffer+(*Length),"EMAIL");
break;
case PBK_Text_URL :
*Length+=sprintf(Buffer+(*Length),"URL");
break;
default :
ignore = true;
break;
}
if (!ignore) {
SaveVCALText(Buffer, Length, pbk->Entries[i].Text, "");
}
}
}
+ *Length+=sprintf(Buffer+(*Length), "X-KADDRESSBOOK-X-ExternalID:%d%c%c",pbk->Location,13,10);
if (header) *Length+=sprintf(Buffer+(*Length),"END:VCARD%c%c",13,10);
}
}
GSM_Error GSM_DecodeVCARD(unsigned char *Buffer, int *Pos, GSM_MemoryEntry *Pbk, GSM_VCardVersion Version)
{
unsigned char Line[2000],Buff[2000];
int Level = 0;
Buff[0] = 0;
Pbk->EntriesNum = 0;
while (1) {
MyGetLine(Buffer, Pos, Line, strlen(Buffer));
if (strlen(Line) == 0) break;
switch (Level) {
case 0:
if (strstr(Line,"BEGIN:VCARD")) Level = 1;
break;
case 1:
if (strstr(Line,"END:VCARD")) {
if (Pbk->EntriesNum == 0) return ERR_EMPTY;
return ERR_NONE;
}
if (ReadVCALText(Line, "N", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_Name;
Pbk->EntriesNum++;
}
if (ReadVCALText(Line, "TEL", Buff) ||
ReadVCALText(Line, "TEL;VOICE", Buff) ||
ReadVCALText(Line, "TEL;PREF", Buff) ||
ReadVCALText(Line, "TEL;PREF;VOICE", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_General;
Pbk->EntriesNum++;
}
if (ReadVCALText(Line, "TEL;CELL", Buff) ||
ReadVCALText(Line, "TEL;CELL;VOICE", Buff) ||
ReadVCALText(Line, "TEL;PREF;CELL", Buff) ||
ReadVCALText(Line, "TEL;PREF;CELL;VOICE", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_Mobile;
Pbk->EntriesNum++;
}
if (ReadVCALText(Line, "TEL;WORK", Buff) ||
ReadVCALText(Line, "TEL;PREF;WORK", Buff) ||
ReadVCALText(Line, "TEL;WORK;VOICE", Buff) ||
ReadVCALText(Line, "TEL;PREF;WORK;VOICE", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_Work;
Pbk->EntriesNum++;
}
if (ReadVCALText(Line, "TEL;FAX", Buff) ||
ReadVCALText(Line, "TEL;PREF;FAX", Buff) ||
ReadVCALText(Line, "TEL;FAX;VOICE", Buff) ||
ReadVCALText(Line, "TEL;PREF;FAX;VOICE", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_Fax;
Pbk->EntriesNum++;
}
if (ReadVCALText(Line, "TEL;HOME", Buff) ||
ReadVCALText(Line, "TEL;PREF;HOME", Buff) ||
ReadVCALText(Line, "TEL;HOME;VOICE", Buff) ||
ReadVCALText(Line, "TEL;PREF;HOME;VOICE", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_Home;
Pbk->EntriesNum++;
}
if (ReadVCALText(Line, "NOTE", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_Note;
Pbk->EntriesNum++;
}
if (ReadVCALText(Line, "ADR", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_Postal;
Pbk->EntriesNum++;
}
if (ReadVCALText(Line, "EMAIL", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_Email;
Pbk->EntriesNum++;
}
if (ReadVCALText(Line, "URL", Buff)) {
CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff);
Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_URL;
Pbk->EntriesNum++;
}
break;
}
}
if (Pbk->EntriesNum == 0) return ERR_EMPTY;
return ERR_NONE;
}
/* -------------- OLD functions (c) by Timo Teras -------------------------- */
#ifndef ENABLE_LGPL
static void ParseVCardLine(char **pos, char *Name, char *Parameters, char *Value)
{
int i;
Name[0] = Parameters[0] = Value[0] = 0;
if (**pos == 0) return;
for (i=0; **pos && **pos != ':' && **pos != ';'; i++, (*pos)++) Name[i] = **pos;
Name[i] = 0;
//dbgprintf("ParseVCardLine: name tag = '%s'\n", Name);
if (**pos == ';') {
(*pos)++;
for (i=0; **pos && **pos != ':'; i++, (*pos)++) Parameters[i] = **pos;
Parameters[i] = ';';
Parameters[i+1] = 0;
//dbgprintf("ParseVCardLine: parameter tag = '%s'\n", Parameters);
}
if (**pos != 0) (*pos)++;
i=0;
while (**pos) {
if ((*pos)[0] == '\x0d' && (*pos)[1] == '\x0a') {
(*pos) += 2;
if (**pos != '\t' && **pos != ' ') break;
while (**pos == '\t' || **pos == ' ') (*pos)++;
continue;
}
Value[i++] = **pos;
(*pos)++;
}
Value[i] = 0;
//dbgprintf("ParseVCardLine: value tag = '%s'\n", Value);
}
void DecodeVCARD21Text(char *VCard, GSM_MemoryEntry *pbk)
{
char *pos = VCard;
char Name[32], Parameters[256], Value[1024];
dbgprintf("Parsing VCard:\n%s\n", VCard);
ParseVCardLine(&pos, Name, Parameters, Value);
if (!mystrncasecmp(Name, "BEGIN", 0) || !mystrncasecmp(Value, "VCARD", 0)) {
dbgprintf("No valid VCARD signature\n");
return;
}
while (1) {
GSM_SubMemoryEntry *pbe = &pbk->Entries[pbk->EntriesNum];
ParseVCardLine(&pos, Name, Parameters, Value);
if (Name[0] == 0x00 ||
(mystrncasecmp(Name, "END", 0) && mystrncasecmp(Value, "VCARD", 0)))
return;
if (mystrncasecmp(Name, "N", 0)) {
//FIXME: Name is tagged field which should be parsed
pbe->EntryType = PBK_Text_Name;
EncodeUnicode(pbe->Text, Value, strlen(Value));
pbk->EntriesNum++;
} else if (mystrncasecmp(Name, "EMAIL", 0)) {
pbe->EntryType = PBK_Text_Email;
EncodeUnicode(pbe->Text, Value, strlen(Value));
pbk->EntriesNum++;
} else if (mystrncasecmp(Name, "TEL", 0)) {
if (strstr(Parameters, "WORK;"))
pbe->EntryType = PBK_Number_Work;
else if (strstr(Name, "HOME;"))
pbe->EntryType = PBK_Number_Home;
else if (strstr(Name, "FAX;"))
pbe->EntryType = PBK_Number_Fax;
else pbe->EntryType = PBK_Number_General;
EncodeUnicode(pbe->Text, Value, strlen(Value));
pbk->EntriesNum++;
}
}
}
#endif
/* How should editor hadle tabs in this file? Add editor commands here.
* vim: noexpandtab sw=8 ts=8 sts=8:
*/
diff --git a/gammu/emb/gammu/gammu.c b/gammu/emb/gammu/gammu.c
index 8db9afb..684e67c 100644
--- a/gammu/emb/gammu/gammu.c
+++ b/gammu/emb/gammu/gammu.c
@@ -1,8534 +1,8534 @@
/* (c) 2002-2004 by Marcin Wiacek and Michal Cihar */
/* FM stuff by Walek */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <locale.h>
#include <signal.h>
#include <ctype.h>
#include <wchar.h>
#ifdef WIN32
# include <windows.h>
# include <process.h>
# ifdef _MSC_VER
# include <sys/utime.h>
# else
# include <utime.h>
# endif
#else
# include <utime.h>
#endif
#include "../common/gammu.h"
#include "gammu.h"
#include "smsd/smsdcore.h"
#ifdef DEBUG
# include "sniff.h"
#endif
#ifdef GSM_ENABLE_NOKIA_DCT3
# include "depend/nokia/dct3.h"
# include "depend/nokia/dct3trac/wmx.h"
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
# include "depend/nokia/dct4.h"
#endif
#ifdef GSM_ENABLE_ATGEN
# include "depend/siemens/dsiemens.h"
#endif
#ifdef HAVE_PTHREAD
# include <pthread.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
GSM_StateMachine s;
GSM_Phone_Functions *Phone;
static INI_Section *cfg = NULL;
GSM_Error error = ERR_NONE;
static int i;
volatile bool gshutdown = false;
void interrupt(int sign)
{
signal(sign, SIG_IGN);
gshutdown = true;
}
#ifdef __GNUC__
__attribute__((format(printf, 1, 2)))
#endif
int printmsg(char *format, ...)
{
va_list argp;
int result;
va_start(argp, format);
result = vfprintf(stdout,GetMsg(s.msg,format),argp);
va_end(argp);
return result;
}
#ifdef __GNUC__
__attribute__((format(printf, 1, 2)))
#endif
int printmsgerr(char *format, ...)
{
va_list argp;
int result;
va_start(argp, format);
result = vfprintf(stderr,GetMsg(s.msg,format), argp);
va_end(argp);
return result;
}
static void PrintSecurityStatus()
{
GSM_SecurityCodeType Status;
error=Phone->GetSecurityStatus(&s,&Status);
Print_Error(error);
switch(Status) {
case SEC_SecurityCode:
printmsg("Waiting for Security Code.\n");
break;
case SEC_Pin:
printmsg("Waiting for PIN.\n");
break;
case SEC_Pin2:
printmsg("Waiting for PIN2.\n");
break;
case SEC_Puk:
printmsg("Waiting for PUK.\n");
break;
case SEC_Puk2:
printmsg("Waiting for PUK2.\n");
break;
case SEC_None:
printmsg("Nothing to enter.\n");
break;
default:
printmsg("Unknown\n");
}
}
void Print_Error(GSM_Error error)
{
if (error != ERR_NONE) {
printf("%s\n",print_error(error,s.di.df,s.msg));
if (error == ERR_SECURITYERROR) {
printmsg("Security status: ");
PrintSecurityStatus();
}
if (s.opened) GSM_TerminateConnection(&s);
exit (-1);
}
}
void GSM_Init(bool checkerror)
{
error=GSM_InitConnection(&s,3);
if (checkerror) Print_Error(error);
Phone=s.Phone.Functions;
}
void GSM_Terminate(void)
{
error=GSM_TerminateConnection(&s);
Print_Error(error);
}
static void GetStartStop(int *start, int *stop, int num, int argc, char *argv[])
{
*start=atoi(argv[num]);
if (*start==0) {
printmsg("ERROR: enumerate locations from 1\n");
exit (-1);
}
if (stop!=NULL) {
*stop=*start;
if (argc>=num+2) *stop=atoi(argv[num+1]);
if (*stop==0) {
printmsg("ERROR: enumerate locations from 1\n");
exit (-1);
}
}
}
bool always_answer_yes = false;
bool always_answer_no = false;
static bool answer_yes(char *text)
{
int len;
char ans[99];
while (1) {
printmsgerr("%s (yes/no/ALL/ONLY/NONE) ? ",text);
if (always_answer_yes) {
printmsgerr("YES (always)\n");
return true;
}
if (always_answer_no) {
printmsgerr("NO (always)\n");
return false;
}
len=GetLine(stdin, ans, 99);
if (len==-1) exit(-1);
if (!strcmp(ans, "NONE")) {
always_answer_no = true;
return false;
}
if (!strcmp(ans, "ONLY")) {
always_answer_no = true;
return true;
}
if (!strcmp(ans, "ALL")) {
always_answer_yes = true;
return true;
}
if (mystrncasecmp(ans, "yes",0)) return true;
if (mystrncasecmp(ans, "no" ,0)) return false;
}
}
#ifdef GSM_ENABLE_BEEP
void GSM_PhoneBeep(void)
{
error = PHONE_Beep(&s);
if (error != ERR_NOTSUPPORTED && error != ERR_NOTIMPLEMENTED) Print_Error(error);
}
#endif
static GSM_Error GSM_PlayRingtone(GSM_Ringtone ringtone)
{
int i;
bool first=true;
GSM_Error error;
signal(SIGINT, interrupt);
printmsg("Press Ctrl+C to break...\n");
for (i=0;i<ringtone.NoteTone.NrCommands;i++) {
if (gshutdown) break;
if (ringtone.NoteTone.Commands[i].Type != RING_NOTETONE) continue;
error=PHONE_RTTLPlayOneNote(&s,ringtone.NoteTone.Commands[i].Note,first);
if (error!=ERR_NONE) return error;
first = false;
}
/* Disables buzzer */
return s.Phone.Functions->PlayTone(&s,255*255,0,false);
}
static void PlayRingtone(int argc, char *argv[])
{
GSM_Ringtone ringtone,ringtone2;
ringtone.Format = 0;
error=GSM_ReadRingtoneFile(argv[2],&ringtone);
Print_Error(error);
error=GSM_RingtoneConvert(&ringtone2,&ringtone,RING_NOTETONE);
Print_Error(error);
GSM_Init(true);
error=GSM_PlayRingtone(ringtone2);
Print_Error(error);
GSM_Terminate();
}
static void Identify(int argc, char *argv[])
{
unsigned char buffer[100];
GSM_Init(true);
error=Phone->GetManufacturer(&s);
Print_Error(error);
printmsg("Manufacturer : %s\n", s.Phone.Data.Manufacturer);
error=Phone->GetModel(&s);
Print_Error(error);
printmsg("Model : %s (%s)\n",
s.Phone.Data.ModelInfo->model,
s.Phone.Data.Model);
error=Phone->GetFirmware(&s);
Print_Error(error);
printmsg("Firmware : %s",s.Phone.Data.Version);
error=Phone->GetPPM(&s, buffer);
if (error != ERR_NOTSUPPORTED) {
if (error != ERR_NOTIMPLEMENTED) Print_Error(error);
if (error == ERR_NONE) printmsg(" %s",buffer);
}
if (s.Phone.Data.VerDate[0]!=0) printmsg(" (%s)",s.Phone.Data.VerDate);
printf("\n");
error=Phone->GetHardware(&s, buffer);
if (error != ERR_NOTSUPPORTED) {
if (error != ERR_NOTIMPLEMENTED) Print_Error(error);
if (error == ERR_NONE) printmsg("Hardware : %s\n",buffer);
}
error=Phone->GetIMEI(&s);
if (error != ERR_NOTSUPPORTED) {
if (error != ERR_NOTIMPLEMENTED) Print_Error(error);
if (error == ERR_NONE) printmsg("IMEI : %s\n",s.Phone.Data.IMEI);
error=Phone->GetOriginalIMEI(&s, buffer);
if (error != ERR_NOTSUPPORTED && error != ERR_SECURITYERROR) {
if (error != ERR_NOTIMPLEMENTED) Print_Error(error);
if (error == ERR_NONE) printmsg("Original IMEI : %s\n",buffer);
}
}
error=Phone->GetManufactureMonth(&s, buffer);
if (error != ERR_NOTSUPPORTED && error != ERR_SECURITYERROR) {
if (error != ERR_NOTIMPLEMENTED) Print_Error(error);
if (error == ERR_NONE) printmsg("Manufactured : %s\n",buffer);
}
error=Phone->GetProductCode(&s, buffer);
if (error != ERR_NOTSUPPORTED) {
if (error != ERR_NOTIMPLEMENTED) Print_Error(error);
if (error == ERR_NONE) printmsg("Product code : %s\n",buffer);
}
error=Phone->GetSIMIMSI(&s, buffer);
switch (error) {
case ERR_SECURITYERROR:
case ERR_NOTSUPPORTED:
case ERR_NOTIMPLEMENTED:
break;
case ERR_NONE:
printmsg("SIM IMSI : %s\n",buffer);
break;
default:
Print_Error(error);
}
#ifdef GSM_ENABLE_NOKIA_DCT3
DCT3Info(argc, argv);
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
DCT4Info(argc, argv);
#endif
GSM_Terminate();
}
static void GetDateTime(int argc, char *argv[])
{
GSM_DateTime date_time;
GSM_Locale locale;
GSM_Init(true);
error=Phone->GetDateTime(&s, &date_time);
switch (error) {
case ERR_EMPTY:
printmsg("Date and time not set in phone\n");
break;
case ERR_NONE:
printmsg("Phone time is %s\n",OSDateTime(date_time,false));
break;
default:
Print_Error(error);
}
error=Phone->GetLocale(&s, &locale);
switch (error) {
case ERR_NOTSUPPORTED:
case ERR_NOTIMPLEMENTED:
break;
default:
Print_Error(error);
printmsg("Time format is ");
if (locale.AMPMTime) printmsg("12 hours\n"); else printmsg("24 hours\n");
printmsg("Date format is ");
switch (locale.DateFormat) {
case GSM_Date_DDMMYYYY:printmsg("DD MM YYYY");break;
case GSM_Date_MMDDYYYY:printmsg("MM DD YYYY");break;
case GSM_Date_YYYYMMDD:printmsg("YYYY MM DD");
default :break;
}
printmsg(", date separator is %c\n",locale.DateSeparator);
}
GSM_Terminate();
}
static void SetDateTime(int argc, char *argv[])
{
GSM_DateTime date_time;
GSM_GetCurrentDateTime(&date_time);
GSM_Init(true);
error=Phone->SetDateTime(&s, &date_time);
Print_Error(error);
GSM_Terminate();
}
static void GetAlarm(int argc, char *argv[])
{
GSM_Alarm alarm;
GSM_Init(true);
alarm.Location = 1;
error=Phone->GetAlarm(&s, &alarm);
switch (error) {
case ERR_EMPTY:
printmsg("Alarm not set in phone\n");
break;
case ERR_NONE:
if (alarm.Repeating) {
printmsg("Date: %s\n","Every day");
} else {
printmsg("Date: %s\n",OSDate(alarm.DateTime));
}
printmsg("Time: %02d:%02d\n",alarm.DateTime.Hour, alarm.DateTime.Minute);
if (alarm.Text[0] != 0 || alarm.Text[1] != 0) {
printmsg("Text: \"%s\"\n", DecodeUnicodeConsole(alarm.Text));
}
break;
default:
Print_Error(error);
}
GSM_Terminate();
}
static void SetAlarm(int argc, char *argv[])
{
GSM_Alarm alarm;
alarm.DateTime.Hour = atoi(argv[2]);
alarm.DateTime.Minute = atoi(argv[3]);
alarm.DateTime.Second = 0;
alarm.Location = 1;
alarm.Repeating = true;
alarm.Text[0] = 0;
alarm.Text[1] = 0;
GSM_Init(true);
error=Phone->SetAlarm(&s, &alarm);
Print_Error(error);
GSM_Terminate();
}
GSM_Bitmap caller[5];
GSM_AllRingtonesInfo Info;
bool callerinit[5] = {false, false, false, false, false};
bool ringinit = false;
static void PrintMemoryEntry(GSM_MemoryEntry *entry)
{
GSM_Category Category;
bool unknown;
int z;
for (i=0;i<entry->EntriesNum;i++) {
unknown = false;
switch (entry->Entries[i].EntryType) {
case PBK_Date:
printmsg("Date and time : %s\n",OSDateTime(entry->Entries[i].Date,false));
continue;
case PBK_Category:
Category.Location = entry->Entries[i].Number;
Category.Type = Category_Phonebook;
error=Phone->GetCategory(&s, &Category);
if (error == ERR_NONE) {
printmsg("Category : \"%s\" (%i)\n", DecodeUnicodeConsole(Category.Name), entry->Entries[i].Number);
} else {
printmsg("Category : %i\n", entry->Entries[i].Number);
}
continue;
case PBK_Private:
printmsg("Private : %s\n", entry->Entries[i].Number == 1 ? "Yes" : "No");
continue;
case PBK_Number_General : printmsg("General number "); break;
case PBK_Number_Mobile : printmsg("Mobile number "); break;
case PBK_Number_Work : printmsg("Work number "); break;
case PBK_Number_Fax : printmsg("Fax number "); break;
case PBK_Number_Home : printmsg("Home number "); break;
case PBK_Number_Pager : printmsg("Pager number "); break;
case PBK_Number_Other : printmsg("Other number "); break;
case PBK_Text_Note : printmsg("Text "); break;
case PBK_Text_Postal : printmsg("Snail address "); break;
case PBK_Text_Email : printmsg("Email address 1 "); break;
case PBK_Text_Email2 : printmsg("Email address 2 "); break;
case PBK_Text_URL : printmsg("URL address "); break;
case PBK_Text_Name : printmsg("Name "); break;
case PBK_Text_LastName : printmsg("Last name "); break;
case PBK_Text_FirstName : printmsg("First name "); break;
case PBK_Text_Company : printmsg("Company "); break;
case PBK_Text_JobTitle : printmsg("Job title "); break;
case PBK_Text_StreetAddress : printmsg("Street address "); break;
case PBK_Text_City : printmsg("City "); break;
case PBK_Text_State : printmsg("State "); break;
case PBK_Text_Zip : printmsg("Zip code "); break;
case PBK_Text_Country : printmsg("Country "); break;
case PBK_Text_Custom1 : printmsg("Custom text 1 "); break;
case PBK_Text_Custom2 : printmsg("Custom text 2 "); break;
case PBK_Text_Custom3 : printmsg("Custom text 3 "); break;
case PBK_Text_Custom4 : printmsg("Custom text 4 "); break;
case PBK_Caller_Group :
unknown = true;
if (!callerinit[entry->Entries[i].Number]) {
caller[entry->Entries[i].Number].Type = GSM_CallerGroupLogo;
caller[entry->Entries[i].Number].Location = entry->Entries[i].Number;
error=Phone->GetBitmap(&s,&caller[entry->Entries[i].Number]);
Print_Error(error);
if (caller[entry->Entries[i].Number].DefaultName) {
NOKIA_GetDefaultCallerGroupName(&s,&caller[entry->Entries[i].Number]);
}
callerinit[entry->Entries[i].Number]=true;
}
printmsg("Caller group : \"%s\"\n",DecodeUnicodeConsole(caller[entry->Entries[i].Number].Text));
break;
case PBK_RingtoneID :
unknown = true;
if (!ringinit) {
error=Phone->GetRingtonesInfo(&s,&Info);
if (error != ERR_NOTSUPPORTED) Print_Error(error);
if (error == ERR_NONE) ringinit = true;
}
if (ringinit) {
for (z=0;z<Info.Number;z++) {
if (Info.Ringtone[z].ID == entry->Entries[i].Number) {
printmsg("Ringtone : \"%s\"\n",DecodeUnicodeConsole(Info.Ringtone[z].Name));
break;
}
}
} else {
printmsg("Ringtone ID : %i\n",entry->Entries[i].Number);
}
break;
case PBK_PictureID :
unknown = true;
printmsg("Picture ID : 0x%x\n",entry->Entries[i].Number);
break;
default :
printmsg("UNKNOWN\n");
unknown = true;
break;
}
if (!unknown) printmsg(" : \"%s\"\n", DecodeUnicodeConsole(entry->Entries[i].Text));
}
printf("\n");
}
static void GetAllMemory(int argc, char *argv[])
{
GSM_MemoryEntry Entry;
bool start = true;
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
Entry.MemoryType = 0;
if (mystrncasecmp(argv[2],"DC",0)) Entry.MemoryType=MEM_DC;
if (mystrncasecmp(argv[2],"ON",0)) Entry.MemoryType=MEM_ON;
if (mystrncasecmp(argv[2],"RC",0)) Entry.MemoryType=MEM_RC;
if (mystrncasecmp(argv[2],"MC",0)) Entry.MemoryType=MEM_MC;
if (mystrncasecmp(argv[2],"ME",0)) Entry.MemoryType=MEM_ME;
if (mystrncasecmp(argv[2],"SM",0)) Entry.MemoryType=MEM_SM;
if (mystrncasecmp(argv[2],"VM",0)) Entry.MemoryType=MEM_VM;
if (mystrncasecmp(argv[2],"FD",0)) Entry.MemoryType=MEM_FD;
if (Entry.MemoryType==0) {
printmsg("ERROR: unknown memory type (\"%s\")\n",argv[2]);
exit (-1);
}
GSM_Init(true);
while (!gshutdown) {
error = Phone->GetNextMemory(&s, &Entry, start);
if (error == ERR_EMPTY) break;
Print_Error(error);
printmsg("Memory %s, Location %i\n",argv[2],Entry.Location);
PrintMemoryEntry(&Entry);
start = false;
}
GSM_Terminate();
}
static void GetMemory(int argc, char *argv[])
{
int j, start, stop, emptynum = 0, fillednum = 0;
GSM_MemoryEntry entry;
bool empty = true;
entry.MemoryType=0;
if (mystrncasecmp(argv[2],"DC",0)) entry.MemoryType=MEM_DC;
if (mystrncasecmp(argv[2],"ON",0)) entry.MemoryType=MEM_ON;
if (mystrncasecmp(argv[2],"RC",0)) entry.MemoryType=MEM_RC;
if (mystrncasecmp(argv[2],"MC",0)) entry.MemoryType=MEM_MC;
if (mystrncasecmp(argv[2],"ME",0)) entry.MemoryType=MEM_ME;
if (mystrncasecmp(argv[2],"SM",0)) entry.MemoryType=MEM_SM;
if (mystrncasecmp(argv[2],"VM",0)) entry.MemoryType=MEM_VM;
if (mystrncasecmp(argv[2],"FD",0)) entry.MemoryType=MEM_FD;
if (entry.MemoryType==0) {
printmsg("ERROR: unknown memory type (\"%s\")\n",argv[2]);
exit (-1);
}
GetStartStop(&start, &stop, 3, argc, argv);
if (argc > 5 && strcmp(argv[5],"")) {
if (mystrncasecmp(argv[5],"-nonempty",0)) {
empty = false;
} else {
printmsg("ERROR: unknown parameter \"%s\"\n",argv[5]);
exit (-1);
}
}
GSM_Init(true);
if (!strcmp(s.Phone.Data.ModelInfo->model,"3310")) {
if (s.Phone.Data.VerNum<=4.06) printmsg("WARNING: you will have null names in entries. Upgrade firmware in phone to higher than 4.06\n");
}
for (j=start;j<=stop;j++) {
if (empty) printmsg("Memory %s, Location %i\n",argv[2],j);
entry.Location=j;
error=Phone->GetMemory(&s, &entry);
if (error != ERR_EMPTY) Print_Error(error);
if (error == ERR_EMPTY) {
emptynum++;
if (empty) {
printmsg("Entry is empty\n");
printf("\n");
}
} else {
fillednum++;
if (!empty) printmsg("Memory %s, Location %i\n",argv[2],j);
PrintMemoryEntry(&entry);
}
}
printmsg("%i entries empty, %i entries filled\n",emptynum,fillednum);
GSM_Terminate();
}
#define MemoryLocationToString(x) ( \
x == MEM_ON ? "ON" : \
x == MEM_RC ? "RC" : \
x == MEM_MC ? "MC" : \
x == MEM_ME ? "ME" : \
x == MEM_SM ? "SM" : \
x == MEM_VM ? "VM" : \
x == MEM_FD ? "FD" : "XX")
static void SearchOneEntry(GSM_MemoryEntry *Entry, unsigned char *Text)
{
int i;
for (i=0;i<Entry->EntriesNum;i++) {
switch (Entry->Entries[i].EntryType) {
case PBK_Number_General :
case PBK_Number_Mobile :
case PBK_Number_Work :
case PBK_Number_Fax :
case PBK_Number_Home :
case PBK_Number_Pager :
case PBK_Number_Other :
case PBK_Text_Note :
case PBK_Text_Postal :
case PBK_Text_Email :
case PBK_Text_Email2 :
case PBK_Text_URL :
case PBK_Text_Name :
case PBK_Text_LastName :
case PBK_Text_FirstName :
case PBK_Text_Company :
case PBK_Text_JobTitle :
case PBK_Text_StreetAddress :
case PBK_Text_City :
case PBK_Text_State :
case PBK_Text_Zip :
case PBK_Text_Country :
case PBK_Text_Custom1 :
case PBK_Text_Custom2 :
case PBK_Text_Custom3 :
case PBK_Text_Custom4 :
case PBK_Caller_Group :
if (mywstrstr(Entry->Entries[i].Text, Text) != NULL) {
fprintf(stderr,"\n");
printmsg("Memory %s, Location %i\n",MemoryLocationToString(Entry->MemoryType),Entry->Location);
PrintMemoryEntry(Entry);
return;
}
break;
default:
break;
}
}
}
static void SearchOneMemory(GSM_MemoryType MemoryType, char *Title, unsigned char *Text)
{
GSM_MemoryEntry Entry;
GSM_MemoryStatus Status;
int i = 0, l = 1;
bool start = true;
Status.MemoryType = MemoryType;
Entry.MemoryType = MemoryType;
if (Phone->GetMemoryStatus(&s, &Status) == ERR_NONE) {
fprintf(stderr,"%c%s: %i%%", 13, Title, (i+1)*100/(Status.MemoryUsed+1));
if (Phone->GetNextMemory != NOTSUPPORTED && Phone->GetNextMemory != NOTIMPLEMENTED) {
while (i < Status.MemoryUsed) {
if (gshutdown) return;
i++;
fprintf(stderr,"\r%s: %i%%", Title, (i+1)*100/(Status.MemoryUsed+1));
error = Phone->GetNextMemory(&s, &Entry, start);
if (error == ERR_EMPTY) break;
Print_Error(error);
SearchOneEntry(&Entry, Text);
start = false;
}
} else {
while (i < Status.MemoryUsed) {
Entry.Location = l;
error = Phone->GetMemory(&s, &Entry);
if (error != ERR_EMPTY) {
Print_Error(error);
i++;
SearchOneEntry(&Entry, Text);
}
fprintf(stderr,"%c%s: %i%%", 13, Title, (i+1)*100/(Status.MemoryUsed+1));
l++;
}
}
fprintf(stderr,"\n");
}
}
static void SearchMemory(int argc, char *argv[])
{
unsigned char Text[(GSM_PHONEBOOK_TEXT_LENGTH+1)*2];
int Length;
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
Length = strlen(argv[2]);
if (Length > GSM_PHONEBOOK_TEXT_LENGTH) {
printmsg("Search text too long, truncating to %d chars!\n", GSM_PHONEBOOK_TEXT_LENGTH);
Length = GSM_PHONEBOOK_TEXT_LENGTH;
}
EncodeUnicode(Text, argv[2], Length);
GSM_Init(true);
if (!gshutdown) SearchOneMemory(MEM_ME, "Phone phonebook", Text);
if (!gshutdown) SearchOneMemory(MEM_SM, "SIM phonebook", Text);
if (!gshutdown) SearchOneMemory(MEM_ON, "Own numbers", Text);
if (!gshutdown) SearchOneMemory(MEM_DC, "Dialled numbers", Text);
if (!gshutdown) SearchOneMemory(MEM_RC, "Received numbers", Text);
if (!gshutdown) SearchOneMemory(MEM_MC, "Missed numbers", Text);
if (!gshutdown) SearchOneMemory(MEM_FD, "Fix dialling", Text);
if (!gshutdown) SearchOneMemory(MEM_VM, "Voice mailbox", Text);
GSM_Terminate();
}
static void ListMemoryCategoryEntries(int Category)
{
GSM_MemoryEntry Entry;
bool start = true;
int j;
/* Category can be only for ME stored entries */
Entry.MemoryType = MEM_ME;
while (!gshutdown) {
error = Phone->GetNextMemory(&s, &Entry, start);
if (error == ERR_EMPTY) break;
Print_Error(error);
for (j=0;j<Entry.EntriesNum;j++) {
if (Entry.Entries[j].EntryType == PBK_Category && Entry.Entries[j].Number == Category) {
printmsg("Memory %s, Location %i\n",MemoryLocationToString(Entry.MemoryType),Entry.Location);
PrintMemoryEntry(&Entry);
}
}
start = false;
}
}
static void ListMemoryCategory(int argc, char *argv[])
{
GSM_Category Category;
GSM_CategoryStatus Status;
int j, count;
unsigned char Text[(GSM_MAX_CATEGORY_NAME_LENGTH+1)*2];
int Length;
bool Number = true;;
GSM_Init(true);
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
Length = strlen(argv[2]);
for (j = 0; j < Length; j++) {
if (!isdigit(argv[2][j])) {
Number = false;
break;
}
}
if (Number) {
j = atoi(argv[2]);
if (j > 0) {
ListMemoryCategoryEntries(j);
}
} else {
if (Length > GSM_MAX_CATEGORY_NAME_LENGTH) {
printmsg("Search text too long, truncating to %d chars!\n", GSM_MAX_CATEGORY_NAME_LENGTH);
Length = GSM_MAX_CATEGORY_NAME_LENGTH;
}
EncodeUnicode(Text, argv[2], Length);
Category.Type = Category_Phonebook;
Status.Type = Category_Phonebook;
if (Phone->GetCategoryStatus(&s, &Status) == ERR_NONE) {
for (count=0,j=1;count<Status.Used;j++) {
Category.Location=j;
error=Phone->GetCategory(&s, &Category);
if (error != ERR_EMPTY) {
count++;
if (mywstrstr(Category.Name, Text) != NULL) {
ListMemoryCategoryEntries(j);
}
}
}
}
}
GSM_Terminate();
}
static void displaysinglesmsinfo(GSM_SMSMessage sms, bool displaytext, bool displayudh)
{
switch (sms.PDU) {
case SMS_Status_Report:
printmsg("SMS status report\n");
printmsg("Status : ");
switch (sms.State) {
case SMS_Sent : printmsg("Sent"); break;
case SMS_Read : printmsg("Read"); break;
case SMS_UnRead : printmsg("UnRead"); break;
case SMS_UnSent : printmsg("UnSent"); break;
}
printmsg("\nRemote number : \"%s\"\n",DecodeUnicodeConsole(sms.Number));
printmsg("Reference number: %d\n",sms.MessageReference);
printmsg("Sent : %s\n",OSDateTime(sms.DateTime,true));
printmsg("SMSC number : \"%s\"\n",DecodeUnicodeConsole(sms.SMSC.Number));
printmsg("SMSC response : %s\n",OSDateTime(sms.SMSCTime,true));
printmsg("Delivery status : %s\n",DecodeUnicodeConsole(sms.Text));
printmsg("Details : ");
if (sms.DeliveryStatus & 0x40) {
if (sms.DeliveryStatus & 0x20) {
printmsg("Temporary error, ");
} else {
printmsg("Permanent error, ");
}
} else if (sms.DeliveryStatus & 0x20) {
printmsg("Temporary error, ");
}
switch (sms.DeliveryStatus) {
case 0x00: printmsg("SM received by the SME"); break;
case 0x01: printmsg("SM forwarded by the SC to the SME but the SC is unable to confirm delivery");break;
case 0x02: printmsg("SM replaced by the SC"); break;
case 0x20: printmsg("Congestion"); break;
case 0x21: printmsg("SME busy"); break;
case 0x22: printmsg("No response from SME"); break;
case 0x23: printmsg("Service rejected"); break;
case 0x24: printmsg("Quality of service not aviable"); break;
case 0x25: printmsg("Error in SME"); break;
case 0x40: printmsg("Remote procedure error"); break;
case 0x41: printmsg("Incompatibile destination"); break;
case 0x42: printmsg("Connection rejected by SME"); break;
case 0x43: printmsg("Not obtainable"); break;
case 0x44: printmsg("Quality of service not available"); break;
case 0x45: printmsg("No internetworking available"); break;
case 0x46: printmsg("SM Validity Period Expired"); break;
case 0x47: printmsg("SM deleted by originating SME"); break;
case 0x48: printmsg("SM Deleted by SC Administration"); break;
case 0x49: printmsg("SM does not exist"); break;
case 0x60: printmsg("Congestion"); break;
case 0x61: printmsg("SME busy"); break;
case 0x62: printmsg("No response from SME"); break;
case 0x63: printmsg("Service rejected"); break;
case 0x64: printmsg("Quality of service not available"); break;
case 0x65: printmsg("Error in SME"); break;
default : printmsg("Reserved/Specific to SC: %x",sms.DeliveryStatus); break;
}
printf("\n");
break;
case SMS_Deliver:
printmsg("SMS message\n");
if (sms.State==SMS_UnSent && sms.Memory==MEM_ME) {
printmsg("Saved : %s\n",OSDateTime(sms.DateTime,true));
} else {
printmsg("SMSC number : \"%s\"",DecodeUnicodeConsole(sms.SMSC.Number));
if (sms.ReplyViaSameSMSC) printmsg(" (set for reply)");
printmsg("\nSent : %s\n",OSDateTime(sms.DateTime,true));
}
/* No break. The only difference for SMS_Deliver and SMS_Submit is,
* that SMS_Deliver contains additional data. We wrote them and then go
* for data shared with SMS_Submit
*/
case SMS_Submit:
if (sms.ReplaceMessage != 0) printmsg("SMS replacing ID : %i\n",sms.ReplaceMessage);
/* If we went here from "case SMS_Deliver", we don't write "SMS Message" */
if (sms.PDU==SMS_Submit) {
printmsg("SMS message\n");
if (sms.State==SMS_UnSent && sms.Memory==MEM_ME) {
} else {
printmsg("Reference number : %d\n",sms.MessageReference);
}
}
if (sms.Name[0] != 0x00 || sms.Name[1] != 0x00) {
printmsg("Name : \"%s\"\n",DecodeUnicodeConsole(sms.Name));
}
if (sms.Class != -1) {
printmsg("Class : %i\n",sms.Class);
}
printmsg("Coding : ");
switch (sms.Coding) {
case SMS_Coding_Unicode : printmsg("Unicode\n"); break;
case SMS_Coding_Default : printmsg("Default GSM alphabet\n"); break;
case SMS_Coding_8bit : printmsg("8 bit\n"); break;
}
if (sms.State==SMS_UnSent && sms.Memory==MEM_ME) {
} else {
printmsg("Remote number : \"%s\"\n",DecodeUnicodeConsole(sms.Number));
}
printmsg("Status : ");
switch (sms.State) {
case SMS_Sent : printmsg("Sent\n"); break;
case SMS_Read : printmsg("Read\n"); break;
case SMS_UnRead : printmsg("UnRead\n"); break;
case SMS_UnSent : printmsg("UnSent\n"); break;
}
if (sms.UDH.Type != UDH_NoUDH) {
printmsg("User Data Header : ");
switch (sms.UDH.Type) {
case UDH_ConcatenatedMessages : printmsg("Concatenated (linked) message"); break;
case UDH_ConcatenatedMessages16bit : printmsg("Concatenated (linked) message"); break;
case UDH_DisableVoice : printmsg("Disables voice indicator"); break;
case UDH_EnableVoice : printmsg("Enables voice indicator"); break;
case UDH_DisableFax : printmsg("Disables fax indicator"); break;
case UDH_EnableFax : printmsg("Enables fax indicator"); break;
case UDH_DisableEmail : printmsg("Disables email indicator"); break;
case UDH_EnableEmail : printmsg("Enables email indicator"); break;
case UDH_VoidSMS : printmsg("Void SMS"); break;
case UDH_NokiaWAP : printmsg("Nokia WAP bookmark"); break;
case UDH_NokiaOperatorLogoLong : printmsg("Nokia operator logo"); break;
case UDH_NokiaWAPLong : printmsg("Nokia WAP bookmark or WAP/MMS settings"); break;
case UDH_NokiaRingtone : printmsg("Nokia ringtone"); break;
case UDH_NokiaRingtoneLong : printmsg("Nokia ringtone"); break;
case UDH_NokiaOperatorLogo : printmsg("Nokia GSM operator logo"); break;
case UDH_NokiaCallerLogo : printmsg("Nokia caller logo"); break;
case UDH_NokiaProfileLong : printmsg("Nokia profile"); break;
case UDH_NokiaCalendarLong : printmsg("Nokia calendar note"); break;
case UDH_NokiaPhonebookLong : printmsg("Nokia phonebook entry"); break;
case UDH_UserUDH : printmsg("User UDH"); break;
case UDH_MMSIndicatorLong : printmsg("MMS indicator"); break;
case UDH_NoUDH: break;
}
if (sms.UDH.Type != UDH_NoUDH) {
if (sms.UDH.ID8bit != -1) printmsg(", ID (8 bit) %i",sms.UDH.ID8bit);
if (sms.UDH.ID16bit != -1) printmsg(", ID (16 bit) %i",sms.UDH.ID16bit);
if (sms.UDH.PartNumber != -1 && sms.UDH.AllParts != -1) {
if (displayudh) {
printmsg(", part %i of %i",sms.UDH.PartNumber,sms.UDH.AllParts);
} else {
printmsg(", %i parts",sms.UDH.AllParts);
}
}
}
printf("\n");
}
if (displaytext) {
printf("\n");
if (sms.Coding!=SMS_Coding_8bit) {
printmsg("%s\n",DecodeUnicodeConsole(sms.Text));
} else {
printmsg("8 bit SMS, cannot be displayed here\n");
}
}
break;
}
}
static void displaymultismsinfo (GSM_MultiSMSMessage sms, bool eachsms, bool ems)
{
GSM_MultiPartSMSInfo SMSInfo;
bool RetVal,udhinfo=true;
int j;
/* GSM_DecodeMultiPartSMS returns if decoded SMS contenst correctly */
RetVal = GSM_DecodeMultiPartSMS(&SMSInfo,&sms,ems);
if (eachsms) {
if (sms.SMS[0].UDH.Type != UDH_NoUDH && sms.SMS[0].UDH.AllParts == sms.Number) udhinfo = false;
if (RetVal && !udhinfo) {
displaysinglesmsinfo(sms.SMS[0],false,false);
printf("\n");
} else {
for (j=0;j<sms.Number;j++) {
displaysinglesmsinfo(sms.SMS[j],!RetVal,udhinfo);
printf("\n");
}
}
} else {
for (j=0;j<sms.Number;j++) {
displaysinglesmsinfo(sms.SMS[j],!RetVal,true);
printf("\n");
}
}
if (!RetVal) {
GSM_FreeMultiPartSMSInfo(&SMSInfo);
return;
}
if (SMSInfo.Unknown) printmsg("Some details were ignored (unknown or not implemented in decoding functions)\n\n");
for (i=0;i<SMSInfo.EntriesNum;i++) {
switch (SMSInfo.Entries[i].ID) {
case SMS_NokiaRingtone:
printmsg("Ringtone \"%s\"\n",DecodeUnicodeConsole(SMSInfo.Entries[i].Ringtone->Name));
saverttl(stdout,SMSInfo.Entries[i].Ringtone);
printf("\n");
if (s.Phone.Functions->PlayTone!=NOTSUPPORTED &&
s.Phone.Functions->PlayTone!=NOTIMPLEMENTED) {
if (answer_yes("Do you want to play it")) GSM_PlayRingtone(*SMSInfo.Entries[i].Ringtone);
}
break;
case SMS_NokiaCallerLogo:
printmsg("Caller logo\n\n");
GSM_PrintBitmap(stdout,&SMSInfo.Entries[i].Bitmap->Bitmap[0]);
break;
case SMS_NokiaOperatorLogo:
printmsg("Operator logo for %s network (%s, %s)\n\n",
SMSInfo.Entries[i].Bitmap->Bitmap[0].NetworkCode,
DecodeUnicodeConsole(GSM_GetNetworkName(SMSInfo.Entries[i].Bitmap->Bitmap[0].NetworkCode)),
DecodeUnicodeConsole(GSM_GetCountryName(SMSInfo.Entries[i].Bitmap->Bitmap[0].NetworkCode)));
GSM_PrintBitmap(stdout,&SMSInfo.Entries[i].Bitmap->Bitmap[0]);
break;
case SMS_NokiaScreenSaverLong:
printmsg("Screen saver\n");
GSM_PrintBitmap(stdout,&SMSInfo.Entries[i].Bitmap->Bitmap[0]);
break;
case SMS_NokiaPictureImageLong:
printmsg("Picture Image\n");
if (UnicodeLength(SMSInfo.Entries[i].Bitmap->Bitmap[0].Text)!=0) printmsg("Text: \"%s\"\n\n",DecodeUnicodeConsole(SMSInfo.Entries[i].Bitmap->Bitmap[0].Text));
GSM_PrintBitmap(stdout,&SMSInfo.Entries[i].Bitmap->Bitmap[0]);
break;
case SMS_NokiaProfileLong:
printmsg("Profile\n");
GSM_PrintBitmap(stdout,&SMSInfo.Entries[i].Bitmap->Bitmap[0]);
break;
case SMS_ConcatenatedTextLong:
case SMS_ConcatenatedAutoTextLong:
case SMS_ConcatenatedTextLong16bit:
case SMS_ConcatenatedAutoTextLong16bit:
printmsg("%s\n",DecodeUnicodeConsole(SMSInfo.Entries[i].Buffer));
break;
case SMS_EMSFixedBitmap:
case SMS_EMSVariableBitmap:
GSM_PrintBitmap(stdout,&SMSInfo.Entries[i].Bitmap->Bitmap[0]);
break;
case SMS_EMSAnimation:
/* Can't show animation, we show first frame */
GSM_PrintBitmap(stdout,&SMSInfo.Entries[i].Bitmap->Bitmap[0]);
break;
case SMS_EMSPredefinedSound:
printmsg("\nEMS sound ID: %i\n",SMSInfo.Entries[i].Number);
break;
case SMS_EMSPredefinedAnimation:
printmsg("\nEMS animation ID: %i\n",SMSInfo.Entries[i].Number);
break;
default:
printf("Error\n");
break;
}
}
printf("\n");
GSM_FreeMultiPartSMSInfo(&SMSInfo);
}
static void NetworkInfo(int argc, char *argv[])
{
GSM_NetworkInfo NetInfo;
GSM_Init(true);
if (Phone->GetNetworkInfo(&s,&NetInfo)==ERR_NONE) {
printmsg("Network state : ");
switch (NetInfo.State) {
case GSM_HomeNetwork : printmsg("home network\n"); break;
case GSM_RoamingNetwork : printmsg("roaming network\n"); break;
case GSM_RequestingNetwork : printmsg("requesting network\n"); break;
case GSM_NoNetwork : printmsg("not logged into network\n"); break;
case GSM_RegistrationDenied : printmsg("registration to network denied\n"); break;
case GSM_NetworkStatusUnknown : printmsg("unknown\n"); break;
default : printmsg("unknown\n");
}
if (NetInfo.State == GSM_HomeNetwork || NetInfo.State == GSM_RoamingNetwork) {
printmsg("Network : %s (%s", NetInfo.NetworkCode,DecodeUnicodeConsole(GSM_GetNetworkName(NetInfo.NetworkCode)));
printmsg(", %s)", DecodeUnicodeConsole(GSM_GetCountryName(NetInfo.NetworkCode)));
printmsg(", LAC %s, CellID %s\n", NetInfo.LAC,NetInfo.CID);
if (NetInfo.NetworkName[0] != 0x00 || NetInfo.NetworkName[1] != 0x00) {
printmsg("Name in phone : \"%s\"\n",DecodeUnicodeConsole(NetInfo.NetworkName));
}
}
}
GSM_Terminate();
}
static void IncomingSMS(char *Device, GSM_SMSMessage sms)
{
GSM_MultiSMSMessage SMS;
printmsg("SMS message received\n");
SMS.Number = 1;
memcpy(&SMS.SMS[0],&sms,sizeof(GSM_SMSMessage));
displaymultismsinfo(SMS,false,false);
}
static void IncomingCB(char *Device, GSM_CBMessage CB)
{
printmsg("CB message received\n");
printmsg("Channel %i, text \"%s\"\n",CB.Channel,DecodeUnicodeConsole(CB.Text));
}
static void IncomingCall(char *Device, GSM_Call call)
{
printmsg("Call info : ");
if (call.CallIDAvailable) printmsg("ID %i, ",call.CallID);
switch(call.Status) {
case GSM_CALL_IncomingCall : printmsg("incoming call from \"%s\"\n",DecodeUnicodeConsole(call.PhoneNumber)); break;
case GSM_CALL_OutgoingCall : printmsg("outgoing call to \"%s\"\n",DecodeUnicodeConsole(call.PhoneNumber)); break;
case GSM_CALL_CallStart : printmsg("call started\n"); break;
case GSM_CALL_CallEnd : printmsg("end of call (unknown side)\n"); break;
case GSM_CALL_CallLocalEnd : printmsg("call end from our side\n"); break;
case GSM_CALL_CallRemoteEnd : printmsg("call end from remote side (code %i)\n",call.StatusCode); break;
case GSM_CALL_CallEstablished : printmsg("call established. Waiting for answer\n"); break;
case GSM_CALL_CallHeld : printmsg("call held\n"); break;
case GSM_CALL_CallResumed : printmsg("call resumed\n"); break;
case GSM_CALL_CallSwitched : printmsg("call switched\n"); break;
}
}
static void IncomingUSSD(char *Device, char *Buffer)
{
printmsg("Service reply: \"%s\"\n",DecodeUnicodeConsole(Buffer));
}
#define CHECKMEMORYSTATUS(x, m, a1, b1) { \
x.MemoryType=m; \
if (Phone->GetMemoryStatus(&s, &x) == ERR_NONE) \
printmsg("%s %03d, %s %03d\n", a1, x.MemoryUsed, b1, x.MemoryFree); \
}
static void Monitor(int argc, char *argv[])
{
GSM_MemoryStatus MemStatus;
GSM_SMSMemoryStatus SMSStatus;
GSM_ToDoStatus ToDoStatus;
GSM_CalendarStatus CalendarStatus;
GSM_NetworkInfo NetInfo;
GSM_BatteryCharge BatteryCharge;
GSM_SignalQuality SignalQuality;
int count = -1;
if (argc >= 3) {
count = atoi(argv[2]);
if (count <= 0) count = -1;
}
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
printmsg("Entering monitor mode...\n\n");
GSM_Init(true);
s.User.IncomingSMS = IncomingSMS;
s.User.IncomingCB = IncomingCB;
s.User.IncomingCall = IncomingCall;
s.User.IncomingUSSD = IncomingUSSD;
error=Phone->SetIncomingSMS (&s,true);
printmsg("Enabling info about incoming SMS : %s\n",print_error(error,NULL,s.msg));
error=Phone->SetIncomingCB (&s,true);
printmsg("Enabling info about incoming CB : %s\n",print_error(error,NULL,s.msg));
error=Phone->SetIncomingCall (&s,true);
printmsg("Enabling info about calls : %s\n",print_error(error,NULL,s.msg));
error=Phone->SetIncomingUSSD (&s,true);
printmsg("Enabling info about USSD : %s\n\n",print_error(error,NULL,s.msg));
while (!gshutdown && count != 0) {
if (count > 0) count--;
CHECKMEMORYSTATUS(MemStatus,MEM_SM,"SIM phonebook : Used","Free");
if (gshutdown) break;
CHECKMEMORYSTATUS(MemStatus,MEM_DC,"Dialled numbers : Used","Free");
if (gshutdown) break;
CHECKMEMORYSTATUS(MemStatus,MEM_RC,"Received numbers : Used","Free");
if (gshutdown) break;
CHECKMEMORYSTATUS(MemStatus,MEM_MC,"Missed numbers : Used","Free");
if (gshutdown) break;
CHECKMEMORYSTATUS(MemStatus,MEM_ON,"Own numbers : Used","Free");
if (gshutdown) break;
CHECKMEMORYSTATUS(MemStatus,MEM_ME,"Phone phonebook : Used","Free");
if (gshutdown) break;
if (Phone->GetToDoStatus(&s, &ToDoStatus) == ERR_NONE) {
printmsg("ToDos : Used %d\n", ToDoStatus.Used);
}
if (gshutdown) break;
if (Phone->GetCalendarStatus(&s, &CalendarStatus) == ERR_NONE) {
printmsg("Calendar : Used %d\n", CalendarStatus.Used);
}
if (gshutdown) break;
if (Phone->GetBatteryCharge(&s,&BatteryCharge)==ERR_NONE) {
if (BatteryCharge.BatteryPercent != -1) printmsg("Battery level : %i percent\n", BatteryCharge.BatteryPercent);
if (BatteryCharge.ChargeState != 0) {
printmsg("Charge state : ");
switch (BatteryCharge.ChargeState) {
case GSM_BatteryPowered:
printmsg("powered from battery");
break;
case GSM_BatteryConnected:
printmsg("battery connected, but not powered from battery");
break;
case GSM_BatteryNotConnected:
printmsg("battery not connected");
break;
case GSM_PowerFault:
printmsg("detected power failure");
break;
default:
printmsg("unknown");
break;
}
printf("\n");
}
}
if (gshutdown) break;
if (Phone->GetSignalQuality(&s,&SignalQuality)==ERR_NONE) {
if (SignalQuality.SignalStrength != -1) printmsg("Signal strength : %i dBm\n", SignalQuality.SignalStrength);
if (SignalQuality.SignalPercent != -1) printmsg("Network level : %i percent\n", SignalQuality.SignalPercent);
if (SignalQuality.BitErrorRate != -1) printmsg("Bit error rate : %i percent\n", SignalQuality.BitErrorRate);
}
if (gshutdown) break;
if (Phone->GetSMSStatus(&s,&SMSStatus)==ERR_NONE) {
if (SMSStatus.SIMSize > 0) {
printmsg("SIM SMS status : %i used, %i unread, %i locations\n",
SMSStatus.SIMUsed,
SMSStatus.SIMUnRead,
SMSStatus.SIMSize);
}
if (SMSStatus.PhoneSize > 0) {
printmsg("Phone SMS status : %i used, %i unread, %i locations",
SMSStatus.PhoneUsed,
SMSStatus.PhoneUnRead,
SMSStatus.PhoneSize);
if (SMSStatus.TemplatesUsed!=0) printmsg(", %i templates", SMSStatus.TemplatesUsed);
printf("\n");
}
}
if (gshutdown) break;
if (Phone->GetNetworkInfo(&s,&NetInfo)==ERR_NONE) {
printmsg("Network state : ");
switch (NetInfo.State) {
case GSM_HomeNetwork : printmsg("home network\n"); break;
case GSM_RoamingNetwork : printmsg("roaming network\n"); break;
case GSM_RequestingNetwork : printmsg("requesting network\n"); break;
case GSM_NoNetwork : printmsg("not logged into network\n"); break;
case GSM_RegistrationDenied : printmsg("registration to network denied\n"); break;
case GSM_NetworkStatusUnknown : printmsg("unknown\n"); break;
default : printmsg("unknown\n");
}
if (NetInfo.State == GSM_HomeNetwork || NetInfo.State == GSM_RoamingNetwork) {
printmsg("Network : %s (%s", NetInfo.NetworkCode,DecodeUnicodeConsole(GSM_GetNetworkName(NetInfo.NetworkCode)));
printmsg(", %s)", DecodeUnicodeConsole(GSM_GetCountryName(NetInfo.NetworkCode)));
printmsg(", LAC %s, CID %s\n", NetInfo.LAC,NetInfo.CID);
if (NetInfo.NetworkName[0] != 0x00 || NetInfo.NetworkName[1] != 0x00) {
printmsg("Name in phone : \"%s\"\n",DecodeUnicodeConsole(NetInfo.NetworkName));
}
}
}
printf("\n");
}
printmsg("Leaving monitor mode...\n");
GSM_Terminate();
}
static void IncomingUSSD2(char *Device, char *Buffer)
{
printmsg("Service reply: \"%s\"\n",DecodeUnicodeConsole(Buffer));
gshutdown = true;
}
static void GetUSSD(int argc, char *argv[])
{
GSM_Init(true);
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
s.User.IncomingUSSD = IncomingUSSD2;
error=Phone->SetIncomingUSSD(&s,true);
Print_Error(error);
error=Phone->DialVoice(&s, argv[2], GSM_CALL_DefaultNumberPresence);
Print_Error(error);
while (!gshutdown) GSM_ReadDevice(&s,true);
GSM_Terminate();
}
static void GetSMSC(int argc, char *argv[])
{
GSM_SMSC smsc;
int start, stop;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
smsc.Location=i;
error=Phone->GetSMSC(&s, &smsc);
Print_Error(error);
if (!strcmp(DecodeUnicodeConsole(smsc.Name),"")) {
printmsg("%i. Set %i\n",smsc.Location, smsc.Location);
} else {
printmsg("%i. \"%s\"\n",smsc.Location, DecodeUnicodeConsole(smsc.Name));
}
printmsg("Number : \"%s\"\n",DecodeUnicodeConsole(smsc.Number));
printmsg("Default number : \"%s\"\n",DecodeUnicodeConsole(smsc.DefaultNumber));
printmsg("Format : ");
switch (smsc.Format) {
case SMS_FORMAT_Text : printmsg("Text"); break;
case SMS_FORMAT_Fax : printmsg("Fax"); break;
case SMS_FORMAT_Email : printmsg("Email"); break;
case SMS_FORMAT_Pager : printmsg("Pager"); break;
}
printf("\n");
printmsg("Validity : ");
switch (smsc.Validity.Relative) {
case SMS_VALID_1_Hour : printmsg("1 hour"); break;
case SMS_VALID_6_Hours : printmsg("6 hours"); break;
case SMS_VALID_1_Day : printmsg("24 hours"); break;
case SMS_VALID_3_Days : printmsg("72 hours"); break;
case SMS_VALID_1_Week : printmsg("1 week"); break;
case SMS_VALID_Max_Time : printmsg("Maximum time"); break;
default :
if (smsc.Validity.Relative >= 0 && smsc.Validity.Relative <= 143) {
printmsg("%i minutes",(smsc.Validity.Relative+1)*5);
} else if (smsc.Validity.Relative >= 144 && smsc.Validity.Relative <= 167) {
printmsg("%i minutes",12*60 + (smsc.Validity.Relative-143)*30);
} else if (smsc.Validity.Relative >= 168 && smsc.Validity.Relative <= 196) {
printmsg("%i days",smsc.Validity.Relative-166);
} else if (smsc.Validity.Relative >= 197 && smsc.Validity.Relative <= 255) {
printmsg("%i weeks",smsc.Validity.Relative-192);
}
}
printf("\n");
}
GSM_Terminate();
}
static void GetSMS(int argc, char *argv[])
{
GSM_MultiSMSMessage sms;
GSM_SMSFolders folders;
int start, stop;
int j;
GetStartStop(&start, &stop, 3, argc, argv);
GSM_Init(true);
error=Phone->GetSMSFolders(&s, &folders);
Print_Error(error);
for (j = start; j <= stop; j++) {
sms.SMS[0].Folder = atoi(argv[2]);
sms.SMS[0].Location = j;
error=Phone->GetSMS(&s, &sms);
switch (error) {
case ERR_EMPTY:
printmsg("Location %i\n",sms.SMS[0].Location);
printmsg("Empty\n");
break;
default:
Print_Error(error);
printmsg("Location %i, folder \"%s\"",sms.SMS[0].Location,DecodeUnicodeConsole(folders.Folder[sms.SMS[0].Folder-1].Name));
switch(sms.SMS[0].Memory) {
case MEM_SM: printmsg(", SIM memory"); break;
case MEM_ME: printmsg(", phone memory"); break;
case MEM_MT: printmsg(", phone or SIM memory"); break;
default : break;
}
if (sms.SMS[0].InboxFolder) printmsg(", Inbox folder");
printf("\n");
displaymultismsinfo(sms,false,false);
}
}
GSM_Terminate();
}
static void DeleteSMS(int argc, char *argv[])
{
GSM_SMSMessage sms;
int start, stop;
sms.Folder=atoi(argv[2]);
GetStartStop(&start, &stop, 3, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
sms.Folder = 0;
sms.Location = i;
error=Phone->DeleteSMS(&s, &sms);
Print_Error(error);
}
#ifdef GSM_ENABLE_BEEP
GSM_PhoneBeep();
#endif
GSM_Terminate();
}
static void GetAllSMS(int argc, char *argv[])
{
GSM_MultiSMSMessage sms;
GSM_SMSFolders folders;
bool start = true;
GSM_Init(true);
error=Phone->GetSMSFolders(&s, &folders);
Print_Error(error);
while (error == ERR_NONE) {
sms.SMS[0].Folder=0x00;
error=Phone->GetNextSMS(&s, &sms, start);
switch (error) {
case ERR_EMPTY:
break;
default:
Print_Error(error);
printmsg("Location %i, folder \"%s\"",sms.SMS[0].Location,DecodeUnicodeConsole(folders.Folder[sms.SMS[0].Folder-1].Name));
switch(sms.SMS[0].Memory) {
case MEM_SM: printmsg(", SIM memory"); break;
case MEM_ME: printmsg(", phone memory"); break;
case MEM_MT: printmsg(", phone or SIM memory"); break;
default : break;
}
if (sms.SMS[0].InboxFolder) printmsg(", Inbox folder");
printf("\n");
displaymultismsinfo(sms,false,false);
}
start=false;
}
fprintf(stderr,"\n");
#ifdef GSM_ENABLE_BEEP
GSM_PhoneBeep();
#endif
GSM_Terminate();
}
static void GetEachSMS(int argc, char *argv[])
{
GSM_MultiSMSMessage *GetSMS[PHONE_MAXSMSINFOLDER],*SortedSMS[PHONE_MAXSMSINFOLDER],sms;
int GetSMSNumber = 0,i,j;
GSM_SMSFolders folders;
bool start = true, ems = true;
GetSMS[0] = NULL;
GSM_Init(true);
error=Phone->GetSMSFolders(&s, &folders);
Print_Error(error);
fprintf(stderr,"Reading: ");
while (error == ERR_NONE) {
sms.SMS[0].Folder=0x00;
error=Phone->GetNextSMS(&s, &sms, start);
switch (error) {
case ERR_EMPTY:
break;
default:
Print_Error(error);
GetSMS[GetSMSNumber] = malloc(sizeof(GSM_MultiSMSMessage));
if (GetSMS[GetSMSNumber] == NULL) Print_Error(ERR_MOREMEMORY);
GetSMS[GetSMSNumber+1] = NULL;
memcpy(GetSMS[GetSMSNumber],&sms,sizeof(GSM_MultiSMSMessage));
GetSMSNumber++;
if (GetSMSNumber==PHONE_MAXSMSINFOLDER) {
fprintf(stderr,"SMS counter overflow\n");
return;
}
}
fprintf(stderr,"*");
start=false;
}
fprintf(stderr,"\n");
#ifdef GSM_ENABLE_BEEP
GSM_PhoneBeep();
#endif
error = GSM_LinkSMS(GetSMS, SortedSMS, ems);
Print_Error(error);
i=0;
while(GetSMS[i] != NULL) {
free(GetSMS[i]);
GetSMS[i] = NULL;
i++;
}
i=0;
while(SortedSMS[i] != NULL) {
for (j=0;j<SortedSMS[i]->Number;j++) {
if ((j==0) || (j!=0 && SortedSMS[i]->SMS[j].Location != SortedSMS[i]->SMS[j-1].Location)) {
printmsg("Location %i, folder \"%s\"",SortedSMS[i]->SMS[j].Location,DecodeUnicodeConsole(folders.Folder[SortedSMS[i]->SMS[j].Folder-1].Name));
switch(SortedSMS[i]->SMS[j].Memory) {
case MEM_SM: printmsg(", SIM memory"); break;
case MEM_ME: printmsg(", phone memory"); break;
case MEM_MT: printmsg(", phone or SIM memory"); break;
default : break;
}
if (SortedSMS[i]->SMS[j].InboxFolder) printmsg(", Inbox folder");
printf("\n");
}
}
displaymultismsinfo(*SortedSMS[i],true,ems);
free(SortedSMS[i]);
SortedSMS[i] = NULL;
i++;
}
GSM_Terminate();
}
static void GetSMSFolders(int argc, char *argv[])
{
GSM_SMSFolders folders;
GSM_Init(true);
error=Phone->GetSMSFolders(&s,&folders);
Print_Error(error);
for (i=0;i<folders.Number;i++) {
printmsg("%i. \"%30s\"",i+1,DecodeUnicodeConsole(folders.Folder[i].Name));
switch(folders.Folder[i].Memory) {
case MEM_SM: printmsg(", SIM memory"); break;
case MEM_ME: printmsg(", phone memory"); break;
case MEM_MT: printmsg(", phone or SIM memory"); break;
default : break;
}
if (folders.Folder[i].InboxFolder) printmsg(", Inbox folder");
printf("\n");
}
GSM_Terminate();
}
static void GetRingtone(int argc, char *argv[])
{
GSM_Ringtone ringtone;
bool PhoneRingtone = false;
if (mystrncasecmp(argv[1],"--getphoneringtone",0)) PhoneRingtone = true;
GetStartStop(&ringtone.Location, NULL, 2, argc, argv);
GSM_Init(true);
ringtone.Format=0;
error=Phone->GetRingtone(&s,&ringtone,PhoneRingtone);
Print_Error(error);
switch (ringtone.Format) {
case RING_NOTETONE : printmsg("Smart Messaging"); break;
case RING_NOKIABINARY : printmsg("Nokia binary"); break;
case RING_MIDI : printmsg("MIDI"); break;
case RING_MMF : printmsg("SMAF (MMF)"); break;
}
printmsg(" format, ringtone \"%s\"\n",DecodeUnicodeConsole(ringtone.Name));
if (argc==4) {
error=GSM_SaveRingtoneFile(argv[3], &ringtone);
Print_Error(error);
}
GSM_Terminate();
}
static void GetRingtonesList(int argc, char *argv[])
{
GSM_AllRingtonesInfo Info;
int i;
GSM_Init(true);
error=Phone->GetRingtonesInfo(&s,&Info);
Print_Error(error);
GSM_Terminate();
for (i=0;i<Info.Number;i++) printmsg("%i. \"%s\"\n",i,DecodeUnicodeConsole(Info.Ringtone[i].Name));
}
static void DialVoice(int argc, char *argv[])
{
GSM_CallShowNumber ShowNumber = GSM_CALL_DefaultNumberPresence;
if (argc > 3) {
if (mystrncasecmp(argv[3],"show",0)) { ShowNumber = GSM_CALL_ShowNumber;
} else if (mystrncasecmp(argv[3],"hide",0)) { ShowNumber = GSM_CALL_HideNumber;
} else {
printmsg("Unknown parameter (\"%s\")\n",argv[3]);
exit(-1);
}
}
GSM_Init(true);
error=Phone->DialVoice(&s, argv[2], ShowNumber);
Print_Error(error);
GSM_Terminate();
}
static void CancelCall(int argc, char *argv[])
{
GSM_Init(true);
if (argc>2) {
error=Phone->CancelCall(&s,atoi(argv[2]),false);
} else {
error=Phone->CancelCall(&s,0,true);
}
Print_Error(error);
GSM_Terminate();
}
static void AnswerCall(int argc, char *argv[])
{
GSM_Init(true);
if (argc>2) {
error=Phone->AnswerCall(&s,atoi(argv[2]),false);
} else {
error=Phone->AnswerCall(&s,0,true);
}
Print_Error(error);
GSM_Terminate();
}
static void UnholdCall(int argc, char *argv[])
{
GSM_Init(true);
error=Phone->UnholdCall(&s,atoi(argv[2]));
Print_Error(error);
GSM_Terminate();
}
static void HoldCall(int argc, char *argv[])
{
GSM_Init(true);
error=Phone->HoldCall(&s,atoi(argv[2]));
Print_Error(error);
GSM_Terminate();
}
static void ConferenceCall(int argc, char *argv[])
{
GSM_Init(true);
error=Phone->ConferenceCall(&s,atoi(argv[2]));
Print_Error(error);
GSM_Terminate();
}
static void SplitCall(int argc, char *argv[])
{
GSM_Init(true);
error=Phone->SplitCall(&s,atoi(argv[2]));
Print_Error(error);
GSM_Terminate();
}
static void SwitchCall(int argc, char *argv[])
{
GSM_Init(true);
if (argc > 2) {
error=Phone->SwitchCall(&s,atoi(argv[2]),false);
} else {
error=Phone->SwitchCall(&s,0,true);
}
Print_Error(error);
GSM_Terminate();
}
static void TransferCall(int argc, char *argv[])
{
GSM_Init(true);
if (argc > 2) {
error=Phone->TransferCall(&s,atoi(argv[2]),false);
} else {
error=Phone->TransferCall(&s,0,true);
}
Print_Error(error);
GSM_Terminate();
}
static void AddSMSFolder(int argc, char *argv[])
{
unsigned char buffer[200];
GSM_Init(true);
EncodeUnicode(buffer,argv[2],strlen(argv[2]));
error=Phone->AddSMSFolder(&s,buffer);
Print_Error(error);
GSM_Terminate();
}
static void Reset(int argc, char *argv[])
{
bool hard;
if (mystrncasecmp(argv[2],"SOFT",0)) { hard=false;
} else if (mystrncasecmp(argv[2],"HARD",0)) { hard=true;
} else {
printmsg("What type of reset do you want (\"%s\") ?\n",argv[2]);
exit(-1);
}
GSM_Init(true);
error=Phone->Reset(&s, hard);
Print_Error(error);
GSM_Terminate();
}
static void PrintCalendar(GSM_CalendarEntry *Note)
{
int i_age = 0,i;
GSM_DateTime Alarm,DateTime;
GSM_MemoryEntry entry;
unsigned char *name;
bool repeating = false;
int repeat_dayofweek = -1;
int repeat_day = -1;
int repeat_weekofmonth = -1;
int repeat_month = -1;
int repeat_frequency = -1;
GSM_DateTime repeat_startdate = {0,0,0,0,0,0,0};
GSM_DateTime repeat_stopdate = {0,0,0,0,0,0,0};
printmsg("Location : %d\n", Note->Location);
printmsg("Note type : ");
switch (Note->Type) {
case GSM_CAL_REMINDER : printmsg("Reminder (Date)\n"); break;
case GSM_CAL_CALL : printmsg("Call\n"); break;
case GSM_CAL_MEETING : printmsg("Meeting\n"); break;
case GSM_CAL_BIRTHDAY : printmsg("Birthday (Anniversary)\n"); break;
case GSM_CAL_MEMO : printmsg("Memo (Miscellaneous)\n"); break;
case GSM_CAL_TRAVEL : printmsg("Travel\n"); break;
case GSM_CAL_VACATION : printmsg("Vacation\n"); break;
case GSM_CAL_ALARM : printmsg("Alarm\n"); break;
case GSM_CAL_DAILY_ALARM : printmsg("Daily alarm\n"); break;
case GSM_CAL_T_ATHL : printmsg("Training/Athletism\n"); break;
case GSM_CAL_T_BALL : printmsg("Training/Ball Games\n"); break;
case GSM_CAL_T_CYCL : printmsg("Training/Cycling\n"); break;
case GSM_CAL_T_BUDO : printmsg("Training/Budo\n"); break;
case GSM_CAL_T_DANC : printmsg("Training/Dance\n"); break;
case GSM_CAL_T_EXTR : printmsg("Training/Extreme Sports\n"); break;
case GSM_CAL_T_FOOT : printmsg("Training/Football\n"); break;
case GSM_CAL_T_GOLF : printmsg("Training/Golf\n"); break;
case GSM_CAL_T_GYM : printmsg("Training/Gym\n"); break;
case GSM_CAL_T_HORS : printmsg("Training/Horse Races\n"); break;
case GSM_CAL_T_HOCK : printmsg("Training/Hockey\n"); break;
case GSM_CAL_T_RACE : printmsg("Training/Races\n"); break;
case GSM_CAL_T_RUGB : printmsg("Training/Rugby\n"); break;
case GSM_CAL_T_SAIL : printmsg("Training/Sailing\n"); break;
case GSM_CAL_T_STRE : printmsg("Training/Street Games\n"); break;
case GSM_CAL_T_SWIM : printmsg("Training/Swimming\n"); break;
case GSM_CAL_T_TENN : printmsg("Training/Tennis\n"); break;
case GSM_CAL_T_TRAV : printmsg("Training/Travels\n"); break;
case GSM_CAL_T_WINT : printmsg("Training/Winter Games\n"); break;
default : printmsg("UNKNOWN\n");
}
Alarm.Year = 0;
repeating = false;
repeat_dayofweek = -1;
repeat_day = -1;
repeat_weekofmonth = -1;
repeat_month = -1;
repeat_frequency = -1;
repeat_startdate.Day = 0;
repeat_stopdate.Day = 0;
for (i=0;i<Note->EntriesNum;i++) {
switch (Note->Entries[i].EntryType) {
case CAL_START_DATETIME:
printmsg("Start : %s\n",OSDateTime(Note->Entries[i].Date,false));
memcpy(&DateTime,&Note->Entries[i].Date,sizeof(GSM_DateTime));
break;
case CAL_END_DATETIME:
printmsg("Stop : %s\n",OSDateTime(Note->Entries[i].Date,false));
memcpy(&DateTime,&Note->Entries[i].Date,sizeof(GSM_DateTime));
break;
case CAL_ALARM_DATETIME:
printmsg("Tone alarm : %s\n",OSDateTime(Note->Entries[i].Date,false));
memcpy(&Alarm,&Note->Entries[i].Date,sizeof(GSM_DateTime));
break;
case CAL_SILENT_ALARM_DATETIME:
printmsg("Silent alarm : %s\n",OSDateTime(Note->Entries[i].Date,false));
memcpy(&Alarm,&Note->Entries[i].Date,sizeof(GSM_DateTime));
break;
case CAL_RECURRANCE:
printmsg("Repeat : %d day%s\n",Note->Entries[i].Number/24,
((Note->Entries[i].Number/24)>1) ? "s":"" );
break;
case CAL_TEXT:
printmsg("Text : \"%s\"\n",DecodeUnicodeConsole(Note->Entries[i].Text));
break;
case CAL_LOCATION:
printmsg("Location : \"%s\"\n",DecodeUnicodeConsole(Note->Entries[i].Text));
break;
case CAL_PHONE:
printmsg("Phone : \"%s\"\n",DecodeUnicodeConsole(Note->Entries[i].Text));
break;
case CAL_PRIVATE:
printmsg("Private : %s\n",Note->Entries[i].Number == 1 ? "Yes" : "No");
break;
case CAL_CONTACTID:
entry.Location = Note->Entries[i].Number;
entry.MemoryType = MEM_ME;
error=Phone->GetMemory(&s, &entry);
if (error == ERR_NONE) {
name = GSM_PhonebookGetEntryName(&entry);
if (name != NULL) {
printmsg("Contact ID : \"%s\" (%d)\n", DecodeUnicodeConsole(name), Note->Entries[i].Number);
} else {
printmsg("Contact ID : %d\n",Note->Entries[i].Number);
}
} else {
printmsg("Contact ID : %d\n",Note->Entries[i].Number);
}
break;
case CAL_REPEAT_DAYOFWEEK:
repeat_dayofweek = Note->Entries[i].Number;
repeating = true;
break;
case CAL_REPEAT_DAY:
repeat_day = Note->Entries[i].Number;
repeating = true;
break;
case CAL_REPEAT_WEEKOFMONTH:
repeat_weekofmonth = Note->Entries[i].Number;
repeating = true;
break;
case CAL_REPEAT_MONTH:
repeat_month = Note->Entries[i].Number;
repeating = true;
break;
case CAL_REPEAT_FREQUENCY:
repeat_frequency = Note->Entries[i].Number;
repeating = true;
break;
case CAL_REPEAT_STARTDATE:
repeat_startdate = Note->Entries[i].Date;
repeating = true;
break;
case CAL_REPEAT_STOPDATE:
repeat_stopdate = Note->Entries[i].Date;
repeating = true;
break;
}
}
if (repeating) {
printmsg("Repeating : ");
if ((repeat_startdate.Day == 0) && (repeat_stopdate.Day == 0)) {
printmsg("Forever");
} else if (repeat_startdate.Day == 0) {
printmsg("Till %s", OSDate(repeat_stopdate));
} else if (repeat_stopdate.Day == 0) {
printmsg("Since %s", OSDate(repeat_startdate));
} else {
printmsg("Since %s till %s", OSDate(repeat_startdate), OSDate(repeat_stopdate));
}
if (repeat_frequency != -1) {
if (repeat_frequency == 1) {
printmsg (" on each ");
} else {
printmsg(" on each %d. ", repeat_frequency);
}
if (repeat_dayofweek > 0) {
switch (repeat_dayofweek) {
case 1 : printmsg("Monday"); break;
case 2 : printmsg("Tuesday"); break;
case 3 : printmsg("Wednesday"); break;
case 4 : printmsg("Thursday"); break;
case 5 : printmsg("Friday"); break;
case 6 : printmsg("Saturday"); break;
case 7 : printmsg("Sunday"); break;
default: printmsg("Bad day!"); break;
}
if (repeat_weekofmonth > 0) {
printmsg(" in %d. week of ", repeat_weekofmonth);
} else {
printmsg(" in ");
}
if (repeat_month > 0) {
switch(repeat_month) {
case 1 : printmsg("January"); break;
case 2 : printmsg("February"); break;
case 3 : printmsg("March"); break;
case 4 : printmsg("April"); break;
case 5 : printmsg("May"); break;
case 6 : printmsg("June"); break;
case 7 : printmsg("July"); break;
case 8 : printmsg("August"); break;
case 9 : printmsg("September"); break;
case 10: printmsg("October"); break;
case 11: printmsg("November"); break;
case 12: printmsg("December"); break;
default: printmsg("Bad month!"); break;
}
} else {
printmsg("each month");
}
} else if (repeat_day > 0) {
printmsg("%d. day of ", repeat_day);
if (repeat_month > 0) {
switch(repeat_month) {
case 1 : printmsg("January"); break;
case 2 : printmsg("February"); break;
case 3 : printmsg("March"); break;
case 4 : printmsg("April"); break;
case 5 : printmsg("May"); break;
case 6 : printmsg("June"); break;
case 7 : printmsg("July"); break;
case 8 : printmsg("August"); break;
case 9 : printmsg("September"); break;
case 10: printmsg("October"); break;
case 11: printmsg("November"); break;
case 12: printmsg("December"); break;
default: printmsg("Bad month!");break;
}
} else {
printmsg("each month");
}
} else {
printmsg("day");
}
}
printf("\n");
}
if (Note->Type == GSM_CAL_BIRTHDAY) {
if (Alarm.Year == 0x00) GSM_GetCurrentDateTime (&Alarm);
if (DateTime.Year != 0) {
i_age = Alarm.Year - DateTime.Year;
if (DateTime.Month < Alarm.Month) i_age++;
if (DateTime.Month == Alarm.Month &&
DateTime.Day < Alarm.Day) {
i_age++;
}
printmsg("Age : %d %s\n",i_age, (i_age==1)?"year":"years");
}
}
printf("\n");
}
static void GetCalendar(int argc, char *argv[])
{
GSM_CalendarEntry Note;
int start,stop;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
Note.Location=i;
error = Phone->GetCalendar(&s, &Note);
if (error == ERR_EMPTY) continue;
Print_Error(error);
PrintCalendar(&Note);
}
GSM_Terminate();
}
static void DeleteCalendar(int argc, char *argv[])
{
GSM_CalendarEntry Note;
int start,stop;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
Note.Location=i;
error = Phone->DeleteCalendar(&s, &Note);
if (error == ERR_EMPTY) continue;
Print_Error(error);
PrintCalendar(&Note);
}
GSM_Terminate();
}
static void GetAllCalendar(int argc, char *argv[])
{
GSM_CalendarEntry Note;
bool refresh = true;
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
GSM_Init(true);
while (!gshutdown) {
error=Phone->GetNextCalendar(&s,&Note,refresh);
if (error == ERR_EMPTY) break;
Print_Error(error);
PrintCalendar(&Note);
refresh=false;
}
GSM_Terminate();
}
static void GetCalendarSettings(int argc, char *argv[])
{
GSM_CalendarSettings settings;
GSM_Init(true);
error=Phone->GetCalendarSettings(&s,&settings);
Print_Error(error);
if (settings.AutoDelete == 0) {
printmsg("Auto deleting disabled");
} else {
printmsg("Auto deleting notes after %i day(s)",settings.AutoDelete);
}
printmsg("\nWeek start on ");
switch(settings.StartDay) {
case 1: printmsg("Monday"); break;
case 6: printmsg("Saturday"); break;
case 7: printmsg("Sunday"); break;
}
printf("\n");
GSM_Terminate();
}
static void GetWAPBookmark(int argc, char *argv[])
{
GSM_WAPBookmark bookmark;
int start,stop;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
bookmark.Location=i;
error=Phone->GetWAPBookmark(&s,&bookmark);
Print_Error(error);
printmsg("Name : \"%s\"\n",DecodeUnicodeConsole(bookmark.Title));
printmsg("Address : \"%s\"\n",DecodeUnicodeConsole(bookmark.Address));
}
GSM_Terminate();
}
static void DeleteWAPBookmark(int argc, char *argv[])
{
GSM_WAPBookmark bookmark;
int start, stop;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
bookmark.Location=i;
error=Phone->DeleteWAPBookmark(&s, &bookmark);
Print_Error(error);
}
GSM_Terminate();
}
static void GetGPRSPoint(int argc, char *argv[])
{
GSM_GPRSAccessPoint point;
int start,stop;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
point.Location=i;
error=Phone->GetGPRSAccessPoint(&s,&point);
if (error != ERR_EMPTY) {
Print_Error(error);
printmsg("%i. \"%s\"",point.Location,DecodeUnicodeConsole(point.Name));
} else {
printmsg("%i. Access point %i",point.Location,point.Location);
}
if (point.Active) printmsg(" (active)");
if (error != ERR_EMPTY) {
printmsg("\nAddress : \"%s\"\n\n",DecodeUnicodeConsole(point.URL));
} else {
printmsg("\n\n");
}
}
GSM_Terminate();
}
static void GetBitmap(int argc, char *argv[])
{
GSM_File File;
GSM_MultiBitmap MultiBitmap;
int location=0;
GSM_AllRingtonesInfo Info;
if (mystrncasecmp(argv[2],"STARTUP",0)) {
MultiBitmap.Bitmap[0].Type=GSM_StartupLogo;
} else if (mystrncasecmp(argv[2],"CALLER",0)) {
MultiBitmap.Bitmap[0].Type=GSM_CallerGroupLogo;
GetStartStop(&location, NULL, 3, argc, argv);
if (location>5) {
printmsg("Maximal location for caller logo can be 5\n");
exit (-1);
}
} else if (mystrncasecmp(argv[2],"PICTURE",0)) {
MultiBitmap.Bitmap[0].Type=GSM_PictureImage;
GetStartStop(&location, NULL, 3, argc, argv);
} else if (mystrncasecmp(argv[2],"TEXT",0)) {
MultiBitmap.Bitmap[0].Type=GSM_WelcomeNote_Text;
} else if (mystrncasecmp(argv[2],"DEALER",0)) {
MultiBitmap.Bitmap[0].Type=GSM_DealerNote_Text;
} else if (mystrncasecmp(argv[2],"OPERATOR",0)) {
MultiBitmap.Bitmap[0].Type=GSM_OperatorLogo;
} else {
printmsg("What type of logo do you want to get (\"%s\") ?\n",argv[2]);
exit(-1);
}
MultiBitmap.Bitmap[0].Location=location;
GSM_Init(true);
error=Phone->GetBitmap(&s,&MultiBitmap.Bitmap[0]);
Print_Error(error);
MultiBitmap.Number = 1;
error=ERR_NONE;
switch (MultiBitmap.Bitmap[0].Type) {
case GSM_CallerGroupLogo:
if (!MultiBitmap.Bitmap[0].DefaultBitmap) GSM_PrintBitmap(stdout,&MultiBitmap.Bitmap[0]);
printmsg("Group name : \"%s\"",DecodeUnicodeConsole(MultiBitmap.Bitmap[0].Text));
if (MultiBitmap.Bitmap[0].DefaultName) printmsg(" (default)");
printf("\n");
if (MultiBitmap.Bitmap[0].DefaultRingtone) {
printmsg("Ringtone : default\n");
} else if (MultiBitmap.Bitmap[0].FileSystemRingtone) {
sprintf(File.ID_FullName,"%i",MultiBitmap.Bitmap[0].RingtoneID);
File.Buffer = NULL;
File.Used = 0;
error = ERR_NONE;
// while (error == ERR_NONE) {
error = Phone->GetFilePart(&s,&File);
// }
if (error != ERR_EMPTY && error != ERR_WRONGCRC) Print_Error(error);
error = ERR_NONE;
printmsg("Ringtone : \"%s\" (file with ID %i)\n",
DecodeUnicodeString(File.Name),
MultiBitmap.Bitmap[0].RingtoneID);
} else {
error = Phone->GetRingtonesInfo(&s,&Info);
if (error != ERR_NONE) Info.Number = 0;
error = ERR_NONE;
printmsg("Ringtone : ");
if (UnicodeLength(GSM_GetRingtoneName(&Info,MultiBitmap.Bitmap[0].RingtoneID))!=0) {
printmsg("\"%s\" (ID %i)\n",
DecodeUnicodeConsole(GSM_GetRingtoneName(&Info,MultiBitmap.Bitmap[0].RingtoneID)),
MultiBitmap.Bitmap[0].RingtoneID);
} else {
printmsg("ID %i\n",MultiBitmap.Bitmap[0].RingtoneID);
}
}
if (MultiBitmap.Bitmap[0].BitmapEnabled) {
printmsg("Bitmap : enabled\n");
} else {
printmsg("Bitmap : disabled\n");
}
if (argc>4 && !MultiBitmap.Bitmap[0].DefaultBitmap) error=GSM_SaveBitmapFile(argv[4],&MultiBitmap);
break;
case GSM_StartupLogo:
GSM_PrintBitmap(stdout,&MultiBitmap.Bitmap[0]);
if (argc>3) error=GSM_SaveBitmapFile(argv[3],&MultiBitmap);
break;
case GSM_OperatorLogo:
if (strcmp(MultiBitmap.Bitmap[0].NetworkCode,"000 00")!=0) {
GSM_PrintBitmap(stdout,&MultiBitmap.Bitmap[0]);
if (argc>3) error=GSM_SaveBitmapFile(argv[3],&MultiBitmap);
} else {
printmsg("No operator logo in phone\n");
}
break;
case GSM_PictureImage:
GSM_PrintBitmap(stdout,&MultiBitmap.Bitmap[0]);
printmsg("Text : \"%s\"\n",DecodeUnicodeConsole(MultiBitmap.Bitmap[0].Text));
printmsg("Sender : \"%s\"\n",DecodeUnicodeConsole(MultiBitmap.Bitmap[0].Sender));
if (MultiBitmap.Bitmap[0].Name)
printmsg("Name : \"%s\"\n",DecodeUnicodeConsole(MultiBitmap.Bitmap[0].Name));
if (argc>4) error=GSM_SaveBitmapFile(argv[4],&MultiBitmap);
break;
case GSM_WelcomeNote_Text:
printmsg("Welcome note text is \"%s\"\n",DecodeUnicodeConsole(MultiBitmap.Bitmap[0].Text));
break;
case GSM_DealerNote_Text:
printmsg("Dealer note text is \"%s\"\n",DecodeUnicodeConsole(MultiBitmap.Bitmap[0].Text));
break;
default:
break;
}
Print_Error(error);
GSM_Terminate();
}
static void SetBitmap(int argc, char *argv[])
{
GSM_Bitmap Bitmap, NewBitmap;
GSM_MultiBitmap MultiBitmap;
GSM_NetworkInfo NetInfo;
bool init = true;
if (mystrncasecmp(argv[2],"STARTUP",0)) {
if (argc<4) {
printmsg("More arguments required\n");
exit(-1);
}
MultiBitmap.Bitmap[0].Type=GSM_StartupLogo;
MultiBitmap.Bitmap[0].Location=1;
if (!strcmp(argv[3],"1")) MultiBitmap.Bitmap[0].Location = 2;
if (!strcmp(argv[3],"2")) MultiBitmap.Bitmap[0].Location = 3;
if (!strcmp(argv[3],"3")) MultiBitmap.Bitmap[0].Location = 4;
if (MultiBitmap.Bitmap[0].Location == 1) {
error=GSM_ReadBitmapFile(argv[3],&MultiBitmap);
Print_Error(error);
}
memcpy(&Bitmap,&MultiBitmap.Bitmap[0],sizeof(GSM_Bitmap));
} else if (mystrncasecmp(argv[2],"TEXT",0)) {
if (argc<4) {
printmsg("More arguments required\n");
exit(-1);
}
Bitmap.Type=GSM_WelcomeNote_Text;
EncodeUnicode(Bitmap.Text,argv[3],strlen(argv[3]));
} else if (mystrncasecmp(argv[2],"DEALER",0)) {
if (argc<4) {
printmsg("More arguments required\n");
exit(-1);
}
Bitmap.Type=GSM_DealerNote_Text;
EncodeUnicode(Bitmap.Text,argv[3],strlen(argv[3]));
} else if (mystrncasecmp(argv[2],"CALLER",0)) {
if (argc<4) {
printmsg("More arguments required\n");
exit(-1);
}
GetStartStop(&i, NULL, 3, argc, argv);
if (i>5 && i!=255) {
printmsg("Maximal location for caller logo can be 5\n");
exit (-1);
}
MultiBitmap.Bitmap[0].Type = GSM_CallerGroupLogo;
MultiBitmap.Bitmap[0].Location = i;
if (argc>4) {
error=GSM_ReadBitmapFile(argv[4],&MultiBitmap);
Print_Error(error);
}
memcpy(&Bitmap,&MultiBitmap.Bitmap[0],sizeof(GSM_Bitmap));
if (i!=255) {
GSM_Init(true);
init = false;
NewBitmap.Type = GSM_CallerGroupLogo;
NewBitmap.Location = i;
error=Phone->GetBitmap(&s,&NewBitmap);
Print_Error(error);
Bitmap.RingtoneID = NewBitmap.RingtoneID;
Bitmap.DefaultRingtone = NewBitmap.DefaultRingtone;
Bitmap.FileSystemRingtone = false;
CopyUnicodeString(Bitmap.Text, NewBitmap.Text);
Bitmap.DefaultName = NewBitmap.DefaultName;
}
} else if (mystrncasecmp(argv[2],"PICTURE",0)) {
if (argc<5) {
printmsg("More arguments required\n");
exit(-1);
}
MultiBitmap.Bitmap[0].Type = GSM_PictureImage;
MultiBitmap.Bitmap[0].Location = atoi(argv[4]);
error=GSM_ReadBitmapFile(argv[3],&MultiBitmap);
Print_Error(error);
memcpy(&Bitmap,&MultiBitmap.Bitmap[0],sizeof(GSM_Bitmap));
Bitmap.Text[0]=0;
Bitmap.Text[1]=0;
if (argc == 6) EncodeUnicode(Bitmap.Text,argv[5],strlen(argv[5]));
Bitmap.Sender[0]=0;
Bitmap.Sender[1]=0;
} else if (mystrncasecmp(argv[2],"COLOUROPERATOR",0)) {
Bitmap.Type = GSM_ColourOperatorLogo_ID;
strcpy(Bitmap.NetworkCode,"000 00");
if (argc > 3) {
Bitmap.ID = atoi(argv[3]);
if (argc>4) {
strncpy(Bitmap.NetworkCode,argv[4],6);
} else {
GSM_Init(true);
init = false;
error=Phone->GetNetworkInfo(&s,&NetInfo);
Print_Error(error);
strcpy(Bitmap.NetworkCode,NetInfo.NetworkCode);
}
}
} else if (mystrncasecmp(argv[2],"COLOURSTARTUP",0)) {
Bitmap.Type = GSM_ColourStartupLogo_ID;
Bitmap.Location = 0;
if (argc > 3) {
Bitmap.Location = 1;
Bitmap.ID = atoi(argv[3]);
}
} else if (mystrncasecmp(argv[2],"WALLPAPER",0)) {
Bitmap.Type = GSM_ColourWallPaper_ID;
Bitmap.ID = 0;
if (argc > 3) Bitmap.ID = atoi(argv[3]);
} else if (mystrncasecmp(argv[2],"OPERATOR",0)) {
MultiBitmap.Bitmap[0].Type = GSM_OperatorLogo;
MultiBitmap.Bitmap[0].Location = 1;
strcpy(MultiBitmap.Bitmap[0].NetworkCode,"000 00");
if (argc>3) {
error=GSM_ReadBitmapFile(argv[3],&MultiBitmap);
Print_Error(error);
if (argc>4) {
strncpy(MultiBitmap.Bitmap[0].NetworkCode,argv[4],6);
} else {
GSM_Init(true);
init = false;
error=Phone->GetNetworkInfo(&s,&NetInfo);
Print_Error(error);
strcpy(MultiBitmap.Bitmap[0].NetworkCode,NetInfo.NetworkCode);
}
}
memcpy(&Bitmap,&MultiBitmap.Bitmap[0],sizeof(GSM_Bitmap));
} else {
printmsg("What type of logo do you want to set (\"%s\") ?\n",argv[2]);
exit(-1);
}
if (init) GSM_Init(true);
error=Phone->SetBitmap(&s,&Bitmap);
Print_Error(error);
#ifdef GSM_ENABLE_BEEP
GSM_PhoneBeep();
#endif
GSM_Terminate();
}
static void SetRingtone(int argc, char *argv[])
{
GSM_Ringtone ringtone;
int i,nextlong=0;
ringtone.Format = 0;
error=GSM_ReadRingtoneFile(argv[2],&ringtone);
Print_Error(error);
ringtone.Location = 255;
for (i=3;i<argc;i++) {
switch (nextlong) {
case 0:
if (mystrncasecmp(argv[i],"-scale",0)) {
ringtone.NoteTone.AllNotesScale = true;
break;
}
if (mystrncasecmp(argv[i],"-location",0)) {
nextlong = 1;
break;
}
if (mystrncasecmp(argv[i],"-name",0)) {
nextlong = 2;
break;
}
printmsg("Unknown parameter \"%s\"",argv[i]);
exit(-1);
case 1:
ringtone.Location=atoi(argv[i]);
nextlong = 0;
break;
case 2:
EncodeUnicode(ringtone.Name,argv[i],strlen(argv[i]));
nextlong = 0;
break;
}
}
if (nextlong!=0) {
printmsg("Parameter missed...\n");
exit(-1);
}
if (ringtone.Location==0) {
printmsg("ERROR: enumerate locations from 1\n");
exit (-1);
}
GSM_Init(true);
error=Phone->SetRingtone(&s, &ringtone, &i);
Print_Error(error);
#ifdef GSM_ENABLE_BEEP
GSM_PhoneBeep();
#endif
GSM_Terminate();
}
static void DisplaySMSFrame(GSM_SMSMessage *SMS)
{
GSM_Error error;
int i, length, current = 0;
unsigned char req[1000], buffer[1000], hexreq[1000];
#ifdef OSCAR
unsigned char hexmsg[1000], hexudh[1000];
#endif
error=PHONE_EncodeSMSFrame(&s,SMS,buffer,PHONE_SMSSubmit,&length,true);
if (error != ERR_NONE) {
printmsg("Error\n");
exit(-1);
}
length = length - PHONE_SMSSubmit.Text;
#ifdef OSCAR
for(i=SMS->UDH.Length;i<length;i++) {
req[i-SMS->UDH.Length]=buffer[PHONE_SMSSubmit.Text+i];
}
EncodeHexBin(hexmsg, req, length-SMS->UDH.Length);
for(i=0;i<SMS->UDH.Length;i++) {
req[i]=buffer[PHONE_SMSSubmit.Text+i];
}
EncodeHexBin(hexudh, req, SMS->UDH.Length);
printf("msg:%s nb:%i udh:%s\n",
hexmsg,
(buffer[PHONE_SMSSubmit.TPUDL]-SMS->UDH.Length)*8,
hexudh);
#else
for (i=0;i<buffer[PHONE_SMSSubmit.SMSCNumber]+1;i++) {
req[current++]=buffer[PHONE_SMSSubmit.SMSCNumber+i];
}
req[current++]=buffer[PHONE_SMSSubmit.firstbyte];
req[current++]=buffer[PHONE_SMSSubmit.TPMR];
for (i=0;i<((buffer[PHONE_SMSSubmit.Number]+1)/2+1)+1;i++) {
req[current++]=buffer[PHONE_SMSSubmit.Number+i];
}
req[current++]=buffer[PHONE_SMSSubmit.TPPID];
req[current++]=buffer[PHONE_SMSSubmit.TPDCS];
req[current++]=buffer[PHONE_SMSSubmit.TPVP];
req[current++]=buffer[PHONE_SMSSubmit.TPUDL];
for(i=0;i<length;i++) req[current++]=buffer[PHONE_SMSSubmit.Text+i];
EncodeHexBin(hexreq, req, current);
printmsg("%s\n\n",hexreq);
#endif
}
#define SEND_SAVE_SMS_BUFFER_SIZE 10000
static GSM_Error SMSStatus;
static void SendSMSStatus (char *Device, int status, int MessageReference)
{
dbgprintf("Sent SMS on device: \"%s\"\n",Device);
if (status==0) {
printmsg("..OK");
SMSStatus = ERR_NONE;
} else {
printmsg("..error %i",status);
SMSStatus = ERR_UNKNOWN;
}
printmsg(", message reference=%d\n",MessageReference);
}
static void SendSaveDisplaySMS(int argc, char *argv[])
{
#ifdef GSM_ENABLE_BACKUP
GSM_Backup Backup;
#endif
int i,j,z,FramesNum = 0;
int Protected = 0;
GSM_SMSFolders folders;
GSM_MultiSMSMessage sms;
GSM_Ringtone ringtone[MAX_MULTI_SMS];
GSM_MultiBitmap bitmap[MAX_MULTI_SMS],bitmap2;
GSM_MultiPartSMSInfo SMSInfo;
GSM_NetworkInfo NetInfo;
GSM_MMSIndicator MMSInfo;
FILE *ReplaceFile,*f;
char ReplaceBuffer2 [200],ReplaceBuffer[200];
char InputBuffer [SEND_SAVE_SMS_BUFFER_SIZE/2+1];
char Buffer [MAX_MULTI_SMS][SEND_SAVE_SMS_BUFFER_SIZE];
char Sender [(GSM_MAX_NUMBER_LENGTH+1)*2];
char Name [(GSM_MAX_NUMBER_LENGTH+1)*2];
char SMSC [(GSM_MAX_NUMBER_LENGTH+1)*2];
int startarg = 0;
int chars_read = 0;
int nextlong = 0;
bool ReplyViaSameSMSC = false;
int SMSCSet = 1;
int MaxSMS = -1;
bool EMS16Bit = false;
bool SendSaved = false;
/* Parameters required only during saving */
int Folder = 1; /*Inbox by default */
GSM_SMS_State State = SMS_Sent;
/* Required only during sending */
GSM_SMSValidity Validity;
GSM_SMSC PhoneSMSC;
bool DeliveryReport = false;
ReplaceBuffer[0] = 0;
ReplaceBuffer[1] = 0;
GSM_ClearMultiPartSMSInfo(&SMSInfo);
SMSInfo.ReplaceMessage = 0;
SMSInfo.EntriesNum = 1;
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender,"Gammu",5);
Name[0] = 0;
Name[1] = 0;
startarg = 0;
} else {
EncodeUnicode(Sender,argv[3],strlen(argv[3]));
startarg = 1;
Validity.Format = 0;
}
if (mystrncasecmp(argv[1],"--sendsmsdsms",0)) {
startarg=startarg+2;
EncodeUnicode(SMSC,"1234",4);
SMSCSet = 0;
}
if (mystrncasecmp(argv[2],"TEXT",0)) {
chars_read = fread(InputBuffer, 1, SEND_SAVE_SMS_BUFFER_SIZE/2, stdin);
if (chars_read == 0) printmsg("Warning: 0 chars read !\n");
InputBuffer[chars_read] = 0x00;
InputBuffer[chars_read+1] = 0x00;
EncodeUnicode(Buffer[0],InputBuffer,strlen(InputBuffer));
SMSInfo.Entries[0].Buffer = Buffer[0];
SMSInfo.Entries[0].ID = SMS_Text;
SMSInfo.UnicodeCoding = false;
startarg += 3;
} else if (mystrncasecmp(argv[2],"SMSTEMPLATE",0)) {
SMSInfo.UnicodeCoding = false;
SMSInfo.EntriesNum = 1;
Buffer[0][0] = 0x00;
Buffer[0][1] = 0x00;
SMSInfo.Entries[0].Buffer = Buffer[0];
SMSInfo.Entries[0].ID = SMS_AlcatelSMSTemplateName;
startarg += 3;
} else if (mystrncasecmp(argv[2],"EMS",0)) {
SMSInfo.UnicodeCoding = false;
SMSInfo.EntriesNum = 0;
startarg += 3;
} else if (mystrncasecmp(argv[2],"MMSINDICATOR",0)) {
if (argc<6+startarg) {
printmsg("Where are parameters ?\n");
exit(-1);
}
SMSInfo.Entries[0].ID = SMS_MMSIndicatorLong;
SMSInfo.Entries[0].MMSIndicator = &MMSInfo;
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender,"MMS Info",8);
}
strcpy(MMSInfo.Address, argv[3+startarg]);
strcpy(MMSInfo.Title, argv[4+startarg]);
strcpy(MMSInfo.Sender, argv[5+startarg]);
startarg += 6;
} else if (mystrncasecmp(argv[2],"WAPINDICATOR",0)) {
if (argc<5+startarg) {
printmsg("Where are parameters ?\n");
exit(-1);
}
SMSInfo.Entries[0].ID = SMS_WAPIndicatorLong;
SMSInfo.Entries[0].MMSIndicator = &MMSInfo;
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender,"WAP Info",8);
}
strcpy(MMSInfo.Address, argv[3+startarg]);
strcpy(MMSInfo.Title, argv[4+startarg]);
startarg += 5;
} else if (mystrncasecmp(argv[2],"RINGTONE",0)) {
if (argc<4+startarg) {
printmsg("Where is ringtone filename ?\n");
exit(-1);
}
ringtone[0].Format=RING_NOTETONE;
error=GSM_ReadRingtoneFile(argv[3+startarg],&ringtone[0]);
Print_Error(error);
SMSInfo.Entries[0].ID = SMS_NokiaRingtone;
SMSInfo.Entries[0].Ringtone = &ringtone[0];
if (mystrncasecmp(argv[1],"--savesms",0)) {
CopyUnicodeString(Sender, ringtone[0].Name);
EncodeUnicode(Name,"Ringtone ",9);
CopyUnicodeString(Name+9*2, ringtone[0].Name);
}
startarg += 4;
} else if (mystrncasecmp(argv[2],"OPERATOR",0)) {
if (argc<4+startarg) {
printmsg("Where is logo filename ?\n");
exit(-1);
}
bitmap[0].Bitmap[0].Type=GSM_OperatorLogo;
error=GSM_ReadBitmapFile(argv[3+startarg],&bitmap[0]);
Print_Error(error);
strcpy(bitmap[0].Bitmap[0].NetworkCode,"000 00");
SMSInfo.Entries[0].ID = SMS_NokiaOperatorLogo;
SMSInfo.Entries[0].Bitmap = &bitmap[0];
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "OpLogo",6);
EncodeUnicode(Name,"OpLogo ",7);
}
startarg += 4;
} else if (mystrncasecmp(argv[2],"CALLER",0)) {
if (argc<4+startarg) {
printmsg("Where is logo filename ?\n");
exit(-1);
}
bitmap[0].Bitmap[0].Type=GSM_CallerGroupLogo;
error=GSM_ReadBitmapFile(argv[3+startarg],&bitmap[0]);
Print_Error(error);
SMSInfo.Entries[0].ID = SMS_NokiaCallerLogo;
SMSInfo.Entries[0].Bitmap = &bitmap[0];
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "Caller",6);
}
startarg += 4;
} else if (mystrncasecmp(argv[2],"ANIMATION",0)) {
SMSInfo.UnicodeCoding = false;
SMSInfo.EntriesNum = 1;
if (argc<4+startarg) {
printmsg("Where is number of frames ?\n");
exit(-1);
}
bitmap[0].Number = 0;
i = 1;
while (1) {
bitmap2.Bitmap[0].Type=GSM_StartupLogo;
error=GSM_ReadBitmapFile(argv[3+startarg+i],&bitmap2);
Print_Error(error);
for (j=0;j<bitmap2.Number;j++) {
if (bitmap[0].Number == atoi(argv[3+startarg])) break;
memcpy(&bitmap[0].Bitmap[bitmap[0].Number],&bitmap2.Bitmap[j],sizeof(GSM_Bitmap));
bitmap[0].Number++;
}
if (bitmap[0].Number == atoi(argv[3+startarg])) break;
i++;
}
SMSInfo.Entries[0].ID = SMS_AlcatelMonoAnimationLong;
SMSInfo.Entries[0].Bitmap = &bitmap[0];
bitmap[0].Bitmap[0].Text[0] = 0;
bitmap[0].Bitmap[0].Text[1] = 0;
startarg += 4 + atoi(argv[3+startarg]);
} else if (mystrncasecmp(argv[2],"PICTURE",0)) {
if (argc<4+startarg) {
printmsg("Where is logo filename ?\n");
exit(-1);
}
bitmap[0].Bitmap[0].Type=GSM_PictureImage;
error=GSM_ReadBitmapFile(argv[3+startarg],&bitmap[0]);
printmsg("File \"%s\"\n",argv[3+startarg]);
Print_Error(error);
SMSInfo.Entries[0].ID = SMS_NokiaPictureImageLong;
SMSInfo.Entries[0].Bitmap = &bitmap[0];
SMSInfo.UnicodeCoding = false;
bitmap[0].Bitmap[0].Text[0] = 0;
bitmap[0].Bitmap[0].Text[1] = 0;
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "Picture",7);
EncodeUnicode(Name,"Picture Image",13);
}
startarg += 4;
#ifdef GSM_ENABLE_BACKUP
} else if (mystrncasecmp(argv[2],"BOOKMARK",0)) {
if (argc<5+startarg) {
printmsg("Where is backup filename and location ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[3+startarg],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
while (Backup.WAPBookmark[i]!=NULL) {
if (i == atoi(argv[4+startarg])-1) break;
i++;
}
if (i != atoi(argv[4+startarg])-1) {
printmsg("Bookmark not found in file\n");
exit(-1);
}
SMSInfo.Entries[0].ID = SMS_NokiaWAPBookmarkLong;
SMSInfo.Entries[0].Bookmark = Backup.WAPBookmark[i];
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "Bookmark",8);
EncodeUnicode(Name,"WAP Bookmark",12);
}
startarg += 5;
} else if (mystrncasecmp(argv[2],"WAPSETTINGS",0)) {
if (argc<6+startarg) {
printmsg("Where is backup filename and location ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[3+startarg],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
while (Backup.WAPSettings[i]!=NULL) {
if (i == atoi(argv[4+startarg])-1) break;
i++;
}
if (i != atoi(argv[4+startarg])-1) {
printmsg("WAP settings not found in file\n");
exit(-1);
}
SMSInfo.Entries[0].Settings = NULL;
for (j=0;j<Backup.WAPSettings[i]->Number;j++) {
switch (Backup.WAPSettings[i]->Settings[j].Bearer) {
case WAPSETTINGS_BEARER_GPRS:
if (mystrncasecmp(argv[5+startarg],"GPRS",0)) {
SMSInfo.Entries[0].Settings = &Backup.WAPSettings[i]->Settings[j];
break;
}
case WAPSETTINGS_BEARER_DATA:
if (mystrncasecmp(argv[5+startarg],"DATA",0)) {
SMSInfo.Entries[0].Settings = &Backup.WAPSettings[i]->Settings[j];
break;
}
default:
break;
}
}
if (SMSInfo.Entries[0].Settings == NULL) {
printmsg("Sorry. For now there is only support for GPRS or DATA bearers end\n");
exit(-1);
}
SMSInfo.Entries[0].ID = SMS_NokiaWAPSettingsLong;
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "Settings",8);
EncodeUnicode(Name,"WAP Settings",12);
}
startarg += 6;
} else if (mystrncasecmp(argv[2],"MMSSETTINGS",0)) {
if (argc<5+startarg) {
printmsg("Where is backup filename and location ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[3+startarg],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
while (Backup.MMSSettings[i]!=NULL) {
if (i == atoi(argv[4+startarg])-1) break;
i++;
}
if (i != atoi(argv[4+startarg])-1) {
printmsg("MMS settings not found in file\n");
exit(-1);
}
SMSInfo.Entries[0].Settings = NULL;
for (j=0;j<Backup.MMSSettings[i]->Number;j++) {
switch (Backup.MMSSettings[i]->Settings[j].Bearer) {
case WAPSETTINGS_BEARER_GPRS:
SMSInfo.Entries[0].Settings = &Backup.MMSSettings[i]->Settings[j];
break;
default:
break;
}
}
if (SMSInfo.Entries[0].Settings == NULL) {
printmsg("Sorry. No GPRS bearer found in MMS settings\n");
exit(-1);
}
SMSInfo.Entries[0].ID = SMS_NokiaMMSSettingsLong;
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "Settings",8);
EncodeUnicode(Name,"MMS Settings",12);
}
startarg += 5;
} else if (mystrncasecmp(argv[2],"CALENDAR",0)) {
if (argc<5+startarg) {
printmsg("Where is backup filename and location ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[3+startarg],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
while (Backup.Calendar[i]!=NULL) {
if (i == atoi(argv[4+startarg])-1) break;
i++;
}
if (i != atoi(argv[4+startarg])-1) {
printmsg("Calendar note not found in file\n");
exit(-1);
}
SMSInfo.Entries[0].ID = SMS_NokiaVCALENDAR10Long;
SMSInfo.Entries[0].Calendar = Backup.Calendar[i];
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "Calendar",8);
}
startarg += 5;
} else if (mystrncasecmp(argv[2],"TODO",0)) {
if (argc<5+startarg) {
printmsg("Where is backup filename and location ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[3+startarg],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
while (Backup.ToDo[i]!=NULL) {
if (i == atoi(argv[4+startarg])-1) break;
i++;
}
if (i != atoi(argv[4+startarg])-1) {
printmsg("ToDo note not found in file\n");
exit(-1);
}
SMSInfo.Entries[0].ID = SMS_NokiaVTODOLong;
SMSInfo.Entries[0].ToDo = Backup.ToDo[i];
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "ToDo",8);
}
startarg += 5;
} else if (mystrncasecmp(argv[2],"VCARD10",0) || mystrncasecmp(argv[2],"VCARD21",0)) {
if (argc<6+startarg) {
printmsg("Where is backup filename and location and memory type ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[3+startarg],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
if (mystrncasecmp(argv[4+startarg],"SM",0)) {
while (Backup.SIMPhonebook[i]!=NULL) {
if (i == atoi(argv[5+startarg])-1) break;
i++;
}
if (i != atoi(argv[5+startarg])-1) {
printmsg("Phonebook entry not found in file\n");
exit(-1);
}
SMSInfo.Entries[0].Phonebook = Backup.SIMPhonebook[i];
} else if (mystrncasecmp(argv[4+startarg],"ME",0)) {
while (Backup.PhonePhonebook[i]!=NULL) {
if (i == atoi(argv[5+startarg])-1) break;
i++;
}
if (i != atoi(argv[5+startarg])-1) {
printmsg("Phonebook entry not found in file\n");
exit(-1);
}
SMSInfo.Entries[0].Phonebook = Backup.PhonePhonebook[i];
} else {
printmsg("Unknown memory type: \"%s\"\n",argv[4+startarg]);
exit(-1);
}
if (mystrncasecmp(argv[2],"VCARD10",0)) {
SMSInfo.Entries[0].ID = SMS_VCARD10Long;
} else {
SMSInfo.Entries[0].ID = SMS_VCARD21Long;
}
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "VCARD",5);
EncodeUnicode(Name, "Phonebook entry",15);
}
startarg += 6;
#endif
} else if (mystrncasecmp(argv[2],"PROFILE",0)) {
SMSInfo.Entries[0].ID = SMS_NokiaProfileLong;
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "Profile",7);
}
startarg += 3;
} else {
printmsg("What format of sms (\"%s\") ?\n",argv[2]);
exit(-1);
}
for (i=startarg;i<argc;i++) {
switch (nextlong) {
case 0:
if (mystrncasecmp(argv[1],"--savesms",0) || SendSaved) {
if (mystrncasecmp(argv[i],"-folder",0)) {
nextlong=1;
continue;
}
}
if (mystrncasecmp(argv[1],"--savesms",0)) {
if (mystrncasecmp(argv[i],"-unread",0)) {
State = SMS_UnRead;
continue;
}
if (mystrncasecmp(argv[i],"-read",0)) {
State = SMS_Read;
continue;
}
if (mystrncasecmp(argv[i],"-unsent",0)) {
State = SMS_UnSent;
continue;
}
if (mystrncasecmp(argv[i],"-sent",0)) {
State = SMS_Sent;
continue;
}
if (mystrncasecmp(argv[i],"-sender",0)) {
nextlong=2;
continue;
}
} else {
if (mystrncasecmp(argv[i],"-save",0)) {
SendSaved=true;
continue;
}
if (mystrncasecmp(argv[i],"-report",0)) {
DeliveryReport=true;
continue;
}
if (mystrncasecmp(argv[i],"-validity",0)) {
nextlong=10;
continue;
}
}
if (mystrncasecmp(argv[i],"-smscset",0)) {
nextlong=3;
continue;
}
if (mystrncasecmp(argv[i],"-smscnumber",0)) {
nextlong=4;
continue;
}
if (mystrncasecmp(argv[i],"-protected",0)) {
nextlong=19;
continue;
}
if (mystrncasecmp(argv[i],"-reply",0)) {
ReplyViaSameSMSC=true;
continue;
}
if (mystrncasecmp(argv[i],"-maxsms",0)) {
nextlong=21;
continue;
}
if (mystrncasecmp(argv[2],"RINGTONE",0)) {
if (mystrncasecmp(argv[i],"-long",0)) {
SMSInfo.Entries[0].ID = SMS_NokiaRingtoneLong;
break;
}
if (mystrncasecmp(argv[i],"-scale",0)) {
ringtone[0].NoteTone.AllNotesScale=true;
break;
}
}
if (mystrncasecmp(argv[2],"TEXT",0)) {
if (mystrncasecmp(argv[i],"-inputunicode",0)) {
ReadUnicodeFile(Buffer[0],InputBuffer);
break;
}
if (mystrncasecmp(argv[i],"-16bit",0)) {
if (SMSInfo.Entries[0].ID == SMS_ConcatenatedTextLong) SMSInfo.Entries[0].ID = SMS_ConcatenatedTextLong16bit;
if (SMSInfo.Entries[0].ID == SMS_ConcatenatedAutoTextLong) SMSInfo.Entries[0].ID = SMS_ConcatenatedAutoTextLong16bit;
break;
}
if (mystrncasecmp(argv[i],"-flash",0)) {
SMSInfo.Class = 0;
break;
}
if (mystrncasecmp(argv[i],"-len",0)) {
nextlong = 5;
break;
}
if (mystrncasecmp(argv[i],"-autolen",0)) {
nextlong = 5;
break;
}
if (mystrncasecmp(argv[i],"-unicode",0)) {
SMSInfo.UnicodeCoding = true;
break;
}
if (mystrncasecmp(argv[i],"-enablevoice",0)) {
SMSInfo.Entries[0].ID = SMS_EnableVoice;
break;
}
if (mystrncasecmp(argv[i],"-disablevoice",0)) {
SMSInfo.Entries[0].ID = SMS_DisableVoice;
break;
}
if (mystrncasecmp(argv[i],"-enablefax",0)) {
SMSInfo.Entries[0].ID = SMS_EnableFax;
break;
}
if (mystrncasecmp(argv[i],"-disablefax",0)) {
SMSInfo.Entries[0].ID = SMS_DisableFax;
break;
}
if (mystrncasecmp(argv[i],"-enableemail",0)) {
SMSInfo.Entries[0].ID = SMS_EnableEmail;
break;
}
if (mystrncasecmp(argv[i],"-disableemail",0)) {
SMSInfo.Entries[0].ID = SMS_DisableEmail;
break;
}
if (mystrncasecmp(argv[i],"-voidsms",0)) {
SMSInfo.Entries[0].ID = SMS_VoidSMS;
break;
}
if (mystrncasecmp(argv[i],"-replacemessages",0) &&
SMSInfo.Entries[0].ID != SMS_ConcatenatedTextLong) {
nextlong = 8;
break;
}
if (mystrncasecmp(argv[i],"-replacefile",0)) {
nextlong = 9;
continue;
}
}
if (mystrncasecmp(argv[2],"PICTURE",0)) {
if (mystrncasecmp(argv[i],"-text",0)) {
nextlong = 6;
break;
}
if (mystrncasecmp(argv[i],"-unicode",0)) {
SMSInfo.UnicodeCoding = true;
break;
}
if (mystrncasecmp(argv[i],"-alcatelbmmi",0)) {
bitmap[0].Bitmap[0].Type=GSM_StartupLogo;
error=GSM_ReadBitmapFile(argv[startarg-1],&bitmap[0]);
Print_Error(error);
SMSInfo.UnicodeCoding = true;
SMSInfo.Entries[0].ID = SMS_AlcatelMonoBitmapLong;
break;
}
break;
}
if (mystrncasecmp(argv[2],"VCARD10",0)) {
if (mystrncasecmp(argv[i],"-nokia",0)) {
SMSInfo.Entries[0].ID = SMS_NokiaVCARD10Long;
break;
}
break;
}
if (mystrncasecmp(argv[2],"VCARD21",0)) {
if (mystrncasecmp(argv[i],"-nokia",0)) {
SMSInfo.Entries[0].ID = SMS_NokiaVCARD21Long;
break;
}
break;
}
if (mystrncasecmp(argv[2],"PROFILE",0)) {
if (mystrncasecmp(argv[i],"-name",0)) {
nextlong = 22;
break;
}
if (mystrncasecmp(argv[i],"-ringtone",0)) {
nextlong = 23;
break;
}
if (mystrncasecmp(argv[i],"-bitmap",0)) {
nextlong = 24;
break;
}
}
if (mystrncasecmp(argv[2],"SMSTEMPLATE",0)) {
if (mystrncasecmp(argv[i],"-unicode",0)) {
SMSInfo.UnicodeCoding = true;
break;
}
if (mystrncasecmp(argv[i],"-text",0)) {
nextlong = 11;
break;
}
if (mystrncasecmp(argv[i],"-unicodefiletext",0)) {
nextlong = 18;
break;
}
if (mystrncasecmp(argv[i],"-defsound",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSPredefinedSound;
nextlong = 12;
break;
}
if (mystrncasecmp(argv[i],"-defanimation",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSPredefinedAnimation;
nextlong = 12;
break;
}
if (mystrncasecmp(argv[i],"-tone10",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSound10;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-tone10long",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSound10Long;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-tone12",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSound12;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-tone12long",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSound12Long;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-toneSE",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSonyEricssonSound;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-toneSElong",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSonyEricssonSoundLong;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-variablebitmap",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSVariableBitmap;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 15;
break;
}
if (mystrncasecmp(argv[i],"-variablebitmaplong",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSVariableBitmapLong;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 15;
break;
}
if (mystrncasecmp(argv[i],"-animation",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSAnimation;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
bitmap[SMSInfo.EntriesNum].Number = 0;
nextlong = 16;
break;
}
}
if (mystrncasecmp(argv[2],"EMS",0)) {
if (mystrncasecmp(argv[i],"-unicode",0)) {
SMSInfo.UnicodeCoding = true;
break;
}
if (mystrncasecmp(argv[i],"-16bit",0)) {
EMS16Bit = true;
break;
}
if (mystrncasecmp(argv[i],"-format",0)) {
nextlong = 20;
break;
}
if (mystrncasecmp(argv[i],"-text",0)) {
nextlong = 11;
break;
}
if (mystrncasecmp(argv[i],"-unicodefiletext",0)) {
nextlong = 18;
break;
}
if (mystrncasecmp(argv[i],"-defsound",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSPredefinedSound;
nextlong = 12;
break;
}
if (mystrncasecmp(argv[i],"-defanimation",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSPredefinedAnimation;
nextlong = 12;
break;
}
if (mystrncasecmp(argv[i],"-tone10",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSound10;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-tone10long",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSound10Long;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-tone12",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSound12;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-tone12long",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSound12Long;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-toneSE",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSonyEricssonSound;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-toneSElong",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSSonyEricssonSoundLong;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 14;
break;
}
if (mystrncasecmp(argv[i],"-fixedbitmap",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSFixedBitmap;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 15;
break;
}
if (mystrncasecmp(argv[i],"-variablebitmap",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSVariableBitmap;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 15;
break;
}
if (mystrncasecmp(argv[i],"-variablebitmaplong",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSVariableBitmapLong;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
nextlong = 15;
break;
}
if (mystrncasecmp(argv[i],"-animation",0)) {
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_EMSAnimation;
if (Protected != 0) {
SMSInfo.Entries[SMSInfo.EntriesNum].Protected = true;
Protected --;
}
bitmap[SMSInfo.EntriesNum].Number = 0;
nextlong = 16;
break;
}
}
if (mystrncasecmp(argv[2],"OPERATOR",0)) {
if (mystrncasecmp(argv[i],"-netcode",0)) {
nextlong = 7;
break;
}
if (mystrncasecmp(argv[i],"-biglogo",0)) {
SMSInfo.Entries[0].ID = SMS_NokiaOperatorLogoLong;
break;
}
break;
}
printmsg("Unknown parameter (\"%s\")\n",argv[i]);
exit(-1);
break;
case 1: /* SMS folder - only during saving SMS */
Folder = atoi(argv[i]);
nextlong = 0;
break;
case 2: /* Sender number - only during saving SMS */
EncodeUnicode(Sender,argv[i],strlen(argv[i]));
nextlong = 0;
break;
case 3: /* SMSC set number */
SMSCSet = atoi(argv[i]);
nextlong = 0;
break;
case 4: /* Number of SMSC */
EncodeUnicode(SMSC,argv[i],strlen(argv[i]));
SMSCSet = 0;
nextlong = 0;
break;
case 5: /* Length of text SMS */
if (atoi(argv[i])<chars_read)
{
Buffer[0][atoi(argv[i])*2] = 0x00;
Buffer[0][atoi(argv[i])*2+1] = 0x00;
}
SMSInfo.Entries[0].ID = SMS_ConcatenatedTextLong;
if (mystrncasecmp(argv[i-1],"-autolen",0)) SMSInfo.Entries[0].ID = SMS_ConcatenatedAutoTextLong;
nextlong = 0;
break;
case 6: /* Picture Images - text */
EncodeUnicode(bitmap[0].Bitmap[0].Text,argv[i],strlen(argv[i]));
nextlong = 0;
break;
case 7: /* Operator Logo - network code */
strncpy(bitmap[0].Bitmap[0].NetworkCode,argv[i],7);
if (!strcmp(DecodeUnicodeConsole(GSM_GetNetworkName(bitmap[0].Bitmap[0].NetworkCode)),"unknown")) {
printmsg("Unknown GSM network code (\"%s\")\n",argv[i]);
exit(-1);
}
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "OpLogo",6);
EncodeUnicode(Sender+6*2,bitmap[0].Bitmap[0].NetworkCode,3);
EncodeUnicode(Sender+6*2+3*2,bitmap[0].Bitmap[0].NetworkCode+4,2);
if (UnicodeLength(GSM_GetNetworkName(bitmap[0].Bitmap[0].NetworkCode))<GSM_MAX_SMS_NAME_LENGTH-7) {
EncodeUnicode(Name,"OpLogo ",7);
CopyUnicodeString(Name+7*2,GSM_GetNetworkName(bitmap[0].Bitmap[0].NetworkCode));
} else {
CopyUnicodeString(Name,Sender);
}
}
nextlong = 0;
break;
case 8:/* Reject duplicates ID */
SMSInfo.ReplaceMessage = atoi(argv[i]);
if (SMSInfo.ReplaceMessage < 1 || SMSInfo.ReplaceMessage > 7) {
printmsg("You have to give number between 1 and 7 (\"%s\")\n",argv[i]);
exit(-1);
}
nextlong = 0;
break;
case 9:/* Replace file for text SMS */
ReplaceFile = fopen(argv[i], "rb");
if (ReplaceFile == NULL) Print_Error(ERR_CANTOPENFILE);
memset(ReplaceBuffer,0,sizeof(ReplaceBuffer));
fread(ReplaceBuffer,1,sizeof(ReplaceBuffer),ReplaceFile);
fclose(ReplaceFile);
ReadUnicodeFile(ReplaceBuffer2,ReplaceBuffer);
for(j=0;j<(int)(UnicodeLength(Buffer[0]));j++) {
for (z=0;z<(int)(UnicodeLength(ReplaceBuffer2)/2);z++) {
if (ReplaceBuffer2[z*4] == Buffer[0][j] &&
ReplaceBuffer2[z*4+1] == Buffer[0][j+1]) {
Buffer[0][j] = ReplaceBuffer2[z*4+2];
Buffer[0][j+1] = ReplaceBuffer2[z*4+3];
break;
}
}
}
nextlong = 0;
break;
case 10:
Validity.Format = SMS_Validity_RelativeFormat;
if (mystrncasecmp(argv[i],"HOUR",0)) Validity.Relative = SMS_VALID_1_Hour;
else if (mystrncasecmp(argv[i],"6HOURS",0)) Validity.Relative = SMS_VALID_6_Hours;
else if (mystrncasecmp(argv[i],"DAY",0)) Validity.Relative = SMS_VALID_1_Day;
else if (mystrncasecmp(argv[i],"3DAYS",0)) Validity.Relative = SMS_VALID_3_Days;
else if (mystrncasecmp(argv[i],"WEEK",0)) Validity.Relative = SMS_VALID_1_Week;
else if (mystrncasecmp(argv[i],"MAX",0)) Validity.Relative = SMS_VALID_Max_Time;
else {
printmsg("Unknown validity string (\"%s\")\n",argv[i]);
exit(-1);
}
nextlong = 0;
break;
case 11:/* EMS text from parameter */
EncodeUnicode(Buffer[SMSInfo.EntriesNum],argv[i],strlen(argv[i]));
dbgprintf("buffer is \"%s\"\n",DecodeUnicodeConsole(Buffer[SMSInfo.EntriesNum]));
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_ConcatenatedTextLong;
SMSInfo.Entries[SMSInfo.EntriesNum].Buffer = Buffer[SMSInfo.EntriesNum];
SMSInfo.EntriesNum++;
nextlong = 0;
break;
case 12:/* EMS predefined sound/animation number */
SMSInfo.Entries[SMSInfo.EntriesNum].Number = atoi(argv[i]);
SMSInfo.EntriesNum++;
nextlong = 0;
break;
case 14: /* EMS ringtone - IMelody */
ringtone[SMSInfo.EntriesNum].Format=RING_NOTETONE;
error=GSM_ReadRingtoneFile(argv[i],&ringtone[SMSInfo.EntriesNum]);
Print_Error(error);
SMSInfo.Entries[SMSInfo.EntriesNum].Ringtone = &ringtone[SMSInfo.EntriesNum];
SMSInfo.EntriesNum++;
nextlong = 0;
break;
case 15:/* EMS bitmap file */
bitmap[SMSInfo.EntriesNum].Bitmap[0].Type=GSM_StartupLogo;
error=GSM_ReadBitmapFile(argv[i],&bitmap[SMSInfo.EntriesNum]);
Print_Error(error);
SMSInfo.Entries[SMSInfo.EntriesNum].Bitmap = &bitmap[SMSInfo.EntriesNum];
SMSInfo.EntriesNum++;
nextlong = 0;
break;
case 16:/* Number of frames for EMS animation */
FramesNum = atoi(argv[i]);
if (FramesNum < 1 || FramesNum > 4) {
printmsg("You have to give number of EMS frames between 1 and 4 (\"%s\")\n",argv[i]);
exit(-1);
}
bitmap[SMSInfo.EntriesNum].Number = 0;
nextlong = 17;
break;
case 17:/*File for EMS animation */
bitmap2.Bitmap[0].Type=GSM_StartupLogo;
error=GSM_ReadBitmapFile(argv[i],&bitmap2);
for (j=0;j<bitmap2.Number;j++) {
if (bitmap[SMSInfo.EntriesNum].Number == FramesNum) break;
memcpy(&bitmap[SMSInfo.EntriesNum].Bitmap[bitmap[SMSInfo.EntriesNum].Number],&bitmap2.Bitmap[j],sizeof(GSM_Bitmap));
bitmap[SMSInfo.EntriesNum].Number++;
}
if (bitmap[SMSInfo.EntriesNum].Number == FramesNum) {
SMSInfo.Entries[SMSInfo.EntriesNum].Bitmap = &bitmap[SMSInfo.EntriesNum];
SMSInfo.EntriesNum++;
nextlong = 0;
}
break;
case 18:/* EMS text from Unicode file */
f = fopen(argv[i],"rb");
if (f == NULL) {
printmsg("Can't open file \"%s\"\n",argv[i]);
exit(-1);
}
z=fread(InputBuffer,1,2000,f);
InputBuffer[z] = 0;
InputBuffer[z+1] = 0;
fclose(f);
ReadUnicodeFile(Buffer[SMSInfo.EntriesNum],InputBuffer);
dbgprintf("buffer is \"%s\"\n",DecodeUnicodeConsole(Buffer[SMSInfo.EntriesNum]));
SMSInfo.Entries[SMSInfo.EntriesNum].ID = SMS_ConcatenatedTextLong;
SMSInfo.Entries[SMSInfo.EntriesNum].Buffer = Buffer[SMSInfo.EntriesNum];
SMSInfo.EntriesNum++;
nextlong = 0;
break;
case 19:/* Number of protected items */
Protected = atoi(argv[i]);
nextlong = 0;
break;
case 20:/* Formatting text for EMS */
if (SMSInfo.Entries[SMSInfo.EntriesNum-1].ID == SMS_ConcatenatedTextLong) {
for(j=0;j<(int)strlen(argv[i]);j++) {
switch(argv[i][j]) {
case 'l': case 'L':
SMSInfo.Entries[SMSInfo.EntriesNum-1].Left = true;
break;
case 'c': case 'C':
SMSInfo.Entries[SMSInfo.EntriesNum-1].Center = true;
break;
case 'r': case 'R':
SMSInfo.Entries[SMSInfo.EntriesNum-1].Right = true;
break;
case 'a': case 'A':
SMSInfo.Entries[SMSInfo.EntriesNum-1].Large = true;
break;
case 's': case 'S':
SMSInfo.Entries[SMSInfo.EntriesNum-1].Small = true;
break;
case 'b': case 'B':
SMSInfo.Entries[SMSInfo.EntriesNum-1].Bold = true;
break;
case 'i': case 'I':
SMSInfo.Entries[SMSInfo.EntriesNum-1].Italic = true;
break;
case 'u': case 'U':
SMSInfo.Entries[SMSInfo.EntriesNum-1].Underlined = true;
break;
case 't': case 'T':
SMSInfo.Entries[SMSInfo.EntriesNum-1].Strikethrough = true;
break;
default:
printmsg("Unknown parameter \"%c\"\n",argv[i][j]);
exit(-1);
}
}
} else {
printmsg("Last parameter wasn't text\n");
exit(-1);
}
nextlong = 0;
break;
case 21:/*MaxSMS*/
MaxSMS = atoi(argv[i]);
nextlong = 0;
break;
case 22:/* profile name */
EncodeUnicode(Buffer[0],argv[i],strlen(argv[i]));
SMSInfo.Entries[0].Buffer = Buffer[0];
nextlong = 0;
break;
case 23:/* profile ringtone */
ringtone[0].Format = RING_NOTETONE;
error=GSM_ReadRingtoneFile(argv[i],&ringtone[0]);
Print_Error(error);
SMSInfo.Entries[0].Ringtone = &ringtone[0];
nextlong = 0;
break;
case 24:/* profile bitmap */
bitmap[0].Bitmap[0].Type = GSM_PictureImage;
error=GSM_ReadBitmapFile(argv[i],&bitmap[0]);
Print_Error(error);
bitmap[0].Bitmap[0].Text[0] = 0;
bitmap[0].Bitmap[0].Text[1] = 0;
SMSInfo.Entries[0].Bitmap = &bitmap[0];
nextlong = 0;
break;
}
}
if (nextlong!=0) {
printmsg("Parameter missed...\n");
exit(-1);
}
if (mystrncasecmp(argv[2],"EMS",0) && EMS16Bit) {
for (i=0;i<SMSInfo.EntriesNum;i++) {
switch (SMSInfo.Entries[i].ID) {
case SMS_ConcatenatedTextLong:
SMSInfo.Entries[i].ID = SMS_ConcatenatedTextLong16bit;
default:
break;
}
}
}
if (mystrncasecmp(argv[2],"TEXT",0)) {
chars_read = UnicodeLength(Buffer[0]);
if (chars_read != 0) {
/* Trim \n at the end of string */
if (Buffer[0][chars_read*2-1] == '\n' && Buffer[0][chars_read*2-2] == 0)
{
Buffer[0][chars_read*2-1] = 0;
}
}
}
if (mystrncasecmp(argv[1],"--displaysms",0) || mystrncasecmp(argv[1],"--sendsmsdsms",0)) {
if (mystrncasecmp(argv[2],"OPERATOR",0)) {
if (bitmap[0].Bitmap[0].Type==GSM_OperatorLogo && strcmp(bitmap[0].Bitmap[0].NetworkCode,"000 00")==0) {
printmsg("No network code\n");
exit(-1);
}
}
} else {
GSM_Init(true);
if (mystrncasecmp(argv[2],"OPERATOR",0)) {
if (bitmap[0].Bitmap[0].Type==GSM_OperatorLogo && strcmp(bitmap[0].Bitmap[0].NetworkCode,"000 00")==0) {
error=Phone->GetNetworkInfo(&s,&NetInfo);
Print_Error(error);
strcpy(bitmap[0].Bitmap[0].NetworkCode,NetInfo.NetworkCode);
if (mystrncasecmp(argv[1],"--savesms",0)) {
EncodeUnicode(Sender, "OpLogo",6);
EncodeUnicode(Sender+6*2,bitmap[0].Bitmap[0].NetworkCode,3);
EncodeUnicode(Sender+6*2+3*2,bitmap[0].Bitmap[0].NetworkCode+4,2);
if (UnicodeLength(GSM_GetNetworkName(bitmap[0].Bitmap[0].NetworkCode))<GSM_MAX_SMS_NAME_LENGTH-7) {
EncodeUnicode(Name,"OpLogo ",7);
CopyUnicodeString(Name+7*2,GSM_GetNetworkName(bitmap[0].Bitmap[0].NetworkCode));
} else {
CopyUnicodeString(Name,Sender);
}
}
}
}
}
error=GSM_EncodeMultiPartSMS(&SMSInfo,&sms);
Print_Error(error);
for (i=0;i<SMSInfo.EntriesNum;i++) {
switch (SMSInfo.Entries[i].ID) {
case SMS_NokiaRingtone:
case SMS_NokiaRingtoneLong:
case SMS_NokiaProfileLong:
case SMS_EMSSound10:
case SMS_EMSSound12:
case SMS_EMSSonyEricssonSound:
case SMS_EMSSound10Long:
case SMS_EMSSound12Long:
case SMS_EMSSonyEricssonSoundLong:
if (SMSInfo.Entries[i].RingtoneNotes!=SMSInfo.Entries[i].Ringtone->NoteTone.NrCommands) {
printmsg("Warning: ringtone too long. %i percent part cut\n",
(SMSInfo.Entries[i].Ringtone->NoteTone.NrCommands-SMSInfo.Entries[i].RingtoneNotes)*100/SMSInfo.Entries[i].Ringtone->NoteTone.NrCommands);
}
default:
break;
}
}
if (MaxSMS != -1 && sms.Number > MaxSMS) {
printmsg("There is %i SMS packed and %i limit. Exiting\n",sms.Number,MaxSMS);
if (!mystrncasecmp(argv[1],"--displaysms",0) && !mystrncasecmp(argv[1],"--sendsmsdsms",0)) GSM_Terminate();
exit(-1);
}
if (mystrncasecmp(argv[1],"--displaysms",0)) {
if (SMSCSet != 0) {
printmsg("Use -smscnumber option to give SMSC number\n");
exit(-1);
}
for (i=0;i<sms.Number;i++) {
sms.SMS[i].Location = 0;
sms.SMS[i].ReplyViaSameSMSC = ReplyViaSameSMSC;
sms.SMS[i].SMSC.Location = 0;
sms.SMS[i].PDU = SMS_Submit;
if (DeliveryReport) sms.SMS[i].PDU = SMS_Status_Report;
CopyUnicodeString(sms.SMS[i].Number, Sender);
CopyUnicodeString(sms.SMS[i].SMSC.Number, SMSC);
if (Validity.Format != 0) memcpy(&sms.SMS[i].SMSC.Validity,&Validity,sizeof(GSM_SMSValidity));
DisplaySMSFrame(&sms.SMS[i]);
}
printmsg("\nNumber of SMS: %i\n",sms.Number);
exit(sms.Number);
}
if (mystrncasecmp(argv[1],"--sendsmsdsms",0)) {
if (SMSCSet != 0) {
printmsg("Use -smscnumber option to give SMSC number\n");
exit(-1);
}
for (i=0;i<sms.Number;i++) {
sms.SMS[i].Location = 0;
sms.SMS[i].ReplyViaSameSMSC = ReplyViaSameSMSC;
sms.SMS[i].SMSC.Location = 0;
sms.SMS[i].PDU = SMS_Submit;
if (DeliveryReport) sms.SMS[i].PDU = SMS_Status_Report;
CopyUnicodeString(sms.SMS[i].Number, Sender);
CopyUnicodeString(sms.SMS[i].SMSC.Number, SMSC);
if (Validity.Format != 0) memcpy(&sms.SMS[i].SMSC.Validity,&Validity,sizeof(GSM_SMSValidity));
}
SMSDaemonSendSMS(argv[4],argv[5],&sms);
exit(0);
}
if (mystrncasecmp(argv[1],"--savesms",0) || SendSaved) {
error=Phone->GetSMSFolders(&s, &folders);
Print_Error(error);
if (SendSaved) {
if (Validity.Format != 0 && SMSCSet != 0) {
PhoneSMSC.Location = SMSCSet;
error=Phone->GetSMSC(&s,&PhoneSMSC);
Print_Error(error);
CopyUnicodeString(SMSC,PhoneSMSC.Number);
SMSCSet = 0;
}
s.User.SendSMSStatus = SendSMSStatus;
signal(SIGINT, interrupt);
printmsgerr("If you want break, press Ctrl+C...\n");
}
for (i=0;i<sms.Number;i++) {
printmsg("Saving SMS %i/%i\n",i+1,sms.Number);
// sms.SMS[i].Location = 0;
sms.SMS[i].Folder = Folder;
sms.SMS[i].State = State;
sms.SMS[i].ReplyViaSameSMSC = ReplyViaSameSMSC;
sms.SMS[i].SMSC.Location = SMSCSet;
if (SendSaved) {
sms.SMS[i].PDU = SMS_Submit;
if (DeliveryReport) sms.SMS[i].PDU = SMS_Status_Report;
if (Validity.Format != 0) sms.SMS[i].SMSC.Validity = Validity;
} else {
sms.SMS[i].PDU = SMS_Deliver;
}
CopyUnicodeString(sms.SMS[i].Number, Sender);
CopyUnicodeString(sms.SMS[i].Name, Name);
if (SMSCSet==0) CopyUnicodeString(sms.SMS[i].SMSC.Number, SMSC);
error=Phone->AddSMS(&s, &sms.SMS[i]);
Print_Error(error);
printmsg("Saved in folder \"%s\", location %i\n",
DecodeUnicodeConsole(folders.Folder[sms.SMS[i].Folder-1].Name),sms.SMS[i].Location);
if (SendSaved) {
printmsg("Sending sms from folder \"%s\", location %i\n",
DecodeUnicodeString(folders.Folder[sms.SMS[i].Folder-1].Name),sms.SMS[i].Location);
SMSStatus = ERR_TIMEOUT;
error=Phone->SendSavedSMS(&s, 0, sms.SMS[i].Location);
Print_Error(error);
printmsg("....waiting for network answer");
while (!gshutdown) {
GSM_ReadDevice(&s,true);
if (SMSStatus == ERR_UNKNOWN) {
GSM_Terminate();
exit(-1);
}
if (SMSStatus == ERR_NONE) break;
}
}
}
} else {
if (Validity.Format != 0 && SMSCSet != 0) {
PhoneSMSC.Location = SMSCSet;
error=Phone->GetSMSC(&s,&PhoneSMSC);
Print_Error(error);
CopyUnicodeString(SMSC,PhoneSMSC.Number);
SMSCSet = 0;
}
signal(SIGINT, interrupt);
printmsgerr("If you want break, press Ctrl+C...\n");
s.User.SendSMSStatus = SendSMSStatus;
for (i=0;i<sms.Number;i++) {
printmsg("Sending SMS %i/%i",i+1,sms.Number);
sms.SMS[i].Location = 0;
sms.SMS[i].ReplyViaSameSMSC = ReplyViaSameSMSC;
sms.SMS[i].SMSC.Location = SMSCSet;
sms.SMS[i].PDU = SMS_Submit;
if (DeliveryReport) sms.SMS[i].PDU = SMS_Status_Report;
CopyUnicodeString(sms.SMS[i].Number, Sender);
if (SMSCSet==0) CopyUnicodeString(sms.SMS[i].SMSC.Number, SMSC);
if (Validity.Format != 0) memcpy(&sms.SMS[i].SMSC.Validity,&Validity,sizeof(GSM_SMSValidity));
SMSStatus = ERR_TIMEOUT;
error=Phone->SendSMS(&s, &sms.SMS[i]);
Print_Error(error);
printmsg("....waiting for network answer");
while (!gshutdown) {
GSM_ReadDevice(&s,true);
if (SMSStatus == ERR_UNKNOWN) {
GSM_Terminate();
exit(-1);
}
if (SMSStatus == ERR_NONE) break;
}
}
}
GSM_Terminate();
}
#ifdef GSM_ENABLE_BACKUP
static void SaveFile(int argc, char *argv[])
{
GSM_Backup Backup;
int i,j;
FILE *file;
unsigned char Buffer[10000];
GSM_MemoryEntry *pbk;
if (mystrncasecmp(argv[2],"CALENDAR",0)) {
if (argc<5) {
printmsg("Where is backup filename and location ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[4],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
while (Backup.Calendar[i]!=NULL) {
if (i == atoi(argv[5])-1) break;
i++;
}
if (i != atoi(argv[5])-1) {
printmsg("Calendar note not found in file\n");
exit(-1);
}
j = 0;
GSM_EncodeVCALENDAR(Buffer, &j, Backup.Calendar[i],true,Nokia_VCalendar);
} else if (mystrncasecmp(argv[2],"BOOKMARK",0)) {
if (argc<5) {
printmsg("Where is backup filename and location ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[4],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
while (Backup.WAPBookmark[i]!=NULL) {
if (i == atoi(argv[5])-1) break;
i++;
}
if (i != atoi(argv[5])-1) {
printmsg("WAP bookmark not found in file\n");
exit(-1);
}
j = 0;
GSM_EncodeURLFile(Buffer, &j, Backup.WAPBookmark[i]);
} else if (mystrncasecmp(argv[2],"NOTE",0)) {
if (argc<5) {
printmsg("Where is backup filename and location ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[4],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
while (Backup.Note[i]!=NULL) {
if (i == atoi(argv[5])-1) break;
i++;
}
if (i != atoi(argv[5])-1) {
printmsg("Note not found in file\n");
exit(-1);
}
j = 0;
GSM_EncodeVNTFile(Buffer, &j, Backup.Note[i]);
} else if (mystrncasecmp(argv[2],"TODO",0)) {
if (argc<5) {
printmsg("Where is backup filename and location ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[4],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
while (Backup.ToDo[i]!=NULL) {
if (i == atoi(argv[5])-1) break;
i++;
}
if (i != atoi(argv[5])-1) {
printmsg("ToDo note not found in file\n");
exit(-1);
}
j = 0;
GSM_EncodeVTODO(Buffer, &j, Backup.ToDo[i], true, Nokia_VToDo);
} else if (mystrncasecmp(argv[2],"VCARD10",0) || mystrncasecmp(argv[2],"VCARD21",0)) {
if (argc<6) {
printmsg("Where is backup filename and location and memory type ?\n");
exit(-1);
}
error=GSM_ReadBackupFile(argv[4],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
i = 0;
if (mystrncasecmp(argv[5],"SM",0)) {
while (Backup.SIMPhonebook[i]!=NULL) {
if (i == atoi(argv[6])-1) break;
i++;
}
if (i != atoi(argv[6])-1) {
printmsg("Phonebook entry not found in file\n");
exit(-1);
}
pbk = Backup.SIMPhonebook[i];
} else if (mystrncasecmp(argv[5],"ME",0)) {
while (Backup.PhonePhonebook[i]!=NULL) {
if (i == atoi(argv[6])-1) break;
i++;
}
if (i != atoi(argv[6])-1) {
printmsg("Phonebook entry not found in file\n");
exit(-1);
}
pbk = Backup.PhonePhonebook[i];
} else {
printmsg("Unknown memory type: \"%s\"\n",argv[5]);
exit(-1);
}
j = 0;
if (mystrncasecmp(argv[2],"VCARD10",0)) {
GSM_EncodeVCARD(Buffer,&j,pbk,true,Nokia_VCard10);
} else {
GSM_EncodeVCARD(Buffer,&j,pbk,true,Nokia_VCard21);
}
} else {
printmsg("What format of file (\"%s\") ?\n",argv[2]);
exit(-1);
}
file = fopen(argv[3],"wb");
fwrite(Buffer,1,j,file);
fclose(file);
}
static void Backup(int argc, char *argv[])
{
int i, used;
GSM_MemoryStatus MemStatus;
GSM_ToDoEntry ToDo;
GSM_ToDoStatus ToDoStatus;
GSM_MemoryEntry Pbk;
GSM_CalendarEntry Calendar;
GSM_Bitmap Bitmap;
GSM_WAPBookmark Bookmark;
GSM_Profile Profile;
GSM_MultiWAPSettings Settings;
GSM_SyncMLSettings SyncML;
GSM_ChatSettings Chat;
GSM_Ringtone Ringtone;
GSM_SMSC SMSC;
GSM_Backup Backup;
GSM_NoteEntry Note;
GSM_Backup_Info Info;
GSM_FMStation FMStation;
GSM_GPRSAccessPoint GPRSPoint;
bool DoBackup;
if (argc == 4 && mystrncasecmp(argv[3],"-yes",0)) always_answer_yes = true;
GSM_ClearBackup(&Backup);
GSM_GetBackupFormatFeatures(argv[2],&Info);
sprintf(Backup.Creator,"Gammu %s",VERSION);
if (strlen(GetOS()) != 0) {
strcat(Backup.Creator+strlen(Backup.Creator),", ");
strcat(Backup.Creator+strlen(Backup.Creator),GetOS());
}
if (strlen(GetCompiler()) != 0) {
strcat(Backup.Creator+strlen(Backup.Creator),", ");
strcat(Backup.Creator+strlen(Backup.Creator),GetCompiler());
}
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
GSM_Init(true);
if (Info.UseUnicode) {
Info.UseUnicode=answer_yes("Use Unicode subformat of backup file");
}
if (Info.DateTime) {
GSM_GetCurrentDateTime (&Backup.DateTime);
Backup.DateTimeAvailable=true;
}
if (Info.Model) {
error=Phone->GetManufacturer(&s);
Print_Error(error);
sprintf(Backup.Model,"%s ",s.Phone.Data.Manufacturer);
if (s.Phone.Data.ModelInfo->model[0]!=0) {
strcat(Backup.Model,s.Phone.Data.ModelInfo->model);
} else {
strcat(Backup.Model,s.Phone.Data.Model);
}
strcat(Backup.Model," ");
strcat(Backup.Model,s.Phone.Data.Version);
}
if (Info.IMEI) {
error=Phone->GetIMEI(&s);
if (error != ERR_NOTSUPPORTED) {
strcpy(Backup.IMEI, s.Phone.Data.IMEI);
Print_Error(error);
} else {
Backup.IMEI[0] = 0;
}
}
printf("\n");
DoBackup = false;
if (Info.PhonePhonebook) {
printmsg("Checking phone phonebook\n");
MemStatus.MemoryType = MEM_ME;
error=Phone->GetMemoryStatus(&s, &MemStatus);
if (error==ERR_NONE && MemStatus.MemoryUsed != 0) {
/*LRif (answer_yes(" Backup phone phonebook")) */DoBackup = true;
}
}
if (DoBackup) {
Pbk.MemoryType = MEM_ME;
i = 1;
used = 0;
while (used != MemStatus.MemoryUsed) {
Pbk.Location = i;
error=Phone->GetMemory(&s, &Pbk);
if (error != ERR_EMPTY) {
Print_Error(error);
if (used < GSM_BACKUP_MAX_PHONEPHONEBOOK) {
Backup.PhonePhonebook[used] = malloc(sizeof(GSM_MemoryEntry));
if (Backup.PhonePhonebook[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.PhonePhonebook[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_PHONEPHONEBOOK");
GSM_Terminate();
exit(-1);
}
*Backup.PhonePhonebook[used]=Pbk;
used++;
}
printmsgerr("%c Reading: %i percent",13,used*100/MemStatus.MemoryUsed);
i++;
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.SIMPhonebook) {
printmsg("Checking SIM phonebook\n");
MemStatus.MemoryType = MEM_SM;
error=Phone->GetMemoryStatus(&s, &MemStatus);
if (error==ERR_NONE && MemStatus.MemoryUsed != 0) {
if (answer_yes(" Backup SIM phonebook")) DoBackup=true;
}
}
if (DoBackup) {
Pbk.MemoryType = MEM_SM;
i = 1;
used = 0;
while (used != MemStatus.MemoryUsed) {
Pbk.Location = i;
error=Phone->GetMemory(&s, &Pbk);
if (error != ERR_EMPTY) {
Print_Error(error);
if (used < GSM_BACKUP_MAX_SIMPHONEBOOK) {
Backup.SIMPhonebook[used] = malloc(sizeof(GSM_MemoryEntry));
if (Backup.SIMPhonebook[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.SIMPhonebook[used + 1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_SIMPHONEBOOK");
GSM_Terminate();
exit(-1);
}
*Backup.SIMPhonebook[used]=Pbk;
used++;
}
printmsgerr("%c Reading: %i percent",13,used*100/MemStatus.MemoryUsed);
i++;
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.Calendar) {
printmsg("Checking calendar\n");
error=Phone->GetNextCalendar(&s,&Calendar,true);
if (error==ERR_NONE) {
if (answer_yes(" Backup calendar notes")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
printmsgerr(" Reading : ");
while (error == ERR_NONE) {
if (used < GSM_MAXCALENDARTODONOTES) {
Backup.Calendar[used] = malloc(sizeof(GSM_CalendarEntry));
if (Backup.Calendar[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.Calendar[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_MAXCALENDARTODONOTES");
GSM_Terminate();
exit(-1);
}
*Backup.Calendar[used]=Calendar;
used ++;
error=Phone->GetNextCalendar(&s,&Calendar,false);
printmsgerr("*");
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.ToDo) {
printmsg("Checking ToDo\n");
error=Phone->GetToDoStatus(&s,&ToDoStatus);
if (error == ERR_NONE && ToDoStatus.Used != 0) {
if (answer_yes(" Backup ToDo")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
error=Phone->GetNextToDo(&s,&ToDo,true);
while (error == ERR_NONE) {
if (used < GSM_MAXCALENDARTODONOTES) {
Backup.ToDo[used] = malloc(sizeof(GSM_ToDoEntry));
if (Backup.ToDo[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.ToDo[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_MAXCALENDARTODONOTES");
GSM_Terminate();
exit(-1);
}
*Backup.ToDo[used]=ToDo;
used ++;
error=Phone->GetNextToDo(&s,&ToDo,false);
printmsgerr("%c Reading: %i percent",13,used*100/ToDoStatus.Used);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.Note) {
printmsg("Checking notes\n");
error=Phone->GetNextNote(&s,&Note,true);
if (error==ERR_NONE) {
if (answer_yes(" Backup notes")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
printmsgerr(" Reading : ");
while (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_NOTE) {
Backup.Note[used] = malloc(sizeof(GSM_NoteEntry));
if (Backup.Note[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.Note[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_NOTE");
GSM_Terminate();
exit(-1);
}
*Backup.Note[used]=Note;
used ++;
error=Phone->GetNextNote(&s,&Note,false);
printmsgerr("*");
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.CallerLogos) {
printmsg("Checking caller logos\n");
Bitmap.Type = GSM_CallerGroupLogo;
Bitmap.Location = 1;
error=Phone->GetBitmap(&s,&Bitmap);
if (error == ERR_NONE) {
if (answer_yes(" Backup caller groups and logos")) DoBackup = true;
}
}
if (DoBackup) {
printmsgerr(" Reading : ");
error = ERR_NONE;
used = 0;
while (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_CALLER) {
Backup.CallerLogos[used] = malloc(sizeof(GSM_Bitmap));
if (Backup.CallerLogos[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.CallerLogos[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_CALLER");
GSM_Terminate();
exit(-1);
}
*Backup.CallerLogos[used] = Bitmap;
used ++;
Bitmap.Location = used + 1;
error=Phone->GetBitmap(&s,&Bitmap);
printmsgerr("*");
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.SMSC) {
printmsg("Checking SMS profiles\n");
if (answer_yes(" Backup SMS profiles")) DoBackup = true;
}
if (DoBackup) {
used = 0;
printmsgerr(" Reading: ");
while (true) {
SMSC.Location = used + 1;
error = Phone->GetSMSC(&s,&SMSC);
if (error != ERR_NONE) break;
if (used < GSM_BACKUP_MAX_SMSC) {
Backup.SMSC[used] = malloc(sizeof(GSM_SMSC));
if (Backup.SMSC[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.SMSC[used + 1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_SMSC");
GSM_Terminate();
exit(-1);
}
*Backup.SMSC[used]=SMSC;
used++;
printmsgerr("*");
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.StartupLogo) {
printmsg("Checking startup text\n");
Bitmap.Type = GSM_WelcomeNote_Text;
error = Phone->GetBitmap(&s,&Bitmap);
if (error == ERR_NONE) {
if (answer_yes(" Backup startup logo/text")) DoBackup = true;
}
}
if (DoBackup) {
Backup.StartupLogo = malloc(sizeof(GSM_Bitmap));
if (Backup.StartupLogo == NULL) Print_Error(ERR_MOREMEMORY);
*Backup.StartupLogo = Bitmap;
if (Bitmap.Text[0]==0 && Bitmap.Text[1]==0) {
Bitmap.Type = GSM_StartupLogo;
error = Phone->GetBitmap(&s,&Bitmap);
if (error == ERR_NONE) *Backup.StartupLogo = Bitmap;
}
}
DoBackup = false;
if (Info.OperatorLogo) {
printmsg("Checking operator logo\n");
Bitmap.Type = GSM_OperatorLogo;
error=Phone->GetBitmap(&s,&Bitmap);
if (error == ERR_NONE) {
if (strcmp(Bitmap.NetworkCode,"000 00")!=0) {
if (answer_yes(" Backup operator logo")) DoBackup = true;
}
}
}
if (DoBackup) {
Backup.OperatorLogo = malloc(sizeof(GSM_Bitmap));
if (Backup.OperatorLogo == NULL) Print_Error(ERR_MOREMEMORY);
*Backup.OperatorLogo = Bitmap;
}
DoBackup = false;
if (Info.WAPBookmark) {
printmsg("Checking WAP bookmarks\n");
Bookmark.Location = 1;
error=Phone->GetWAPBookmark(&s,&Bookmark);
if (error==ERR_NONE) {
if (answer_yes(" Backup WAP bookmarks")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
printmsgerr(" Reading : ");
while (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_WAPBOOKMARK) {
Backup.WAPBookmark[used] = malloc(sizeof(GSM_WAPBookmark));
if (Backup.WAPBookmark[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.WAPBookmark[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_WAPBOOKMARK");
GSM_Terminate();
exit(-1);
}
*Backup.WAPBookmark[used]=Bookmark;
used ++;
Bookmark.Location = used+1;
error=Phone->GetWAPBookmark(&s,&Bookmark);
printmsgerr("*");
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.WAPSettings) {
printmsg("Checking WAP settings\n");
Settings.Location = 1;
error=Phone->GetWAPSettings(&s,&Settings);
if (error==ERR_NONE) {
if (answer_yes(" Backup WAP settings")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
printmsgerr(" Reading : ");
while (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_WAPSETTINGS) {
Backup.WAPSettings[used] = malloc(sizeof(GSM_MultiWAPSettings));
if (Backup.WAPSettings[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.WAPSettings[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_WAPSETTINGS");
GSM_Terminate();
exit(-1);
}
*Backup.WAPSettings[used]=Settings;
used ++;
Settings.Location = used+1;
error=Phone->GetWAPSettings(&s,&Settings);
printmsgerr("*");
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.MMSSettings) {
printmsg("Checking MMS settings\n");
Settings.Location = 1;
error=Phone->GetMMSSettings(&s,&Settings);
if (error==ERR_NONE) {
if (answer_yes(" Backup MMS settings")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
printmsgerr(" Reading : ");
while (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_MMSSETTINGS) {
Backup.MMSSettings[used] = malloc(sizeof(GSM_MultiWAPSettings));
if (Backup.MMSSettings[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.MMSSettings[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_MMSSETTINGS");
GSM_Terminate();
exit(-1);
}
*Backup.MMSSettings[used]=Settings;
used ++;
Settings.Location = used+1;
error=Phone->GetMMSSettings(&s,&Settings);
printmsgerr("*");
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.ChatSettings) {
printmsg("Checking Chat settings\n");
Chat.Location = 1;
error=Phone->GetChatSettings(&s,&Chat);
if (error==ERR_NONE) {
if (answer_yes(" Backup Chat settings")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
printmsgerr(" Reading : ");
while (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_CHATSETTINGS) {
Backup.ChatSettings[used] = malloc(sizeof(GSM_ChatSettings));
if (Backup.ChatSettings[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.ChatSettings[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_CHATSETTINGS");
GSM_Terminate();
exit(-1);
}
*Backup.ChatSettings[used]=Chat;
used ++;
Chat.Location = used+1;
error=Phone->GetChatSettings(&s,&Chat);
printmsgerr("*");
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.SyncMLSettings) {
printmsg("Checking SyncML settings\n");
SyncML.Location = 1;
error=Phone->GetSyncMLSettings(&s,&SyncML);
if (error==ERR_NONE) {
if (answer_yes(" Backup SyncML settings")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
printmsgerr(" Reading : ");
while (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_SYNCMLSETTINGS) {
Backup.SyncMLSettings[used] = malloc(sizeof(GSM_SyncMLSettings));
if (Backup.SyncMLSettings[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.SyncMLSettings[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_SYNCMLSETTINGS");
GSM_Terminate();
exit(-1);
}
*Backup.SyncMLSettings[used]=SyncML;
used ++;
SyncML.Location = used+1;
error=Phone->GetSyncMLSettings(&s,&SyncML);
printmsgerr("*");
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.Ringtone) {
printmsg("Checking user ringtones\n");
Ringtone.Location = 1;
Ringtone.Format = 0;
error=Phone->GetRingtone(&s,&Ringtone,false);
if (error==ERR_EMPTY || error == ERR_NONE) {
if (answer_yes(" Backup user ringtones")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
i = 1;
printmsgerr(" Reading : ");
while (error == ERR_NONE || error == ERR_EMPTY) {
if (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_RINGTONES) {
Backup.Ringtone[used] = malloc(sizeof(GSM_Ringtone));
if (Backup.Ringtone[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.Ringtone[used+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_RINGTONES");
GSM_Terminate();
exit(-1);
}
*Backup.Ringtone[used]=Ringtone;
used ++;
}
i++;
Ringtone.Location = i;
Ringtone.Format = 0;
error=Phone->GetRingtone(&s,&Ringtone,false);
printmsgerr("*");
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.Profiles) {
printmsg("Checking phone profiles\n");
Profile.Location = 1;
error = Phone->GetProfile(&s,&Profile);
if (error == ERR_NONE) {
if (answer_yes(" Backup phone profiles")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
printmsgerr(" Reading: ");
while (true) {
Profile.Location = used + 1;
error = Phone->GetProfile(&s,&Profile);
if (error != ERR_NONE) break;
if (used < GSM_BACKUP_MAX_PROFILES) {
Backup.Profiles[used] = malloc(sizeof(GSM_Profile));
if (Backup.Profiles[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.Profiles[used + 1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_PROFILES");
GSM_Terminate();
exit(-1);
}
*Backup.Profiles[used]=Profile;
used++;
printmsgerr("*");
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.FMStation) {
printmsg("Checking FM stations\n");
FMStation.Location = 1;
error = Phone->GetFMStation(&s,&FMStation);
if (error == ERR_NONE || error == ERR_EMPTY) {
if (answer_yes(" Backup phone FM stations")) DoBackup=true;
}
}
if (DoBackup) {
used = 0;
i = 1;
printmsgerr(" Reading: ");
while (error == ERR_NONE || error == ERR_EMPTY) {
error = Phone->GetFMStation(&s,&FMStation);
if (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_FMSTATIONS) {
Backup.FMStation[used] = malloc(sizeof(GSM_FMStation));
if (Backup.FMStation[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.FMStation[used + 1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_FMSTATIONS");
GSM_Terminate();
exit(-1);
}
*Backup.FMStation[used]=FMStation;
used++;
}
i++;
FMStation.Location = i;
printmsgerr("*");
}
printmsgerr("\n");
}
DoBackup = false;
if (Info.GPRSPoint) {
printmsg("Checking GPRS access points\n");
GPRSPoint.Location = 1;
error = Phone->GetGPRSAccessPoint(&s,&GPRSPoint);
if (error == ERR_NONE || error == ERR_EMPTY) {
if (answer_yes(" Backup GPRS access points")) DoBackup = true;
}
}
if (DoBackup) {
used = 0;
i = 1;
printmsgerr(" Reading: ");
while (error == ERR_NONE || error == ERR_EMPTY) {
error = Phone->GetGPRSAccessPoint(&s,&GPRSPoint);
if (error == ERR_NONE) {
if (used < GSM_BACKUP_MAX_GPRSPOINT) {
Backup.GPRSPoint[used] = malloc(sizeof(GSM_GPRSAccessPoint));
if (Backup.GPRSPoint[used] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.GPRSPoint[used + 1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_GPRSPOINT");
GSM_Terminate();
exit(-1);
}
*Backup.GPRSPoint[used]=GPRSPoint;
used++;
}
i++;
GPRSPoint.Location = i;
printmsgerr("*");
}
printmsgerr("\n");
}
GSM_Terminate();
GSM_SaveBackupFile(argv[2],&Backup, Info.UseUnicode);
GSM_FreeBackup(&Backup);
}
static void Restore(int argc, char *argv[])
{
GSM_Backup Backup;
GSM_FMStation FMStation;
GSM_DateTime date_time;
GSM_CalendarEntry Calendar;
GSM_Bitmap Bitmap;
GSM_Ringtone Ringtone;
GSM_MemoryEntry Pbk;
GSM_MemoryStatus MemStatus;
GSM_ToDoEntry ToDo;
GSM_ToDoStatus ToDoStatus;
GSM_Profile Profile;
GSM_MultiWAPSettings Settings;
GSM_GPRSAccessPoint GPRSPoint;
GSM_WAPBookmark Bookmark;
int i, used, max = 0;
bool Past = true;
bool Found, DoRestore;
error=GSM_ReadBackupFile(argv[2],&Backup);
if (error!=ERR_NOTIMPLEMENTED) {
Print_Error(error);
} else {
printmsgerr("WARNING: Some data not read from file. It can be damaged or restoring some settings from this file format not implemented (maybe higher Gammu required ?)\n");
}
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
if (Backup.DateTimeAvailable) printmsgerr("Time of backup : %s\n",OSDateTime(Backup.DateTime,false));
if (Backup.Model[0]!=0) printmsgerr("Phone : %s\n",Backup.Model);
if (Backup.IMEI[0]!=0) printmsgerr("IMEI : %s\n",Backup.IMEI);
if (Backup.Creator[0]!=0) printmsgerr("File created by : %s\n",Backup.Creator);
if (Backup.MD5Calculated[0]!=0) {
dbgprintf("\"%s\"\n",Backup.MD5Original);
dbgprintf("\"%s\"\n",Backup.MD5Calculated);
if (strcmp(Backup.MD5Original,Backup.MD5Calculated)) {
if (!answer_yes("Checksum in backup file do not match. Continue")) return;
}
}
GSM_Init(true);
DoRestore = false;
if (Backup.PhonePhonebook[0] != NULL) {
MemStatus.MemoryType = MEM_ME;
error=Phone->GetMemoryStatus(&s, &MemStatus);
if (error==ERR_NONE) {
max = 0;
while (Backup.PhonePhonebook[max]!=NULL) max++;
printmsgerr("%i entries in backup file\n",max);
- if (answer_yes("Restore phone phonebook")) DoRestore = true;
+ /* LR if (answer_yes("Restore phone phonebook")) */DoRestore = true;
}
}
if (DoRestore) {
used = 0;
for (i=0;i<MemStatus.MemoryUsed+MemStatus.MemoryFree;i++) {
Pbk.MemoryType = MEM_ME;
Pbk.Location = i + 1;
Pbk.EntriesNum = 0;
if (used<max) {
if (Backup.PhonePhonebook[used]->Location == Pbk.Location) {
Pbk = *Backup.PhonePhonebook[used];
used++;
dbgprintf("Location %i\n",Pbk.Location);
if (Pbk.EntriesNum != 0) error=Phone->SetMemory(&s, &Pbk);
}
}
if (Pbk.EntriesNum == 0) error=Phone->DeleteMemory(&s, &Pbk);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/(MemStatus.MemoryUsed+MemStatus.MemoryFree));
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoRestore = false;
if (Backup.SIMPhonebook[0] != NULL) {
MemStatus.MemoryType = MEM_SM;
error=Phone->GetMemoryStatus(&s, &MemStatus);
if (error==ERR_NONE) {
max = 0;
while (Backup.SIMPhonebook[max]!=NULL) max++;
printmsgerr("%i entries in backup file\n",max);
if (answer_yes("Restore SIM phonebook")) DoRestore = true;
}
}
if (DoRestore) {
used = 0;
for (i=0;i<MemStatus.MemoryUsed+MemStatus.MemoryFree;i++) {
Pbk.MemoryType = MEM_SM;
Pbk.Location = i + 1;
Pbk.EntriesNum = 0;
if (used<max) {
if (Backup.SIMPhonebook[used]->Location == Pbk.Location) {
Pbk = *Backup.SIMPhonebook[used];
used++;
dbgprintf("Location %i\n",Pbk.Location);
if (Pbk.EntriesNum != 0) error=Phone->SetMemory(&s, &Pbk);
}
}
if (Pbk.EntriesNum == 0) error=Phone->DeleteMemory(&s, &Pbk);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/(MemStatus.MemoryUsed+MemStatus.MemoryFree));
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoRestore = false;
if (Backup.CallerLogos[0] != NULL) {
Bitmap.Type = GSM_CallerGroupLogo;
Bitmap.Location = 1;
error=Phone->GetBitmap(&s,&Bitmap);
if (error == ERR_NONE) {
if (answer_yes("Restore caller groups and logos")) DoRestore = true;
}
}
if (DoRestore) {
max = 0;
while (Backup.CallerLogos[max]!=NULL) max++;
for (i=0;i<max;i++) {
error=Phone->SetBitmap(&s,Backup.CallerLogos[i]);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
if (!mystrncasecmp(s.CurrentConfig->SyncTime,"yes",0)) {
if ( true /*LRanswer_yes("Do you want to set date/time in phone (NOTE: in some phones it's required to correctly restore calendar notes and other items)")*/) {
GSM_GetCurrentDateTime(&date_time);
error=Phone->SetDateTime(&s, &date_time);
Print_Error(error);
}
}
DoRestore = false;
if (Backup.Calendar[0] != NULL) {
/* N6110 doesn't support getting calendar status */
error = Phone->GetNextCalendar(&s,&Calendar,true);
if (error == ERR_NONE || error == ERR_INVALIDLOCATION || error == ERR_EMPTY) {
max = 0;
while (Backup.Calendar[max] != NULL) max++;
printmsgerr("%i entries in backup file\n",max);
// LR
//if (answer_yes("Restore calendar notes")) {
//Past = answer_yes("Restore notes from the past");
DoRestore = true;
//}
}
}
if (DoRestore) {
printmsgerr("Deleting old notes: ");
error = Phone->DeleteAllCalendar(&s);
if (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED) {
while (1) {
error = Phone->GetNextCalendar(&s,&Calendar,true);
if (error != ERR_NONE) break;
error = Phone->DeleteCalendar(&s,&Calendar);
Print_Error(error);
printmsgerr("*");
}
printmsgerr("\n");
} else {
printmsgerr("Done\n");
Print_Error(error);
}
for (i=0;i<max;i++) {
if (!Past && IsCalendarNoteFromThePast(Backup.Calendar[i])) continue;
Calendar = *Backup.Calendar[i];
error=Phone->AddCalendar(&s,&Calendar);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoRestore = false;
if (Backup.ToDo[0] != NULL) {
error = Phone->GetToDoStatus(&s,&ToDoStatus);
if (error == ERR_NONE) {
max = 0;
while (Backup.ToDo[max]!=NULL) max++;
printmsgerr("%i entries in backup file\n",max);
//LR if (answer_yes("Restore ToDo"))
DoRestore = true;
}
}
if (DoRestore) {
ToDo = *Backup.ToDo[0];
error = Phone->SetToDo(&s,&ToDo);
}
if (DoRestore && (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED)) {
printmsgerr("Deleting old ToDo: ");
error=Phone->DeleteAllToDo(&s);
if (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED) {
while (1) {
error = Phone->GetNextToDo(&s,&ToDo,true);
if (error != ERR_NONE) break;
error = Phone->DeleteToDo(&s,&ToDo);
Print_Error(error);
printmsgerr("*");
}
printmsgerr("\n");
} else {
printmsgerr("Done\n");
Print_Error(error);
}
for (i=0;i<max;i++) {
ToDo = *Backup.ToDo[i];
ToDo.Location = 0;
error=Phone->AddToDo(&s,&ToDo);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
} else if (DoRestore) {
/* At first delete entries, that were deleted */
used = 0;
error = Phone->GetNextToDo(&s,&ToDo,true);
while (error == ERR_NONE) {
used++;
Found = false;
for (i=0;i<max;i++) {
if (Backup.ToDo[i]->Location == ToDo.Location) {
Found = true;
break;
}
}
if (!Found) {
error=Phone->DeleteToDo(&s,&ToDo);
Print_Error(error);
}
error = Phone->GetNextToDo(&s,&ToDo,false);
printmsgerr("%cCleaning: %i percent",13,used*100/ToDoStatus.Used);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
/* Now write modified/new entries */
for (i=0;i<max;i++) {
ToDo = *Backup.ToDo[i];
error = Phone->SetToDo(&s,&ToDo);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
if (Backup.SMSC[0] != NULL && answer_yes("Restore SMSC profiles")) {
max = 0;
while (Backup.SMSC[max]!=NULL) max++;
for (i=0;i<max;i++) {
error=Phone->SetSMSC(&s,Backup.SMSC[i]);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
if (Backup.StartupLogo != NULL && answer_yes("Restore startup logo/text")) {
error=Phone->SetBitmap(&s,Backup.StartupLogo);
Print_Error(error);
}
if (Backup.OperatorLogo != NULL && answer_yes("Restore operator logo")) {
error=Phone->SetBitmap(&s,Backup.OperatorLogo);
Print_Error(error);
}
DoRestore = false;
if (Backup.WAPBookmark[0] != NULL) {
Bookmark.Location = 1;
error = Phone->GetWAPBookmark(&s,&Bookmark);
if (error == ERR_NONE || error == ERR_INVALIDLOCATION) {
if (answer_yes("Restore WAP bookmarks")) DoRestore = true;
}
}
if (DoRestore) {
printmsgerr("Deleting old bookmarks: ");
/* One thing to explain: DCT4 phones seems to have bug here.
* When delete for example first bookmark, phone change
* numeration for getting frame, not for deleting. So, we try to
* get 1'st bookmark. Inside frame is "correct" location. We use
* it later
*/
while (error==ERR_NONE) {
error = Phone->DeleteWAPBookmark(&s,&Bookmark);
Bookmark.Location = 1;
error = Phone->GetWAPBookmark(&s,&Bookmark);
printmsgerr("*");
}
printmsgerr("\n");
max = 0;
while (Backup.WAPBookmark[max]!=NULL) max++;
for (i=0;i<max;i++) {
Bookmark = *Backup.WAPBookmark[i];
Bookmark.Location = 0;
error=Phone->SetWAPBookmark(&s,&Bookmark);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoRestore = false;
if (Backup.WAPSettings[0] != NULL) {
Settings.Location = 1;
error = Phone->GetWAPSettings(&s,&Settings);
if (error == ERR_NONE) {
if (answer_yes("Restore WAP settings")) DoRestore = true;
}
}
if (DoRestore) {
max = 0;
while (Backup.WAPSettings[max]!=NULL) max++;
for (i=0;i<max;i++) {
error=Phone->SetWAPSettings(&s,Backup.WAPSettings[i]);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoRestore = false;
if (Backup.MMSSettings[0] != NULL) {
Settings.Location = 1;
error = Phone->GetMMSSettings(&s,&Settings);
if (error == ERR_NONE) {
if (answer_yes("Restore MMS settings")) DoRestore = true;
}
}
if (DoRestore) {
max = 0;
while (Backup.MMSSettings[max]!=NULL) max++;
for (i=0;i<max;i++) {
error=Phone->SetMMSSettings(&s,Backup.MMSSettings[i]);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoRestore = false;
if (Backup.Ringtone[0] != NULL) {
Ringtone.Location = 1;
Ringtone.Format = 0;
error = Phone->GetRingtone(&s,&Ringtone,false);
if (error == ERR_NONE || error ==ERR_EMPTY) {
if (Phone->DeleteUserRingtones != NOTSUPPORTED) {
if (answer_yes("Delete all user ringtones")) DoRestore = true;
}
}
}
if (DoRestore) {
printmsgerr("Deleting: ");
error=Phone->DeleteUserRingtones(&s);
Print_Error(error);
printmsgerr("Done\n");
DoRestore = false;
if (answer_yes("Restore user ringtones")) DoRestore = true;
}
if (DoRestore) {
max = 0;
while (Backup.Ringtone[max]!=NULL) max++;
for (i=0;i<max;i++) {
error=GSM_RingtoneConvert(&Ringtone, Backup.Ringtone[i], Ringtone.Format);
Print_Error(error);
error=Phone->SetRingtone(&s,&Ringtone,&i);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoRestore = false;
if (Backup.Profiles[0] != NULL) {
Profile.Location = 1;
error = Phone->GetProfile(&s,&Profile);
if (error == ERR_NONE) {
if (answer_yes("Restore profiles")) DoRestore = true;
}
}
if (DoRestore) {
Profile.Location= 0;
max = 0;
while (Backup.Profiles[max]!=NULL) max++;
for (i=0;i<max;i++) {
Profile = *Backup.Profiles[i];
error=Phone->SetProfile(&s,&Profile);
Print_Error(error);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoRestore = false;
if (Backup.FMStation[0] != NULL) {
FMStation.Location = 1;
error = Phone->GetFMStation(&s,&FMStation);
if (error == ERR_NONE || error == ERR_EMPTY) {
if (answer_yes("Restore FM stations")) DoRestore = true;
}
}
if (DoRestore) {
printmsgerr("Deleting old FM stations: ");
error=Phone->ClearFMStations(&s);
Print_Error(error);
printmsgerr("Done\n");
max = 0;
while (Backup.FMStation[max]!=NULL) max++;
for (i=0;i<max;i++) {
FMStation = *Backup.FMStation[i];
error=Phone->SetFMStation(&s,&FMStation);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
DoRestore = false;
if (Backup.GPRSPoint[0] != NULL) {
GPRSPoint.Location = 1;
error = Phone->GetGPRSAccessPoint(&s,&GPRSPoint);
if (error == ERR_NONE || error == ERR_EMPTY) {
if (answer_yes("Restore GPRS Points")) DoRestore = true;
}
}
if (DoRestore) {
max = 0;
while (Backup.GPRSPoint[max]!=NULL) max++;
for (i=0;i<max;i++) {
error=Phone->SetGPRSAccessPoint(&s,Backup.GPRSPoint[i]);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
GSM_Terminate();
}
static void AddNew(int argc, char *argv[])
{
GSM_Backup Backup;
GSM_DateTime date_time;
GSM_MemoryEntry Pbk;
GSM_MemoryStatus MemStatus;
GSM_ToDoEntry ToDo;
GSM_ToDoStatus ToDoStatus;
GSM_CalendarEntry Calendar;
GSM_WAPBookmark Bookmark;
int i, max, j;
error=GSM_ReadBackupFile(argv[2],&Backup);
if (error!=ERR_NOTIMPLEMENTED) Print_Error(error);
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
if (Backup.DateTimeAvailable) printmsgerr("Time of backup : %s\n",OSDateTime(Backup.DateTime,false));
if (Backup.Model[0]!=0) printmsgerr("Phone : %s\n",Backup.Model);
if (Backup.IMEI[0]!=0) printmsgerr("IMEI : %s\n",Backup.IMEI);
GSM_Init(true);
if (Backup.PhonePhonebook[0] != NULL) {
MemStatus.MemoryType = MEM_ME;
error=Phone->GetMemoryStatus(&s, &MemStatus);
if (error==ERR_NONE) {
max = 0;
while (Backup.PhonePhonebook[max]!=NULL) max++;
printmsgerr("%i entries in backup file\n",max);
if (MemStatus.MemoryFree < max) {
printmsgerr("Memory has only %i free locations.Exiting\n",MemStatus.MemoryFree);
} else if (answer_yes("Add phone phonebook entries")) {
for (i=0;i<max;i++) {
Pbk = *Backup.PhonePhonebook[i];
Pbk.MemoryType = MEM_ME;
error=Phone->AddMemory(&s, &Pbk);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
}
}
if (Backup.SIMPhonebook[0] != NULL) {
MemStatus.MemoryType = MEM_SM;
error=Phone->GetMemoryStatus(&s, &MemStatus);
if (error==ERR_NONE) {
max = 0;
while (Backup.SIMPhonebook[max]!=NULL) max++;
printmsgerr("%i entries in backup file\n",max);
if (MemStatus.MemoryFree < max) {
printmsgerr("Memory has only %i free locations.Exiting\n",MemStatus.MemoryFree);
} else if (answer_yes("Add SIM phonebook entries")) {
j = 1;
for (i=0;i<max;i++) {
Pbk = *Backup.SIMPhonebook[i];
Pbk.MemoryType = MEM_SM;
error=Phone->AddMemory(&s, &Pbk);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
}
}
if (!mystrncasecmp(s.CurrentConfig->SyncTime,"yes",0)) {
if (true /*LRanswer_yes("Do you want to set date/time in phone (NOTE: in some phones it's required to correctly restore calendar notes and other items)")*/) {
GSM_GetCurrentDateTime(&date_time);
error=Phone->SetDateTime(&s, &date_time);
Print_Error(error);
}
}
if (Backup.Calendar[0] != NULL) {
error = Phone->GetNextCalendar(&s,&Calendar,true);
if (error == ERR_NONE || error == ERR_INVALIDLOCATION || error == ERR_EMPTY) {
if (answer_yes("Add calendar notes")) {
max = 0;
while (Backup.Calendar[max]!=NULL) max++;
for (i=0;i<max;i++) {
Calendar = *Backup.Calendar[i];
error=Phone->AddCalendar(&s,&Calendar);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
}
}
if (Backup.ToDo[0] != NULL) {
ToDo.Location = 1;
error=Phone->GetToDoStatus(&s,&ToDoStatus);
if (error == ERR_NONE) {
if (answer_yes("Add ToDo")) {
max = 0;
while (Backup.ToDo[max]!=NULL) max++;
for (i=0;i<max;i++) {
ToDo = *Backup.ToDo[i];
error = Phone->AddToDo(&s,&ToDo);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
}
}
if (Backup.WAPBookmark[0] != NULL) {
Bookmark.Location = 1;
error = Phone->GetWAPBookmark(&s,&Bookmark);
if (error == ERR_NONE || error == ERR_INVALIDLOCATION) {
if (answer_yes("Add WAP bookmarks")) {
max = 0;
while (Backup.WAPBookmark[max]!=NULL) max++;
for (i=0;i<max;i++) {
Bookmark = *Backup.WAPBookmark[i];
Bookmark.Location = 0;
error=Phone->SetWAPBookmark(&s,&Bookmark);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/max);
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
}
}
}
GSM_Terminate();
}
#endif
static void ClearAll(int argc, char *argv[])
{
GSM_MemoryStatus MemStatus;
GSM_ToDoStatus ToDoStatus;
GSM_CalendarEntry Calendar;
GSM_ToDoEntry ToDo;
GSM_WAPBookmark Bookmark;
GSM_FMStation Station;
GSM_MemoryEntry Pbk;
bool DoClear;
GSM_Init(true);
DoClear = false;
MemStatus.MemoryType = MEM_ME;
error=Phone->GetMemoryStatus(&s, &MemStatus);
if (error==ERR_NONE && MemStatus.MemoryUsed !=0) {
if (answer_yes("Delete phone phonebook")) DoClear = true;
}
if (DoClear) {
error = Phone->DeleteAllMemory(&s,MEM_ME);
if (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED) {
for (i=0;i<MemStatus.MemoryUsed+MemStatus.MemoryFree;i++) {
Pbk.MemoryType = MEM_ME;
Pbk.Location = i + 1;
Pbk.EntriesNum = 0;
error=Phone->DeleteMemory(&s, &Pbk);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/(MemStatus.MemoryUsed+MemStatus.MemoryFree));
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
} else {
printmsgerr("Done\n");
Print_Error(error);
}
}
DoClear = false;
MemStatus.MemoryType = MEM_SM;
error=Phone->GetMemoryStatus(&s, &MemStatus);
if (error==ERR_NONE && MemStatus.MemoryUsed !=0) {
if (answer_yes("Delete SIM phonebook")) DoClear = true;
}
if (DoClear) {
error = Phone->DeleteAllMemory(&s,MEM_SM);
if (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED) {
for (i=0;i<MemStatus.MemoryUsed+MemStatus.MemoryFree;i++) {
Pbk.MemoryType = MEM_SM;
Pbk.Location = i + 1;
Pbk.EntriesNum = 0;
error=Phone->DeleteMemory(&s, &Pbk);
Print_Error(error);
printmsgerr("%cWriting: %i percent",13,(i+1)*100/(MemStatus.MemoryUsed+MemStatus.MemoryFree));
if (gshutdown) {
GSM_Terminate();
exit(0);
}
}
printmsgerr("\n");
} else {
printmsgerr("Done\n");
Print_Error(error);
}
}
DoClear = false;
error = Phone->GetNextCalendar(&s,&Calendar,true);
if (error == ERR_NONE) {
if (answer_yes("Delete calendar notes")) DoClear = true;
}
if (DoClear) {
printmsgerr("Deleting: ");
error=Phone->DeleteAllCalendar(&s);
if (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED) {
while (1) {
error = Phone->GetNextCalendar(&s,&Calendar,true);
if (error != ERR_NONE) break;
error = Phone->DeleteCalendar(&s,&Calendar);
Print_Error(error);
printmsgerr("*");
}
printmsgerr("\n");
} else {
printmsgerr("Done\n");
Print_Error(error);
}
}
DoClear = false;
error = Phone->GetToDoStatus(&s,&ToDoStatus);
if (error == ERR_NONE && ToDoStatus.Used != 0) {
if (answer_yes("Delete ToDo")) DoClear = true;
}
if (DoClear) {
printmsgerr("Deleting: ");
error=Phone->DeleteAllToDo(&s);
if (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED) {
while (1) {
error = Phone->GetNextToDo(&s,&ToDo,true);
if (error != ERR_NONE) break;
error = Phone->DeleteToDo(&s,&ToDo);
Print_Error(error);
printmsgerr("*");
}
printmsgerr("\n");
} else {
printmsgerr("Done\n");
Print_Error(error);
}
}
Bookmark.Location = 1;
error = Phone->GetWAPBookmark(&s,&Bookmark);
if (error == ERR_NONE || error == ERR_INVALIDLOCATION) {
if (answer_yes("Delete WAP bookmarks")) {
printmsgerr("Deleting: ");
/* One thing to explain: DCT4 phones seems to have bug here.
* When delete for example first bookmark, phone change
* numeration for getting frame, not for deleting. So, we try to
* get 1'st bookmark. Inside frame is "correct" location. We use
* it later
*/
while (error==ERR_NONE) {
error = Phone->DeleteWAPBookmark(&s,&Bookmark);
Bookmark.Location = 1;
error = Phone->GetWAPBookmark(&s,&Bookmark);
printmsgerr("*");
}
printmsgerr("\n");
}
}
if (Phone->DeleteUserRingtones != NOTSUPPORTED) {
if (answer_yes("Delete all user ringtones")) {
printmsgerr("Deleting: ");
error=Phone->DeleteUserRingtones(&s);
Print_Error(error);
printmsgerr("Done\n");
}
}
Station.Location=i;
error=Phone->GetFMStation(&s,&Station);
if (error == ERR_NONE || error == ERR_EMPTY) {
if (answer_yes("Delete all FM station")) {
error=Phone->ClearFMStations(&s);
Print_Error(error);
}
}
GSM_Terminate();
}
static void DisplayConnectionSettings(GSM_MultiWAPSettings *settings,int j)
{
if (settings->Settings[j].IsContinuous) {
printmsg("Connection type : Continuous\n");
} else {
printmsg("Connection type : Temporary\n");
}
if (settings->Settings[j].IsSecurity) {
printmsg("Connection security : On\n");
} else {
printmsg("Connection security : Off\n");
}
printmsg("Proxy : address \"%s\", port %i\n",DecodeUnicodeConsole(settings->Proxy),settings->ProxyPort);
printmsg("2'nd proxy : address \"%s\", port %i\n",DecodeUnicodeConsole(settings->Proxy2),settings->Proxy2Port);
switch (settings->Settings[j].Bearer) {
case WAPSETTINGS_BEARER_SMS:
printmsg("Bearer : SMS");
if (settings->ActiveBearer == WAPSETTINGS_BEARER_SMS) printf(" (active)");
printmsg("\nServer number : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].Server));
printmsg("Service number : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].Service));
break;
case WAPSETTINGS_BEARER_DATA:
printmsg("Bearer : Data (CSD)");
if (settings->ActiveBearer == WAPSETTINGS_BEARER_DATA) printf(" (active)");
printmsg("\nDial-up number : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].DialUp));
printmsg("IP address : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].IPAddress));
if (settings->Settings[j].ManualLogin) {
printmsg("Login Type : Manual\n");
} else {
printmsg("Login Type : Automatic\n");
}
if (settings->Settings[j].IsNormalAuthentication) {
printmsg("Authentication type : Normal\n");
} else {
printmsg("Authentication type : Secure\n");
}
if (settings->Settings[j].IsISDNCall) {
printmsg("Data call type : ISDN\n");
} else {
printmsg("Data call type : Analogue\n");
}
switch (settings->Settings[j].Speed) {
case WAPSETTINGS_SPEED_9600 : printmsg("Data call speed : 9600\n"); break;
case WAPSETTINGS_SPEED_14400 : printmsg("Data call speed : 14400\n"); break;
case WAPSETTINGS_SPEED_AUTO : printmsg("Data call speed : Auto\n"); break;
}
printmsg("User name : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].User));
printmsg("Password : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].Password));
break;
case WAPSETTINGS_BEARER_USSD:
printmsg("Bearer : USSD");
if (settings->ActiveBearer == WAPSETTINGS_BEARER_USSD) printf(" (active)");
printmsg("\nService code : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].Code));
if (settings->Settings[j].IsIP) {
printmsg("Address type : IP address\nIPaddress : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].Service));
} else {
printmsg("Address type : Service number\nService number : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].Service));
}
break;
case WAPSETTINGS_BEARER_GPRS:
printmsg("Bearer : GPRS");
if (settings->ActiveBearer == WAPSETTINGS_BEARER_GPRS) printf(" (active)");
if (settings->Settings[j].ManualLogin) {
printmsg("\nLogin Type : Manual\n");
} else {
printmsg("\nLogin Type : Automatic\n");
}
if (settings->Settings[j].IsNormalAuthentication) {
printmsg("Authentication type : Normal\n");
} else {
printmsg("Authentication type : Secure\n");
}
printmsg("Access point : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].DialUp));
printmsg("IP address : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].IPAddress));
printmsg("User name : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].User));
printmsg("Password : \"%s\"\n",DecodeUnicodeConsole(settings->Settings[j].Password));
}
}
static void GetSyncMLSettings(int argc, char *argv[])
{
GSM_SyncMLSettings settings;
int start,stop,j;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
settings.Location=i;
error=Phone->GetSyncMLSettings(&s,&settings);
Print_Error(error);
printmsg("%i. ",i);
if (settings.Name[0]==0 && settings.Name[1]==0) {
printmsg("Set %i",i);
} else {
printmsg("%s",DecodeUnicodeConsole(settings.Name));
}
if (settings.Active) printmsg(" (active)");
// if (settings.ReadOnly) printmsg("\nRead only : yes");
printmsg("\n");
printmsg("User : \"%s\"\n",DecodeUnicodeConsole(settings.User));
printmsg("Password : \"%s\"\n",DecodeUnicodeConsole(settings.Password));
printmsg("Phonebook database : \"%s\"\n",DecodeUnicodeConsole(settings.PhonebookDataBase));
printmsg("Calendar database : \"%s\"\n",DecodeUnicodeConsole(settings.CalendarDataBase));
printmsg("Server : \"%s\"\n",DecodeUnicodeConsole(settings.Server));
printmsg("Sync. phonebook : ");
if (settings.SyncPhonebook) printmsg("yes\n");
if (!settings.SyncPhonebook) printmsg("no\n");
printmsg("Sync. calendar : ");
if (settings.SyncCalendar) printmsg("yes\n");
if (!settings.SyncCalendar) printmsg("no\n");
printmsg("\n");
for (j=0;j<settings.Connection.Number;j++) {
if (settings.Connection.Settings[j].Title[0]==0 && settings.Connection.Settings[j].Title[1]==0) {
printmsg("Connection set name : Set %i\n",i);
} else {
printmsg("Connection set name : %s\n",DecodeUnicodeConsole(settings.Connection.Settings[j].Title));
}
DisplayConnectionSettings(&settings.Connection,j);
printf("\n");
}
}
GSM_Terminate();
}
static void GetChatSettings(int argc, char *argv[])
{
GSM_ChatSettings settings;
int start,stop,j;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
settings.Location=i;
error=Phone->GetChatSettings(&s,&settings);
Print_Error(error);
printmsg("%i. ",i);
if (settings.Name[0]==0 && settings.Name[1]==0) {
printmsg("Set %i",i);
} else {
printmsg("%s",DecodeUnicodeConsole(settings.Name));
}
if (settings.Active) printmsg(" (active)");
// if (settings.ReadOnly) printmsg("\nRead only : yes");
printmsg("\n");
printmsg("Homepage : \"%s\"\n",DecodeUnicodeConsole(settings.HomePage));
printmsg("User : \"%s\"\n",DecodeUnicodeConsole(settings.User));
printmsg("Password : \"%s\"\n",DecodeUnicodeConsole(settings.Password));
printmsg("\n");
for (j=0;j<settings.Connection.Number;j++) {
if (settings.Connection.Settings[j].Title[0]==0 && settings.Connection.Settings[j].Title[1]==0) {
printmsg("Connection set name : Set %i\n",i);
} else {
printmsg("Connection set name : %s\n",DecodeUnicodeConsole(settings.Connection.Settings[j].Title));
}
DisplayConnectionSettings(&settings.Connection,j);
printf("\n");
}
}
GSM_Terminate();
}
static void GetWAPMMSSettings(int argc, char *argv[])
{
GSM_MultiWAPSettings settings;
int start,stop,j;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
settings.Location=i;
if (mystrncasecmp(argv[1],"--getwapsettings",0)) {
error=Phone->GetWAPSettings(&s,&settings);
} else {
error=Phone->GetMMSSettings(&s,&settings);
}
Print_Error(error);
for (j=0;j<settings.Number;j++) {
printmsg("%i. ",i);
if (settings.Settings[j].Title[0]==0 && settings.Settings[j].Title[1]==0) {
printmsg("Set %i",i);
} else {
printmsg("%s",DecodeUnicodeConsole(settings.Settings[j].Title));
}
if (settings.Active) printmsg(" (active)");
if (settings.ReadOnly) printmsg("\nRead only : yes");
printmsg("\nHomepage : \"%s\"\n",DecodeUnicodeConsole(settings.Settings[j].HomePage));
DisplayConnectionSettings(&settings,j);
printf("\n");
}
}
GSM_Terminate();
}
#ifdef GSM_ENABLE_BACKUP
static void BackupSMS(int argc, char *argv[])
{
GSM_SMS_Backup Backup;
GSM_MultiSMSMessage sms;
GSM_SMSFolders folders;
bool BackupFromFolder[GSM_MAX_SMS_FOLDERS];
bool start = true;
bool DeleteAfter;
int j, smsnum;
char buffer[200];
/* We ignore return code, because (when file doesn't exist) we
* will create new later
*/
GSM_ReadSMSBackupFile(argv[2], &Backup);
smsnum = 0;
while (Backup.SMS[smsnum]!=NULL) smsnum++;
GSM_Init(true);
error=Phone->GetSMSFolders(&s, &folders);
Print_Error(error);
DeleteAfter=answer_yes("Delete each sms after backup");
for (j=0;j<folders.Number;j++) {
BackupFromFolder[j] = false;
sprintf(buffer,"Backup sms from folder \"%s\"",DecodeUnicodeConsole(folders.Folder[j].Name));
if (answer_yes(buffer)) BackupFromFolder[j] = true;
}
while (error == ERR_NONE) {
sms.SMS[0].Folder=0x00;
error=Phone->GetNextSMS(&s, &sms, start);
switch (error) {
case ERR_EMPTY:
break;
default:
Print_Error(error);
for (j=0;j<sms.Number;j++) {
if (BackupFromFolder[sms.SMS[j].Folder-1]) {
switch (sms.SMS[j].PDU) {
case SMS_Status_Report:
break;
case SMS_Submit:
case SMS_Deliver:
if (sms.SMS[j].Length == 0) break;
if (smsnum < GSM_BACKUP_MAX_SMS) {
Backup.SMS[smsnum] = malloc(sizeof(GSM_SMSMessage));
if (Backup.SMS[smsnum] == NULL) Print_Error(ERR_MOREMEMORY);
Backup.SMS[smsnum+1] = NULL;
} else {
printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_SMS");
GSM_Terminate();
exit(-1);
}
*Backup.SMS[smsnum] = sms.SMS[j];
smsnum++;
break;
}
}
}
}
start=false;
}
error = GSM_SaveSMSBackupFile(argv[2],&Backup);
Print_Error(error);
if (DeleteAfter) {
for (j=0;j<smsnum;j++) {
Backup.SMS[j]->Folder = 0;
error=Phone->DeleteSMS(&s, Backup.SMS[j]);
Print_Error(error);
printmsgerr("%cDeleting: %i percent",13,(j+1)*100/smsnum);
}
}
GSM_Terminate();
}
static void AddSMS(int argc, char *argv[])
{
GSM_MultiSMSMessage SMS;
GSM_SMS_Backup Backup;
int smsnum = 0;
int folder;
folder = atoi(argv[2]);
error = GSM_ReadSMSBackupFile(argv[3], &Backup);
Print_Error(error);
GSM_Init(true);
while (Backup.SMS[smsnum] != NULL) {
Backup.SMS[smsnum]->Folder = folder;
Backup.SMS[smsnum]->SMSC.Location = 1;
SMS.Number = 1;
SMS.SMS[0] = *Backup.SMS[smsnum];
displaymultismsinfo(SMS,false,false);
if (answer_yes("Restore sms")) {
error=Phone->AddSMS(&s, Backup.SMS[smsnum]);
Print_Error(error);
}
smsnum++;
}
GSM_Terminate();
}
static void RestoreSMS(int argc, char *argv[])
{
GSM_MultiSMSMessage SMS;
GSM_SMS_Backup Backup;
GSM_SMSFolders folders;
int smsnum = 0;
char buffer[200];
error=GSM_ReadSMSBackupFile(argv[2], &Backup);
Print_Error(error);
GSM_Init(true);
error=Phone->GetSMSFolders(&s, &folders);
Print_Error(error);
while (Backup.SMS[smsnum] != NULL) {
SMS.Number = 1;
memcpy(&SMS.SMS[0],Backup.SMS[smsnum],sizeof(GSM_SMSMessage));
displaymultismsinfo(SMS,false,false);
sprintf(buffer,"Restore sms to folder \"%s\"",DecodeUnicodeConsole(folders.Folder[Backup.SMS[smsnum]->Folder-1].Name));
if (answer_yes(buffer)) {
error=Phone->AddSMS(&s, Backup.SMS[smsnum]);
Print_Error(error);
}
smsnum++;
}
GSM_Terminate();
}
#endif
static void CopyBitmap(int argc, char *argv[])
{
GSM_MultiBitmap Bitmap;
int i;
Bitmap.Bitmap[0].Type = GSM_None;
error=GSM_ReadBitmapFile(argv[2],&Bitmap);
Print_Error(error);
if (argc==3) {
for (i=0;i<Bitmap.Number;i++) {
switch (Bitmap.Bitmap[i].Type) {
case GSM_StartupLogo : printmsg("Startup logo"); break;
case GSM_OperatorLogo: printmsg("Operator logo"); break;
case GSM_PictureImage: printmsg("Picture Image"); break;
case GSM_CallerGroupLogo : printmsg("Caller group logo"); break;
default : break;
}
printmsg(", width %i, height %i\n",Bitmap.Bitmap[i].BitmapWidth,Bitmap.Bitmap[i].BitmapHeight);
GSM_PrintBitmap(stdout,&Bitmap.Bitmap[i]);
}
} else {
if (argc == 5) {
for (i=0;i<Bitmap.Number;i++) {
if (mystrncasecmp(argv[4],"PICTURE",0)) {
Bitmap.Bitmap[i].Type = GSM_PictureImage;
} else if (mystrncasecmp(argv[4],"STARTUP",0)) {
Bitmap.Bitmap[i].Type = GSM_StartupLogo;
} else if (mystrncasecmp(argv[4],"CALLER",0)) {
Bitmap.Bitmap[i].Type = GSM_CallerGroupLogo;
} else if (mystrncasecmp(argv[4],"OPERATOR",0)) {
Bitmap.Bitmap[i].Type = GSM_OperatorLogo;
} else {
printmsg("What format of output file logo (\"%s\") ?\n",argv[4]);
exit(-1);
}
}
}
error=GSM_SaveBitmapFile(argv[3],&Bitmap);
Print_Error(error);
}
}
static void NokiaComposer(int argc, char *argv[])
{
GSM_Ringtone ringtone;
bool started;
int i,j;
GSM_RingNote *Note;
GSM_RingNoteDuration Duration;
GSM_RingNoteDuration DefNoteDuration = 32; /* 32 = Duration_1_4 */
unsigned int DefNoteScale = Scale_880;
ringtone.Format = 0;
error=GSM_ReadRingtoneFile(argv[2],&ringtone);
if (ringtone.Format != RING_NOTETONE) {
printmsg("It can be RTTL ringtone only used with this option\n");
exit(-1);
}
started = false;
j = 0;
for (i=0;i<ringtone.NoteTone.NrCommands;i++) {
if (ringtone.NoteTone.Commands[i].Type == RING_Note) {
Note = &ringtone.NoteTone.Commands[i].Note;
if (!started) {
if (Note->Note != Note_Pause) {
printmsg("Ringtone \"%s\" (tempo = %i Beats Per Minute)\n\n",DecodeUnicodeConsole(ringtone.Name),GSM_RTTLGetTempo(Note->Tempo));
started = true;
}
}
if (started) j++;
}
}
if (j>50) printmsg("WARNING: LENGTH=%i NOTES, BUT YOU WILL ENTER ONLY FIRST 50 TONES.",j);
printmsg("\n\nThis ringtone in Nokia Composer in phone should look: ");
started = false;
for (i=0;i<ringtone.NoteTone.NrCommands;i++) {
if (ringtone.NoteTone.Commands[i].Type == RING_Note) {
Note = &ringtone.NoteTone.Commands[i].Note;
if (!started) {
if (Note->Note != Note_Pause) started = true;
}
if (started) {
switch (Note->Duration) {
case Duration_Full: printmsg("1"); break;
case Duration_1_2 : printmsg("2"); break;
case Duration_1_4 : printmsg("4"); break;
case Duration_1_8 : printmsg("8"); break;
case Duration_1_16: printmsg("16");break;
case Duration_1_32: printmsg("32");break;
}
if (Note->DurationSpec == DottedNote) printmsg(".");
switch (Note->Note) {
case Note_C : printmsg("c"); break;
case Note_Cis : printmsg("#c"); break;
case Note_D :printmsg("d"); break;
case Note_Dis : printmsg("#d"); break;
case Note_E : printmsg("e"); break;
case Note_F : printmsg("f"); break;
case Note_Fis : printmsg("#f"); break;
case Note_G : printmsg("g"); break;
case Note_Gis : printmsg("#g"); break;
case Note_A : printmsg("a"); break;
case Note_Ais : printmsg("#a"); break;
case Note_H : printmsg("h"); break;
case Note_Pause : printmsg("-"); break;
}
if (Note->Note != Note_Pause) printmsg("%i",Note->Scale - 4);
printmsg(" ");
}
}
}
printmsg("\n\nTo enter it please press: ");
started = false;
for (i=0;i<ringtone.NoteTone.NrCommands;i++) {
if (ringtone.NoteTone.Commands[i].Type == RING_Note) {
Note = &ringtone.NoteTone.Commands[i].Note;
if (!started) {
if (Note->Note != Note_Pause) started = true;
}
if (started) {
switch (Note->Note) {
case Note_C : case Note_Cis: printmsg("1");break;
case Note_D : case Note_Dis: printmsg("2");break;
case Note_E : printmsg("3");break;
case Note_F : case Note_Fis: printmsg("4");break;
case Note_G : case Note_Gis: printmsg("5");break;
case Note_A : case Note_Ais: printmsg("6");break;
case Note_H : printmsg("7");break;
default : printmsg("0");break;
}
if (Note->DurationSpec == DottedNote) printmsg("(longer)");
switch (Note->Note) {
case Note_Cis: case Note_Dis:
case Note_Fis: case Note_Gis:
case Note_Ais:
printmsg("#");
break;
default :
break;
}
if (Note->Note != Note_Pause) {
if ((unsigned int)Note->Scale != DefNoteScale) {
while (DefNoteScale != (unsigned int)Note->Scale) {
printmsg("*");
DefNoteScale++;
if (DefNoteScale==Scale_7040) DefNoteScale = Scale_880;
}
}
}
Duration = 0;
switch (Note->Duration) {
case Duration_Full : Duration = 128; break;
case Duration_1_2 : Duration = 64; break;
case Duration_1_4 : Duration = 32; break;
case Duration_1_8 : Duration = 16; break;
case Duration_1_16 : Duration = 8; break;
case Duration_1_32 : Duration = 4; break;
default : dbgprintf("error\n");break;
}
if (Duration > DefNoteDuration) {
while (DefNoteDuration != Duration) {
printmsg("9");
DefNoteDuration = DefNoteDuration * 2;
}
}
if (Duration < DefNoteDuration) {
while (DefNoteDuration != Duration) {
printmsg("8");
DefNoteDuration = DefNoteDuration / 2;
}
}
printmsg(" ");
}
}
}
printf("\n");
}
static void CopyRingtone(int argc, char *argv[])
{
GSM_Ringtone ringtone, ringtone2;
GSM_RingtoneFormat Format;
ringtone.Format = 0;
error=GSM_ReadRingtoneFile(argv[2],&ringtone);
Print_Error(error);
Format = ringtone.Format;
if (argc == 5) {
if (mystrncasecmp(argv[4],"RTTL",0)) { Format = RING_NOTETONE;
} else if (mystrncasecmp(argv[4],"BINARY",0)) { Format = RING_NOKIABINARY;
} else {
printmsg("What format of output ringtone file (\"%s\") ?\n",argv[4]);
exit(-1);
}
}
error=GSM_RingtoneConvert(&ringtone2,&ringtone,Format);
Print_Error(error);
error=GSM_SaveRingtoneFile(argv[3],&ringtone2);
Print_Error(error);
}
static void PressKeySequence(int argc, char *argv[])
{
int i,Length;
GSM_KeyCode KeyCode[500];
error = MakeKeySequence(argv[2], KeyCode, &Length);
if (error == ERR_NOTSUPPORTED) {
printmsg("Unknown key/function name: \"%c\"\n",argv[2][Length]);
exit(-1);
}
GSM_Init(true);
for (i=0;i<Length;i++) {
error=Phone->PressKey(&s, KeyCode[i], true);
Print_Error(error);
error=Phone->PressKey(&s, KeyCode[i], false);
Print_Error(error);
}
GSM_Terminate();
}
static void GetAllCategories(int argc, char *argv[])
{
GSM_Category Category;
GSM_CategoryStatus Status;
int j, count;
if (mystrncasecmp(argv[2],"TODO",0)) {
Category.Type = Category_ToDo;
Status.Type = Category_ToDo;
} else if (mystrncasecmp(argv[2],"PHONEBOOK",0)) {
Category.Type = Category_Phonebook;
Status.Type = Category_Phonebook;
} else {
printmsg("What type of categories do you want to get (\"%s\") ?\n",argv[2]);
exit(-1);
}
GSM_Init(true);
error=Phone->GetCategoryStatus(&s, &Status);
Print_Error(error);
for (count=0,j=1;count<Status.Used;j++)
{
Category.Location=j;
error=Phone->GetCategory(&s, &Category);
if (error != ERR_EMPTY) {
printmsg("Location: %i\n",j);
Print_Error(error);
printmsg("Name : \"%s\"\n\n",DecodeUnicodeConsole(Category.Name));
count++;
}
}
GSM_Terminate();
}
static void GetCategory(int argc, char *argv[])
{
GSM_Category Category;
int start,stop,j;
if (mystrncasecmp(argv[2],"TODO",0)) {
Category.Type = Category_ToDo;
} else if (mystrncasecmp(argv[2],"PHONEBOOK",0)) {
Category.Type = Category_Phonebook;
} else {
printmsg("What type of categories do you want to get (\"%s\") ?\n",argv[2]);
exit(-1);
}
GetStartStop(&start, &stop, 2, argc - 1, argv + 1);
GSM_Init(true);
for (j=start;j<=stop;j++)
{
printmsg("Location: %i\n",j);
Category.Location=j;
error=Phone->GetCategory(&s, &Category);
if (error != ERR_EMPTY) Print_Error(error);
if (error == ERR_EMPTY) {
printmsg("Entry is empty\n\n");
} else {
printmsg("Name : \"%s\"\n\n",DecodeUnicodeConsole(Category.Name));
}
}
GSM_Terminate();
}
static void DeleteToDo(int argc, char *argv[])
{
GSM_ToDoEntry ToDo;
int i;
int start,stop;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
ToDo.Location=i;
printmsg("Location : %i\n",i);
error=Phone->DeleteToDo(&s,&ToDo);
if (error != ERR_EMPTY) Print_Error(error);
if (error == ERR_EMPTY) {
printmsg("Entry was empty\n");
} else {
printmsg("Entry was deleted\n");
}
printf("\n");
}
GSM_Terminate();
}
static void PrintToDo(GSM_ToDoEntry *ToDo)
{
int j;
GSM_MemoryEntry entry;
unsigned char *name;
GSM_Category Category;
printmsg("Location : %i\n",ToDo->Location);
printmsg("Priority : ");
switch (ToDo->Priority) {
case GSM_Priority_Low : printmsg("Low\n"); break;
case GSM_Priority_Medium : printmsg("Medium\n"); break;
case GSM_Priority_High : printmsg("High\n"); break;
default : printmsg("Unknown\n"); break;
}
for (j=0;j<ToDo->EntriesNum;j++) {
switch (ToDo->Entries[j].EntryType) {
case TODO_END_DATETIME:
printmsg("DueTime : %s\n",OSDateTime(ToDo->Entries[j].Date,false));
break;
case TODO_COMPLETED:
printmsg("Completed : %s\n",ToDo->Entries[j].Number == 1 ? "Yes" : "No");
break;
case TODO_ALARM_DATETIME:
printmsg("Alarm : %s\n",OSDateTime(ToDo->Entries[j].Date,false));
break;
case TODO_SILENT_ALARM_DATETIME:
printmsg("Silent alarm : %s\n",OSDateTime(ToDo->Entries[j].Date,false));
break;
case TODO_TEXT:
printmsg("Text : \"%s\"\n",DecodeUnicodeConsole(ToDo->Entries[j].Text));
break;
case TODO_PRIVATE:
printmsg("Private : %s\n",ToDo->Entries[j].Number == 1 ? "Yes" : "No");
break;
case TODO_CATEGORY:
Category.Location = ToDo->Entries[j].Number;
Category.Type = Category_ToDo;
error=Phone->GetCategory(&s, &Category);
if (error == ERR_NONE) {
printmsg("Category : \"%s\" (%i)\n", DecodeUnicodeConsole(Category.Name), ToDo->Entries[j].Number);
} else {
printmsg("Category : %i\n", ToDo->Entries[j].Number);
}
break;
case TODO_CONTACTID:
entry.Location = ToDo->Entries[j].Number;
entry.MemoryType = MEM_ME;
error=Phone->GetMemory(&s, &entry);
if (error == ERR_NONE) {
name = GSM_PhonebookGetEntryName(&entry);
if (name != NULL) {
printmsg("Contact ID : \"%s\" (%d)\n", DecodeUnicodeConsole(name), ToDo->Entries[j].Number);
} else {
printmsg("Contact ID : %d\n",ToDo->Entries[j].Number);
}
} else {
printmsg("Contact : %d\n",ToDo->Entries[j].Number);
}
break;
case TODO_PHONE:
printmsg("Phone : \"%s\"\n",DecodeUnicodeConsole(ToDo->Entries[j].Text));
break;
}
}
printf("\n");
}
static void ListToDoCategoryEntries(int Category)
{
GSM_ToDoEntry Entry;
bool start = true;
int j;
while (!gshutdown) {
error = Phone->GetNextToDo(&s, &Entry, start);
if (error == ERR_EMPTY) break;
Print_Error(error);
for (j=0;j<Entry.EntriesNum;j++) {
if (Entry.Entries[j].EntryType == TODO_CATEGORY && Entry.Entries[j].Number == (unsigned int)Category)
PrintToDo(&Entry);
}
start = false;
}
}
static void ListToDoCategory(int argc, char *argv[])
{
GSM_Category Category;
GSM_CategoryStatus Status;
int j, count;
unsigned char Text[(GSM_MAX_CATEGORY_NAME_LENGTH+1)*2];
int Length;
bool Number = true;;
GSM_Init(true);
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
Length = strlen(argv[2]);
for (j = 0; j < Length; j++) {
if (!isdigit(argv[2][j])) {
Number = false;
break;
}
}
if (Number) {
j = atoi(argv[2]);
if (j > 0) {
ListToDoCategoryEntries(j);
}
} else {
if (Length > GSM_MAX_CATEGORY_NAME_LENGTH) {
printmsg("Search text too long, truncating to %d chars!\n", GSM_MAX_CATEGORY_NAME_LENGTH);
Length = GSM_MAX_CATEGORY_NAME_LENGTH;
}
EncodeUnicode(Text, argv[2], Length);
Category.Type = Category_ToDo;
Status.Type = Category_ToDo;
if (Phone->GetCategoryStatus(&s, &Status) == ERR_NONE) {
for (count=0,j=1;count<Status.Used;j++) {
Category.Location=j;
error=Phone->GetCategory(&s, &Category);
if (error != ERR_EMPTY) {
count++;
if (mywstrstr(Category.Name, Text) != NULL) {
ListToDoCategoryEntries(j);
}
}
}
}
}
GSM_Terminate();
}
static void GetToDo(int argc, char *argv[])
{
GSM_ToDoEntry ToDo;
int i;
int start,stop;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
ToDo.Location=i;
error = Phone->GetToDo(&s,&ToDo);
if (error == ERR_EMPTY) continue;
Print_Error(error);
PrintToDo(&ToDo);
}
GSM_Terminate();
}
static void GetAllToDo(int argc, char *argv[])
{
GSM_ToDoEntry ToDo;
bool start = true;
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
GSM_Init(true);
while (!gshutdown) {
error = Phone->GetNextToDo(&s, &ToDo, start);
if (error == ERR_EMPTY) break;
Print_Error(error);
PrintToDo(&ToDo);
start = false;
}
GSM_Terminate();
}
static void GetAllNotes(int argc, char *argv[])
{
GSM_NoteEntry Note;
bool start = true;
signal(SIGINT, interrupt);
printmsgerr("Press Ctrl+C to break...\n");
GSM_Init(true);
while (!gshutdown) {
error = Phone->GetNextNote(&s, &Note, start);
if (error == ERR_EMPTY) break;
Print_Error(error);
printmsg("Text : \"%s\"\n",DecodeUnicodeConsole(Note.Text));
printf("\n");
start = false;
}
GSM_Terminate();
}
static void GetSecurityStatus(int argc, char *argv[])
{
GSM_Init(true);
PrintSecurityStatus();
GSM_Terminate();
}
static void EnterSecurityCode(int argc, char *argv[])
{
GSM_SecurityCode Code;
if (mystrncasecmp(argv[2],"PIN",0)) { Code.Type = SEC_Pin;
} else if (mystrncasecmp(argv[2],"PUK",0)) { Code.Type = SEC_Puk;
} else if (mystrncasecmp(argv[2],"PIN2",0)) { Code.Type = SEC_Pin2;
} else if (mystrncasecmp(argv[2],"PUK2",0)) { Code.Type = SEC_Puk2;
} else {
printmsg("What security code (\"%s\") ?\n",argv[2]);
exit(-1);
}
strcpy(Code.Code,argv[3]);
GSM_Init(true);
error=Phone->EnterSecurityCode(&s,Code);
Print_Error(error);
GSM_Terminate();
}
static void GetProfile(int argc, char *argv[])
{
GSM_Profile Profile;
int start,stop,j,k;
GSM_Bitmap caller[5];
bool callerinit[5],special;
GSM_AllRingtonesInfo Info;
GetStartStop(&start, &stop, 2, argc, argv);
for (i=0;i<5;i++) callerinit[i] = false;
GSM_Init(true);
error=Phone->GetRingtonesInfo(&s,&Info);
if (error != ERR_NONE) Info.Number = 0;
for (i=start;i<=stop;i++) {
Profile.Location=i;
error=Phone->GetProfile(&s,&Profile);
Print_Error(error);
printmsg("%i. \"%s\"",i,DecodeUnicodeConsole(Profile.Name));
if (Profile.Active) printmsg(" (active)");
if (Profile.DefaultName) printmsg(" (default name)");
if (Profile.HeadSetProfile) printmsg(" (HeadSet profile)");
if (Profile.CarKitProfile) printmsg(" (CarKit profile)");
printf("\n");
for (j=0;j<Profile.FeaturesNumber;j++) {
special = false;
switch (Profile.FeatureID[j]) {
case Profile_MessageToneID:
case Profile_RingtoneID:
special = true;
if (Profile.FeatureID[j] == Profile_RingtoneID) {
printmsg("Ringtone ID : ");
} else {
printmsg("Message alert tone ID : ");
}
if (UnicodeLength(GSM_GetRingtoneName(&Info,Profile.FeatureValue[j]))!=0) {
printmsg("\"%s\"\n",DecodeUnicodeConsole(GSM_GetRingtoneName(&Info,Profile.FeatureValue[j])));
} else {
printmsg("%i\n",Profile.FeatureValue[j]);
}
break;
case Profile_CallerGroups:
special = true;
printmsg("Call alert for :");
for (k=0;k<5;k++) {
if (Profile.CallerGroups[k]) {
if (!callerinit[k]) {
caller[k].Type = GSM_CallerGroupLogo;
caller[k].Location = k + 1;
error=Phone->GetBitmap(&s,&caller[k]);
if (error == ERR_SECURITYERROR) {
NOKIA_GetDefaultCallerGroupName(&s,&caller[k]);
} else {
Print_Error(error);
}
callerinit[k] = true;
}
printmsg(" \"%s\"",DecodeUnicodeConsole(caller[k].Text));
}
}
printf("\n");
break;
case Profile_ScreenSaverNumber:
special = true;
printmsg("Screen saver number : ");
printmsg("%i\n",Profile.FeatureValue[j]);
break;
case Profile_CallAlert : printmsg("Incoming call alert : "); break;
case Profile_RingtoneVolume : printmsg("Ringtone volume : "); break;
case Profile_Vibration : printmsg("Vibrating alert : "); break;
case Profile_MessageTone : printmsg("Message alert tone : "); break;
case Profile_KeypadTone : printmsg("Keypad tones : "); break;
case Profile_WarningTone : printmsg("Warning (games) tones : "); break;
case Profile_ScreenSaver : printmsg("Screen saver : "); break;
case Profile_ScreenSaverTime : printmsg("Screen saver timeout : "); break;
case Profile_AutoAnswer : printmsg("Automatic answer : "); break;
case Profile_Lights : printmsg("Lights : "); break;
default:
printmsg("Unknown\n");
special = true;
}
if (!special) {
switch (Profile.FeatureValue[j]) {
case PROFILE_VOLUME_LEVEL1 :
case PROFILE_KEYPAD_LEVEL1 : printmsg("Level 1\n"); break;
case PROFILE_VOLUME_LEVEL2 :
case PROFILE_KEYPAD_LEVEL2 : printmsg("Level 2\n"); break;
case PROFILE_VOLUME_LEVEL3 :
case PROFILE_KEYPAD_LEVEL3 : printmsg("Level 3\n"); break;
case PROFILE_VOLUME_LEVEL4 : printmsg("Level 4\n"); break;
case PROFILE_VOLUME_LEVEL5 : printmsg("Level 5\n"); break;
case PROFILE_MESSAGE_NOTONE :
case PROFILE_AUTOANSWER_OFF :
case PROFILE_LIGHTS_OFF :
case PROFILE_SAVER_OFF :
case PROFILE_WARNING_OFF :
case PROFILE_CALLALERT_OFF :
case PROFILE_VIBRATION_OFF :
case PROFILE_KEYPAD_OFF : printmsg("Off\n"); break;
case PROFILE_CALLALERT_RINGING : printmsg("Ringing\n"); break;
case PROFILE_CALLALERT_BEEPONCE :
case PROFILE_MESSAGE_BEEPONCE : printmsg("Beep once\n"); break;
case PROFILE_CALLALERT_RINGONCE : printmsg("Ring once\n"); break;
case PROFILE_CALLALERT_ASCENDING : printmsg("Ascending\n"); break;
case PROFILE_CALLALERT_CALLERGROUPS : printmsg("Caller groups\n"); break;
case PROFILE_MESSAGE_STANDARD : printmsg("Standard\n"); break;
case PROFILE_MESSAGE_SPECIAL : printmsg("Special\n"); break;
case PROFILE_MESSAGE_ASCENDING : printmsg("Ascending\n"); break;
case PROFILE_MESSAGE_PERSONAL : printmsg("Personal\n"); break;
case PROFILE_AUTOANSWER_ON :
case PROFILE_WARNING_ON :
case PROFILE_SAVER_ON :
case PROFILE_VIBRATION_ON : printmsg("On\n"); break;
case PROFILE_VIBRATION_FIRST : printmsg("Vibrate first\n"); break;
case PROFILE_LIGHTS_AUTO : printmsg("Auto\n"); break;
case PROFILE_SAVER_TIMEOUT_5SEC : printmsg("5 seconds\n"); break;
case PROFILE_SAVER_TIMEOUT_20SEC : printmsg("20 seconds\n"); break;
case PROFILE_SAVER_TIMEOUT_1MIN : printmsg("1 minute\n"); break;
case PROFILE_SAVER_TIMEOUT_2MIN : printmsg("2 minutes\n"); break;
case PROFILE_SAVER_TIMEOUT_5MIN : printmsg("5 minutes\n"); break;
case PROFILE_SAVER_TIMEOUT_10MIN : printmsg("10 minutes\n"); break;
default : printmsg("UNKNOWN\n");
}
}
}
printf("\n");
}
GSM_Terminate();
}
static void GetSpeedDial(int argc, char *argv[])
{
GSM_SpeedDial SpeedDial;
GSM_MemoryEntry Phonebook;
int start,stop,Name,Number,Group;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
SpeedDial.Location=i;
error=Phone->GetSpeedDial(&s,&SpeedDial);
printmsg("%i.",i);
switch (error) {
case ERR_EMPTY:
printmsg(" speed dial not assigned\n");
break;
default:
Print_Error(error);
Phonebook.Location = SpeedDial.MemoryLocation;
Phonebook.MemoryType = SpeedDial.MemoryType;
error=Phone->GetMemory(&s,&Phonebook);
GSM_PhonebookFindDefaultNameNumberGroup(&Phonebook, &Name, &Number, &Group);
if (Name != -1) printmsg(" Name \"%s\",",DecodeUnicodeConsole(Phonebook.Entries[Name].Text));
printmsg(" Number \"%s\"",DecodeUnicodeConsole(Phonebook.Entries[SpeedDial.MemoryNumberID-1].Text));
}
printf("\n");
}
GSM_Terminate();
}
static void ResetPhoneSettings(int argc, char *argv[])
{
GSM_ResetSettingsType Type;
if (mystrncasecmp(argv[2],"PHONE",0)) { Type = GSM_RESET_PHONESETTINGS;
} else if (mystrncasecmp(argv[2],"UIF",0)) { Type = GSM_RESET_USERINTERFACE;
} else if (mystrncasecmp(argv[2],"ALL",0)) { Type = GSM_RESET_USERINTERFACE_PHONESETTINGS;
} else if (mystrncasecmp(argv[2],"DEV",0)) { Type = GSM_RESET_DEVICE;
} else if (mystrncasecmp(argv[2],"FACTORY",0)) { Type = GSM_RESET_FULLFACTORY;
} else {
printmsg("What type of reset phone settings (\"%s\") ?\n",argv[2]);
exit(-1);
}
GSM_Init(true);
error=Phone->ResetPhoneSettings(&s,Type);
Print_Error(error);
GSM_Terminate();
}
#if defined(GSM_ENABLE_NOKIA_DCT3) || defined(GSM_ENABLE_NOKIA_DCT4)
static void NokiaSecurityCode(int argc, char *argv[])
{
GSM_Init(true);
#ifdef GSM_ENABLE_NOKIA_DCT3
DCT3GetSecurityCode(argc,argv);
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
// DCT4ResetSecurityCode(argc, argv);
DCT4GetSecurityCode(argc,argv);
#endif
GSM_Terminate();
}
static void NokiaSetPhoneMenus(int argc, char *argv[])
{
GSM_Init(true);
#ifdef GSM_ENABLE_NOKIA_DCT3
DCT3SetPhoneMenus (argc, argv);
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
DCT4SetPhoneMenus (argc, argv);
#endif
GSM_Terminate();
}
static void NokiaSelfTests(int argc, char *argv[])
{
GSM_Init(true);
#ifdef GSM_ENABLE_NOKIA_DCT3
DCT3SelfTests(argc, argv);
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
DCT4SelfTests(argc, argv);
#endif
GSM_Terminate();
}
#endif
static void DeleteAllSMS(int argc, char *argv[])
{
GSM_MultiSMSMessage sms;
GSM_SMSFolders folders;
int foldernum;
bool start = true;
GSM_Init(true);
error=Phone->GetSMSFolders(&s, &folders);
Print_Error(error);
GetStartStop(&foldernum, NULL, 2, argc, argv);
if (foldernum > folders.Number) {
printmsg("Too high folder number (max. %i)\n",folders.Number);
GSM_Terminate();
exit(-1);
}
printmsg("Deleting SMS from \"%s\" folder: ",DecodeUnicodeConsole(folders.Folder[foldernum-1].Name));
while (error == ERR_NONE) {
sms.SMS[0].Folder=0x00;
error=Phone->GetNextSMS(&s, &sms, start);
switch (error) {
case ERR_EMPTY:
break;
default:
Print_Error(error);
if (sms.SMS[0].Folder == foldernum) {
sms.SMS[0].Folder=0x00;
error=Phone->DeleteSMS(&s, &sms.SMS[0]);
Print_Error(error);
printmsg("*");
}
}
start=false;
}
printf("\n");
GSM_Terminate();
}
static void SendDTMF(int argc, char *argv[])
{
GSM_Init(true);
error=Phone->SendDTMF(&s,argv[2]);
Print_Error(error);
GSM_Terminate();
}
static void GetDisplayStatus(int argc, char *argv[])
{
GSM_DisplayFeatures Features;
int i;
GSM_Init(true);
error=Phone->GetDisplayStatus(&s,&Features);
Print_Error(error);
printmsg("Current display features :\n");
for (i=0;i<Features.Number;i++) {
switch(Features.Feature[i]) {
case GSM_CallActive : printmsg("Call active\n"); break;
case GSM_UnreadSMS : printmsg("Unread SMS\n"); break;
case GSM_VoiceCall : printmsg("Voice call\n"); break;
case GSM_FaxCall : printmsg("Fax call\n"); break;
case GSM_DataCall : printmsg("Data call\n"); break;
case GSM_KeypadLocked : printmsg("Keypad locked\n"); break;
case GSM_SMSMemoryFull : printmsg("SMS memory full\n");
}
}
GSM_Terminate();
}
static void SetAutoNetworkLogin(int argc, char *argv[])
{
GSM_Init(true);
error=Phone->SetAutoNetworkLogin(&s);
Print_Error(error);
GSM_Terminate();
}
#ifdef DEBUG
static void MakeConvertTable(int argc, char *argv[])
{
unsigned char InputBuffer[10000], Buffer[10000];
FILE *file;
int size,i,j=0;
file = fopen(argv[2], "rb");
if (file == NULL) Print_Error(ERR_CANTOPENFILE);
size=fread(InputBuffer, 1, 10000-1, file);
fclose(file);
InputBuffer[size] = 0;
InputBuffer[size+1] = 0;
ReadUnicodeFile(Buffer,InputBuffer);
for(i=0;i<((int)UnicodeLength(Buffer));i++) {
j++;
if (j==100) {
printf("\"\\\n\"");
j=0;
}
printf("\\x%02x\\x%02x",Buffer[i*2],Buffer[i*2+1]);
}
printf("\\x00\\x00");
}
#endif
static void ListNetworks(int argc, char *argv[])
{
extern unsigned char *GSM_Networks[];
extern unsigned char *GSM_Countries[];
int i=0;
char country[4]="";
if (argc>2) {
while (GSM_Countries[i*2]!=NULL) {
if (!strncmp(GSM_Countries[i*2+1],argv[2],strlen(argv[2]))) {
strcpy(country,GSM_Countries[i*2]);
printmsg("Networks for %s:\n\n",GSM_Countries[i*2+1]);
break;
}
i++;
}
if (!*country) {
printmsg("Unknown country name.");
exit(-1);
}
}
printmsg("Network Name\n");
i=0;
while (GSM_Networks[i*2]!=NULL) {
if (argc>2) {
if (!strncmp(GSM_Networks[i*2],country,strlen(country))) {
printmsg("%s %s\n", GSM_Networks[i*2], GSM_Networks[i*2+1]);
}
} else {
printmsg("%s %s\n", GSM_Networks[i*2], GSM_Networks[i*2+1]);
}
i++;
}
}
static void Version(int argc, char *argv[])
{
// unsigned char buff[10];
// int len;
printmsg("[Gammu version %s built %s %s",VERSION,__TIME__,__DATE__);
if (strlen(GetCompiler()) != 0) printmsg(" in %s",GetCompiler());
printmsg("]\n\n");
#ifdef DEBUG
printf("GSM_SMSMessage - %i\n",sizeof(GSM_SMSMessage));
printf("GSM_SMSC - %i\n",sizeof(GSM_SMSC));
printf("GSM_SMS_State - %i\n",sizeof(GSM_SMS_State));
printf("GSM_UDHHeader - %i\n",sizeof(GSM_UDHHeader));
printf("bool - %i\n",sizeof(bool));
printf("GSM_DateTime - %i\n",sizeof(GSM_DateTime));
printf("int - %i\n",sizeof(int));
printf("GSM_NetworkInfo - %i\n",sizeof(GSM_NetworkInfo));
#endif
// len=DecodeBASE64("AXw", buff, 3);
// DumpMessage(stdout, buff, len);
}
static void GetFMStation(int argc, char *argv[])
{
GSM_FMStation Station;
int start,stop;
GetStartStop(&start, &stop, 2, argc, argv);
GSM_Init(true);
for (i=start;i<=stop;i++) {
Station.Location=i;
error=Phone->GetFMStation(&s,&Station);
switch (error) {
case ERR_EMPTY:
printmsg("Entry number %i is empty\n",i);
break;
case ERR_NONE:
printmsg("Entry number %i\nStation name : \"%s\"\nFrequency : %.1f MHz\n",
i,DecodeUnicodeConsole(Station.StationName),
Station.Frequency);
break;
default:
Print_Error(error);
}
}
GSM_Terminate();
}
static void GetFileSystemStatus(int argc, char *argv[])
{
GSM_FileSystemStatus Status;
GSM_Init(true);
error = Phone->GetFileSystemStatus(&s,&Status);
if (error != ERR_NOTSUPPORTED && error != ERR_NOTIMPLEMENTED) {
Print_Error(error);
printmsg("\nFree memory: %i, total memory: %i\n",Status.Free,Status.Free+Status.Used);
}
GSM_Terminate();
}
static void GetFileSystem(int argc, char *argv[])
{
bool Start = true;
GSM_File Files;
int j;
GSM_FileSystemStatus Status;
char FolderName[256];
GSM_Init(true);
while (1) {
error = Phone->GetNextFileFolder(&s,&Files,Start);
if (error == ERR_EMPTY) break;
Print_Error(error);
if (argc <= 2 || !mystrncasecmp(argv[2],"-flatall",0)) {
if (strlen(Files.ID_FullName) < 5 && strlen(Files.ID_FullName) != 0) {
printf("%5s.",Files.ID_FullName);
}
if (Files.Protected) {
printf("P");
} else {
printf(" ");
}
if (Files.ReadOnly) {
printf("R");
} else {
printf(" ");
}
if (Files.Hidden) {
printf("H");
} else {
printf(" ");
}
if (Files.System) {
printf("S");
} else {
printf(" ");
}
if (argc > 2 && mystrncasecmp(argv[2],"-flat",0)) {
if (!Files.Folder) {
if (mystrncasecmp(argv[2],"-flatall",0)) {
if (!Files.ModifiedEmpty) {
printf(" %30s",OSDateTime(Files.Modified,false));
} else printf(" %30c",0x20);
printf(" %9i",Files.Used);
printf(" ");
} else printf("|-- ");
} else printf("Folder ");
} else {
if (Files.Level != 1) {
for (j=0;j<Files.Level-2;j++) printf(" | ");
printf(" |-- ");
}
if (Files.Folder) printf("Folder ");
}
printf("\"%s\"",DecodeUnicodeConsole(Files.Name));
} else if (argc > 2 && mystrncasecmp(argv[2],"-flatall",0)) {
/* format for a folder ID;Folder;FOLDER_NAME;[FOLDER_PARAMETERS]
* format for a file ID;File;FOLDER_NAME;FILE_NAME;DATESTAMP;FILE_SIZE;[FILE_PARAMETERS] */
if (!Files.Folder) {
printf("%s;File;",Files.ID_FullName);
printf("\"%s\";",FolderName);
printf("\"%s\";",DecodeUnicodeConsole(Files.Name));
if (!Files.ModifiedEmpty) {
printf("\"%s\";",OSDateTime(Files.Modified,false));
} else printf("\"%c\";",0x20);
printf("%i;",Files.Used);
} else {
printf("%s;Folder;",Files.ID_FullName);
printf("\"%s\";",DecodeUnicodeConsole(Files.Name));
strcpy(FolderName,DecodeUnicodeConsole(Files.Name));
}
if (Files.Protected) printf("P");
if (Files.ReadOnly) printf("R");
if (Files.Hidden) printf("H");
if (Files.System) printf("S");
}
Start = false;
}
error = Phone->GetFileSystemStatus(&s,&Status);
if (error != ERR_NOTSUPPORTED && error != ERR_NOTIMPLEMENTED) {
Print_Error(error);
printmsg("\nFree memory: %i, total memory: %i\n",Status.Free,Status.Free+Status.Used);
}
GSM_Terminate();
}
static void GetOneFile(GSM_File *File, bool newtime, int i)
{
FILE *file;
bool start;
unsigned char buffer[5000];
struct utimbuf filedate;
if (File->Buffer != NULL) {
free(File->Buffer);
File->Buffer = NULL;
}
File->Used = 0;
start = true;
error = ERR_NONE;
while (error == ERR_NONE) {
error = Phone->GetFilePart(&s,File);
if (error == ERR_NONE || error == ERR_EMPTY || error == ERR_WRONGCRC) {
if (start) {
printmsg("Getting \"%s\": ", DecodeUnicodeConsole(File->Name));
start = false;
}
if (File->Folder) {
free(File->Buffer);
GSM_Terminate();
printmsg("it's folder. Please give only file names\n");
exit(-1);
}
printmsg("*");
if (error == ERR_EMPTY) break;
if (error == ERR_WRONGCRC) {
printmsg("WARNING: File checksum calculated by phone doesn't match with value calculated by Gammu. File damaged or error in Gammu\n");
break;
}
}
Print_Error(error);
}
printf("\n");
if (File->Used != 0) {
sprintf(buffer,"%s",DecodeUnicodeConsole(File->Name));
file = fopen(buffer,"wb");
if (file == NULL) {
sprintf(buffer,"file%s",File->ID_FullName);
file = fopen(buffer,"wb");
}
if (file == NULL) {
sprintf(buffer,"file%i",i);
file = fopen(buffer,"wb");
}
printmsg(" Saving to %s\n",buffer);
if (!file) Print_Error(ERR_CANTOPENFILE);
fwrite(File->Buffer,1,File->Used,file);
fclose(file);
if (!newtime && !File->ModifiedEmpty) {
/* access time */
filedate.actime = Fill_Time_T(File->Modified, 8);
/* modification time */
filedate.modtime = Fill_Time_T(File->Modified, 8);
dbgprintf("Setting date of %s\n",buffer);
utime(buffer,&filedate);
}
}
}
static void GetFiles(int argc, char *argv[])
{
GSM_File File;
int i;
bool newtime = false;
File.Buffer = NULL;
GSM_Init(true);
for (i=2;i<argc;i++) {
if (mystrncasecmp(argv[i],"-newtime",0)) {
newtime = true;
continue;
}
strcpy(File.ID_FullName,argv[i]);
GetOneFile(&File, newtime, i);
}
free(File.Buffer);
GSM_Terminate();
}
static void GetFileFolder(int argc, char *argv[])
{
bool Start = true;
GSM_File File;
int level=0,allnum=0,num=0,filelevel=0;
bool newtime = false, found;
File.Buffer = NULL;
GSM_Init(true);
for (i=2;i<argc;i++) {
if (mystrncasecmp(argv[i],"-newtime",0)) {
newtime = true;
continue;
}
allnum++;
}
while (allnum != num) {
error = Phone->GetNextFileFolder(&s,&File,Start);
if (error == ERR_EMPTY) break;
Print_Error(error);
if (level == 0) {
/* We search for file or folder */
found = false;
for (i=2;i<argc;i++) {
if (mystrncasecmp(argv[i],"-newtime",0)) {
continue;
}
if (!strcmp(File.ID_FullName,argv[i])) {
found = true;
if (File.Folder) {
level = 1;
filelevel = File.Level + 1;
Start = false;
} else {
level = 2;
}
break;
}
}
if (found && File.Folder) continue;
}
if (level == 1) {
/* We have folder */
dbgprintf("%i %i\n",File.Level,filelevel);
if (File.Level != filelevel) {
level = 0;
num++;
}
}
if (level != 0 && !File.Folder) GetOneFile(&File, newtime,num);
if (level == 2) {
level = 0;
num++;
}
Start = false;
}
free(File.Buffer);
GSM_Terminate();
}
static void AddFile(int argc, char *argv[])
{
GSM_File File;
int Pos = 0,i,nextlong;
File.Buffer = NULL;
strcpy(File.ID_FullName,argv[2]);
error = GSM_ReadFile(argv[3], &File);
Print_Error(error);
EncodeUnicode(File.Name,argv[3],strlen(argv[3]));
GSM_IdentifyFileFormat(&File);
File.Protected = false;
File.ReadOnly = false;
File.Hidden = false;
File.System = false;
if (argc > 4) {
nextlong = 0;
for (i=4;i<argc;i++) {
switch(nextlong) {
case 0:
if (mystrncasecmp(argv[i],"-type",0)) {
nextlong = 1;
continue;
}
if (mystrncasecmp(argv[i],"-protected",0)) {
File.Protected = true;
continue;
}
if (mystrncasecmp(argv[i],"-readonly",0)) {
File.ReadOnly = true;
continue;
}
if (mystrncasecmp(argv[i],"-hidden",0)) {
File.Hidden = true;
continue;
}
if (mystrncasecmp(argv[i],"-system",0)) {
File.System = true;
continue;
}
if (mystrncasecmp(argv[i],"-newtime",0)) {
File.ModifiedEmpty = true;
continue;
}
printmsg("Parameter \"%s\" unknown\n",argv[i]);
exit(-1);
case 1:
if (mystrncasecmp(argv[i],"JAR",0)) {
File.Type = GSM_File_Java_JAR;
} else if (mystrncasecmp(argv[i],"JPG",0)) {
File.Type = GSM_File_Image_JPG;
} else if (mystrncasecmp(argv[i],"BMP",0)) {
File.Type = GSM_File_Image_BMP;
} else if (mystrncasecmp(argv[i],"WBMP",0)) {
File.Type = GSM_File_Image_WBMP;
} else if (mystrncasecmp(argv[i],"GIF",0)) {
File.Type = GSM_File_Image_GIF;
} else if (mystrncasecmp(argv[i],"PNG",0)) {
File.Type = GSM_File_Image_PNG;
} else if (mystrncasecmp(argv[i],"MIDI",0)) {
File.Type = GSM_File_Sound_MIDI;
} else if (mystrncasecmp(argv[i],"AMR",0)) {
File.Type = GSM_File_Sound_AMR;
} else if (mystrncasecmp(argv[i],"NRT",0)) {
File.Type = GSM_File_Sound_NRT;
} else if (mystrncasecmp(argv[i],"3GP",0)) {
File.Type = GSM_File_Video_3GP;
} else {
printmsg("What file type (\"%s\") ?\n",argv[i]);
exit(-1);
}
nextlong = 0;
break;
}
}
if (nextlong!=0) {
printmsg("Parameter missed...\n");
exit(-1);
}
}
GSM_Init(true);
error = ERR_NONE;
while (error == ERR_NONE) {
error = Phone->AddFilePart(&s,&File,&Pos);
if (error != ERR_EMPTY && error != ERR_WRONGCRC) Print_Error(error);
printmsgerr("%cWriting: %i percent",13,Pos*100/File.Used);
}
printmsgerr("\n");
if (error == ERR_WRONGCRC) {
printmsg("WARNING: File checksum calculated by phone doesn't match with value calculated by Gammu. File damaged or error in Gammu\n");
}
free(File.Buffer);
GSM_Terminate();
}
static void AddFolder(int argc, char *argv[])
{
GSM_File File;
strcpy(File.ID_FullName,argv[2]);
EncodeUnicode(File.Name,argv[3],strlen(argv[3]));
File.ReadOnly = false;
GSM_Init(true);
error = Phone->AddFolder(&s,&File);
Print_Error(error);
GSM_Terminate();
}
struct NokiaFolderInfo {
char *model;
char *parameter;
char *folder;
char *level;
};
static struct NokiaFolderInfo Folder[] = {
/* Language indepedent in DCT4 */
{"", "MMSUnreadInbox", "INBOX", "3"},
{"", "MMSReadInbox", "INBOX", "3"},
{"", "MMSOutbox", "OUTBOX", "3"},
{"", "MMSSent", "SENT", "3"},
{"", "MMSDrafts", "DRAFTS", "3"},
{"", "Application", "applications", "3"},
{"", "Game", "games", "3"},
/* Language depedent in DCT4 */
{"", "Gallery", "Pictures", "2"}, /* 3510 */
{"", "Gallery", "Graphics", "3"}, /* 3510i */
{"", "Gallery", "Images", "3"}, /* 6610 */
{"3510", "Gallery", "", "8"},
{"3510i","Gallery", "", "3"},
{"5100", "Gallery", "", "3"},
{"6220", "Gallery", "", "5"},
{"6610", "Gallery", "", "2"},
{"7210", "Gallery", "", "2"},
{"", "Tones", "Tones", "3"},
{"3510i","Tones", "", "4"},
{"5100", "Tones", "", "4"},
{"6220", "Tones", "", "6"},
{"6610", "Tones", "", "4"},
{"7210", "Tones", "", "4"},
/* Language indepedent in OBEX */
{"obex", "MMSUnreadInbox", "", "predefMessages\\predefINBOX" },
{"obex", "MMSReadInbox", "", "predefMessages\\predefINBOX" },
{"obex", "MMSOutbox", "", "predefMessages\\predefOUTBOX" },
{"obex", "MMSSent", "", "predefMessages\\predefSENT" },
{"obex", "MMSDrafts", "", "predefMessages\\predefDRAFTS" },
// {"obex", "Application, "", "predefjava\\predefapplications"},
// {"obex", "Game", "", "predefjava\\predefgames" },
{"obex", "Gallery", "", "predefgallery\\predefgraphics" },
{"obex", "Tones", "", "predefgallery\\predeftones" },
/* End of list */
{"", "", "", ""}
};
static void NokiaAddFile(int argc, char *argv[])
{
GSM_File File, Files;
FILE *file;
GSM_DateTime DT,DT2;
time_t t_time1,t_time2;
unsigned char buffer[10000],JAR[500],Vendor[500],Name[500],Version[500],FileID[400];
bool Start = true, Found = false, wasclr;
bool ModEmpty = false;
int i = 0, Pos, Size, Size2, nextlong;
while (Folder[i].level[0] != 0) {
if (mystrncasecmp(argv[2],Folder[i].parameter,0)) {
Found = true;
break;
}
i++;
}
if (!Found) {
printmsg("What folder type (\"%s\") ?\n",argv[2]);
exit(-1);
}
GSM_Init(true);
if (s.ConnectionType == GCT_IRDAOBEX || s.ConnectionType == GCT_BLUEOBEX) {
Found = false;
i = 0;
while (Folder[i].level[0] != 0) {
if (!strcmp("obex",Folder[i].model) &&
mystrncasecmp(argv[2],Folder[i].parameter,0)) {
strcpy(Files.ID_FullName,Folder[i].level);
Found = true;
break;
}
i++;
}
} else {
printmsgerr("Searching for phone folder: ");
while (1) {
error = Phone->GetNextFileFolder(&s,&Files,Start);
if (error == ERR_EMPTY) break;
Print_Error(error);
if (Files.Folder) {
dbgprintf("folder %s level %i\n",DecodeUnicodeConsole(Files.Name),Files.Level);
Found = false;
i = 0;
while (Folder[i].level[0] != 0) {
EncodeUnicode(buffer,Folder[i].folder,strlen(Folder[i].folder));
dbgprintf("comparing \"%s\" \"%s\" \"%s\"\n",s.Phone.Data.ModelInfo->model,Files.ID_FullName,Folder[i].level);
if (mystrncasecmp(argv[2],Folder[i].parameter,0) &&
mywstrncasecmp(Files.Name,buffer,0) &&
Files.Level == atoi(Folder[i].level)) {
Found = true;
break;
}
if (!strcmp(s.Phone.Data.ModelInfo->model,Folder[i].model) &&
mystrncasecmp(argv[2],Folder[i].parameter,0) &&
!strcmp(Files.ID_FullName,Folder[i].level)) {
Found = true;
break;
}
i++;
}
if (Found) break;
}
printmsgerr("*");
Start = false;
}
printmsgerr("\n");
}
if (!Found) {
printmsg("Folder not found. Probably function not supported !\n");
GSM_Terminate();
exit(-1);
}
File.Buffer = NULL;
File.Protected = false;
File.ReadOnly = false;
File.Hidden = false;
File.System = false;
if (mystrncasecmp(argv[2],"Application",0) || mystrncasecmp(argv[2],"Game",0)) {
sprintf(buffer,"%s.jad",argv[3]);
file = fopen(buffer,"rb");
if (file == NULL) Print_Error(ERR_CANTOPENFILE);
fclose(file);
sprintf(buffer,"%s.jar",argv[3]);
file = fopen(buffer,"rb");
if (file == NULL) Print_Error(ERR_CANTOPENFILE);
fclose(file);
/* reading jar file */
sprintf(buffer,"%s.jar",argv[3]);
error = GSM_ReadFile(buffer, &File);
Print_Error(error);
Size2 = File.Used;
/* reading jad file */
sprintf(buffer,"%s.jad",argv[3]);
error = GSM_ReadFile(buffer, &File);
Print_Error(error);
/* Getting values from JAD file */
error = GSM_JADFindData(File, Vendor, Name, JAR, Version, &Size);
if (error == ERR_FILENOTSUPPORTED) {
if (Vendor[0] == 0x00) {
printmsgerr("No vendor info in JAD file\n");
GSM_Terminate();
return;
}
if (Name[0] == 0x00) {
printmsgerr("No name info in JAD file\n");
GSM_Terminate();
return;
}
if (JAR[0] == 0x00) {
printmsgerr("No JAR URL info in JAD file\n");
GSM_Terminate();
return;
}
if (Size == -1) {
printmsgerr("No JAR size info in JAD file\n");
GSM_Terminate();
return;
}
}
if (Size != Size2) {
printmsgerr("Declared JAR file size is different than real\n");
GSM_Terminate();
return;
}
printmsgerr("Adding \"%s\"",Name);
if (Version[0] != 0x00) printmsgerr(" version %s",Version);
printmsgerr(" created by %s\n",Vendor);
/* Bostjan Muller 3200 RH-30 3.08 */
if (strstr(JAR,"http://") != NULL) {
i = strlen(JAR)-1;
while (JAR[i] != '/') i--;
strcpy(buffer,JAR+i+1);
strcpy(JAR,buffer);
dbgprintf("New file name is \"%s\"\n",JAR);
}
/* Changing all #13 or #10 to #13#10 in JAD */
Pos = 0;
wasclr = false;
for (i=0;i<File.Used;i++) {
switch (File.Buffer[i]) {
case 0x0D:
case 0x0A:
if (!wasclr) {
buffer[Pos++] = 0x0D;
buffer[Pos++] = 0x0A;
wasclr = true;
} else wasclr = false;
break;
default:
buffer[Pos++] = File.Buffer[i];
wasclr = false;
}
}
File.Buffer = realloc(File.Buffer, Pos);
File.Used = Pos;
memcpy(File.Buffer,buffer,Pos);
/* adding folder */
strcpy(buffer,Vendor);
strcat(buffer,Name);
EncodeUnicode(File.Name,buffer,strlen(buffer));
strcpy(File.ID_FullName,Files.ID_FullName);
error = Phone->AddFolder(&s,&File);
Print_Error(error);
strcpy(FileID,File.ID_FullName);
/* adding jad file */
strcpy(buffer,JAR);
buffer[strlen(buffer) - 1] = 'd';
EncodeUnicode(File.Name,buffer,strlen(buffer));
File.Type = GSM_File_Other;
File.ModifiedEmpty = true;
error = ERR_NONE;
Pos = 0;
while (error == ERR_NONE) {
error = Phone->AddFilePart(&s,&File,&Pos);
if (error != ERR_EMPTY && error != ERR_WRONGCRC) Print_Error(error);
printmsgerr("%cWriting JAD file: %i percent",13,Pos*100/File.Used);
}
printmsgerr("\n");
if (error == ERR_WRONGCRC) {
printmsg("WARNING: File checksum calculated by phone doesn't match with value calculated by Gammu. File damaged or error in Gammu\n");
}
if (argc > 4) {
if (mystrncasecmp(argv[4],"-readonly",0)) File.ReadOnly = true;
}
/* reading jar file */
sprintf(buffer,"%s.jar",argv[3]);
error = GSM_ReadFile(buffer, &File);
Print_Error(error);
/* adding jar file */
strcpy(File.ID_FullName,FileID);
strcpy(buffer,JAR);
EncodeUnicode(File.Name,buffer,strlen(buffer));
File.Type = GSM_File_Java_JAR;
File.ModifiedEmpty = true;
error = ERR_NONE;
Pos = 0;
while (error == ERR_NONE) {
error = Phone->AddFilePart(&s,&File,&Pos);
if (error != ERR_EMPTY && error != ERR_WRONGCRC) Print_Error(error);
printmsgerr("%cWriting JAR file: %i percent",13,Pos*100/File.Used);
}
printmsgerr("\n");
if (error == ERR_WRONGCRC) {
printmsg("WARNING: File checksum calculated by phone doesn't match with value calculated by Gammu. File damaged or error in Gammu\n");
}
free(File.Buffer);
GSM_Terminate();
return;
}
if (mystrncasecmp(argv[2],"Gallery",0) || mystrncasecmp(argv[2],"Tones",0)) {
strcpy(buffer,argv[3]);
if (argc > 4) {
nextlong = 0;
for (i=4;i<argc;i++) {
switch(nextlong) {
case 0:
if (mystrncasecmp(argv[i],"-name",0)) {
nextlong = 1;
continue;
}
if (mystrncasecmp(argv[i],"-protected",0)) {
File.Protected = true;
continue;
}
if (mystrncasecmp(argv[i],"-readonly",0)) {
File.ReadOnly = true;
continue;
}
if (mystrncasecmp(argv[i],"-hidden",0)) {
File.Hidden = true;
continue;
}
if (mystrncasecmp(argv[i],"-system",0)) {
File.System = true;
continue;
}
if (mystrncasecmp(argv[i],"-newtime",0)) {
ModEmpty = true;
continue;
}
printmsg("Parameter \"%s\" unknown\n",argv[i]);
exit(-1);
case 1:
strcpy(buffer,argv[i]);
nextlong = 0;
break;
}
}
if (nextlong!=0) {
printmsg("Parameter missed...\n");
exit(-1);
}
}
} else { /* MMS things */
DT2.Year = 2001;
DT2.Month = 12;
DT2.Day = 31;
DT2.Hour = 14;
DT2.Minute = 00;
DT2.Second = 00;
t_time2 = Fill_Time_T(DT2,8);
GSM_GetCurrentDateTime(&DT);
t_time1 = Fill_Time_T(DT,8);
sprintf(buffer,"%07X %07X ",(int)(t_time1-t_time2-40),(int)(t_time1-t_time2-40));
#ifdef DEVELOP
sprintf(buffer,"2A947BD 2A947DB ");
#endif
/* 40 = inbox "multimedia message received" message */
/* 30 = outbox sending failed */
if (mystrncasecmp(argv[2],"MMSUnreadInbox",0)) strcat(buffer,"43 ");
else if (mystrncasecmp(argv[2],"MMSReadInbox",0)) strcat(buffer,"50 ");
else if (mystrncasecmp(argv[2],"MMSOutbox",0)) strcat(buffer,"10 ");
else if (mystrncasecmp(argv[2],"MMSSent",0)) strcat(buffer,"20 ");
else if (mystrncasecmp(argv[2],"MMSDrafts",0)) strcat(buffer,"61 ");
if (argc > 4) {
if (!mystrncasecmp(argv[2],"MMSOutbox",0) &&
!mystrncasecmp(argv[2],"MMSSent",0)) {
sprintf(Name,"%s",argv[4]);
strcat(buffer,Name);
}
if (argc > 5) {
sprintf(Name,"%zd%s/TYPE=PLMN",strlen(argv[5])+10,argv[5]);
strcat(buffer,Name);
}
}
ModEmpty = true;
}
error = GSM_ReadFile(argv[3], &File);
Print_Error(error);
if (ModEmpty) File.ModifiedEmpty = true;
strcpy(File.ID_FullName,Files.ID_FullName);
EncodeUnicode(File.Name,buffer,strlen(buffer));
GSM_IdentifyFileFormat(&File);
#ifdef DEVELOP
if (mystrncasecmp(argv[2],"Gallery",0) || mystrncasecmp(argv[2],"Tones",0)) {
} else { /* MMS things */
File.Type = GSM_File_MMS;
}
#endif
dbgprintf("Adding file to filesystem now\n");
error = ERR_NONE;
Pos = 0;
while (error == ERR_NONE) {
error = Phone->AddFilePart(&s,&File,&Pos);
if (error != ERR_EMPTY && error != ERR_WRONGCRC) Print_Error(error);
if (File.Used != 0) printmsgerr("%cWriting file: %i percent",13,Pos*100/File.Used);
}
printmsgerr("\n");
if (error == ERR_WRONGCRC) {
printmsg("WARNING: File checksum calculated by phone doesn't match with value calculated by Gammu. File damaged or error in Gammu\n");
}
free(File.Buffer);
GSM_Terminate();
}
static void DeleteFiles(int argc, char *argv[])
{
int i;
GSM_Init(true);
for (i=2;i<argc;i++) {
error = Phone->DeleteFile(&s,argv[i]);
Print_Error(error);
}
GSM_Terminate();
}
static void SaveMMSFile(int argc, char *argv[])
{
FILE *file;
unsigned char Buffer[50000],Buffer2[20][2010];
int i,nextlong = 0,len = 0;
GSM_EncodeMultiPartMMSInfo Info;
GSM_ClearMultiPartMMSInfo(&Info);
for (i=3;i<argc;i++) {
switch (nextlong) {
case 0:
if (mystrncasecmp(argv[i],"-subject",0)) {
nextlong=1;
continue;
}
if (mystrncasecmp(argv[i],"-text",0)) {
nextlong=2;
continue;
}
if (mystrncasecmp(argv[i],"-from",0)) {
nextlong=3;
continue;
}
if (mystrncasecmp(argv[i],"-to",0)) {
nextlong=4;
continue;
}
printmsg("Unknown parameter (\"%s\")\n",argv[i]);
exit(-1);
break;
case 1: /* Subject */
EncodeUnicode(Info.Subject,argv[i],strlen(argv[i]));
nextlong = 0;
break;
case 2: /* Text */
EncodeUnicode(Buffer2[Info.EntriesNum],argv[i],strlen(argv[i]));
Info.Entries[Info.EntriesNum].ID = MMS_Text;
Info.Entries[Info.EntriesNum].Buffer = Buffer2[Info.EntriesNum];
Info.EntriesNum++;
nextlong = 0;
break;
case 3: /* From */
EncodeUnicode(Info.Source,argv[i],strlen(argv[i]));
nextlong = 0;
break;
case 4: /* To */
EncodeUnicode(Info.Destination,argv[i],strlen(argv[i]));
nextlong = 0;
break;
}
}
if (nextlong!=0) {
printmsg("Parameter missed...\n");
exit(-1);
}
GSM_EncodeMMSFile(&Info,Buffer,&len);
file = fopen(argv[2],"wb");
if (file == NULL) Print_Error(ERR_CANTOPENFILE);
fwrite(Buffer,1,len,file);
fclose(file);
}
static void CallDivert(int argc, char *argv[])
{
GSM_MultiCallDivert cd;
if (mystrncasecmp("get", argv[2],0)) {}
else if (mystrncasecmp("set", argv[2],0)) {}
else {
printmsg("Unknown divert action (\"%s\")\n",argv[2]);
exit(-1);
}
if (mystrncasecmp("all" , argv[3],0)) {cd.Request.DivertType = GSM_DIVERT_AllTypes ;}
else if (mystrncasecmp("busy" , argv[3],0)) {cd.Request.DivertType = GSM_DIVERT_Busy ;}
else if (mystrncasecmp("noans" , argv[3],0)) {cd.Request.DivertType = GSM_DIVERT_NoAnswer ;}
else if (mystrncasecmp("outofreach", argv[3],0)) {cd.Request.DivertType = GSM_DIVERT_OutOfReach;}
else {
printmsg("Unknown divert type (\"%s\")\n",argv[3]);
exit(-1);
}
if (mystrncasecmp("all" , argv[4],0)) {cd.Request.CallType = GSM_DIVERT_AllCalls ;}
else if (mystrncasecmp("voice", argv[4],0)) {cd.Request.CallType = GSM_DIVERT_VoiceCalls;}
else if (mystrncasecmp("fax" , argv[4],0)) {cd.Request.CallType = GSM_DIVERT_FaxCalls ;}
else if (mystrncasecmp("data" , argv[4],0)) {cd.Request.CallType = GSM_DIVERT_DataCalls ;}
else {
printmsg("Unknown call type (\"%s\")\n",argv[4]);
exit(-1);
}
GSM_Init(true);
if (mystrncasecmp("get", argv[2],0)) {
error = Phone->GetCallDivert(&s,&cd);
Print_Error(error);
printmsg("Query:\n Divert type: ");
} else {
cd.Request.Number[0] = 0;
cd.Request.Number[1] = 0;
if (argc > 5) EncodeUnicode(cd.Request.Number,argv[5],strlen(argv[5]));
cd.Request.Timeout = 0;
if (argc > 6) cd.Request.Timeout = atoi(argv[6]);
error = Phone->SetCallDivert(&s,&cd);
Print_Error(error);
printmsg("Changed:\n Divert type: ");
}
switch (cd.Request.DivertType) {
case GSM_DIVERT_Busy : printmsg("when busy"); break;
case GSM_DIVERT_NoAnswer : printmsg("when not answered"); break;
case GSM_DIVERT_OutOfReach: printmsg("when phone off or no coverage"); break;
case GSM_DIVERT_AllTypes : printmsg("all types of diverts"); break;
default : printmsg("unknown %i",cd.Request.DivertType); break;
}
printmsg("\n Calls type : ");
switch (cd.Request.CallType) {
case GSM_DIVERT_VoiceCalls: printmsg("voice"); break;
case GSM_DIVERT_FaxCalls : printmsg("fax"); break;
case GSM_DIVERT_DataCalls : printmsg("data"); break;
case GSM_DIVERT_AllCalls : printmsg("data & fax & voice"); break;
default : printmsg("unknown %i",cd.Request.CallType); break;
}
printmsg("\nResponse:");
for (i=0;i<cd.Response.EntriesNum;i++) {
printmsg("\n Calls type : ");
switch (cd.Response.Entries[i].CallType) {
case GSM_DIVERT_VoiceCalls: printmsg("voice"); break;
case GSM_DIVERT_FaxCalls : printmsg("fax"); break;
case GSM_DIVERT_DataCalls : printmsg("data"); break;
default : printmsg("unknown %i",cd.Response.Entries[i].CallType);break;
}
printf("\n");
printmsg(" Timeout : %i seconds\n",cd.Response.Entries[i].Timeout);
printmsg(" Number : %s\n",DecodeUnicodeString(cd.Response.Entries[i].Number));
}
printf("\n");
GSM_Terminate();
}
static void CancelAllDiverts(int argc, char *argv[])
{
GSM_Init(true);
error = Phone->CancelAllDiverts(&s);
Print_Error(error);
GSM_Terminate();
}
typedef struct {
unsigned char Connection[50];
} OneConnectionInfo;
typedef struct {
unsigned char Device[50];
OneConnectionInfo Connections[4];
} OneDeviceInfo;
int num;
bool SearchOutput;
void SearchPhoneThread(OneDeviceInfo *Info)
{
//LR
#if 0
int j;
GSM_Error error;
GSM_StateMachine ss;
j = 0;
while(strlen(Info->Connections[j].Connection) != 0) {
memcpy(&ss.di,&s.di,sizeof(Debug_Info));
ss.msg = s.msg;
ss.ConfigNum = 1;
ss.opened = false;
ss.Config[0].UseGlobalDebugFile = s.Config[0].UseGlobalDebugFile;
ss.Config[0].Localize = s.Config[0].Localize;
ss.Config[0].Device = Info->Device;
ss.Config[0].Connection = Info->Connections[j].Connection;
ss.Config[0].SyncTime = "no";
ss.Config[0].DebugFile = s.Config[0].DebugFile;
ss.Config[0].Model[0] = 0;
strcpy(ss.Config[0].DebugLevel,s.Config[0].DebugLevel);
ss.Config[0].LockDevice = "no";
ss.Config[0].StartInfo = "no";
error = GSM_InitConnection(&ss,1);
if (SearchOutput) printf("Connection \"%s\" on device \"%s\"\n",Info->Connections[j].Connection,Info->Device);
if (error == ERR_NONE) {
error=ss.Phone.Functions->GetManufacturer(&ss);
if (error == ERR_NONE) {
error=ss.Phone.Functions->GetModel(&ss);
if (error == ERR_NONE) {
if (!SearchOutput) printf("Connection \"%s\" on device \"%s\"\n",Info->Connections[j].Connection,Info->Device);
printmsg(" Manufacturer : %s\n",
ss.Phone.Data.Manufacturer);
printmsg(" Model : %s (%s)\n",
ss.Phone.Data.ModelInfo->model,
ss.Phone.Data.Model);
} else {
if (SearchOutput) printf(" %s\n",print_error(error,ss.di.df,ss.msg));
}
} else {
if (SearchOutput) printf(" %s\n",print_error(error,ss.di.df,ss.msg));
}
} else {
if (SearchOutput) printf(" %s\n",print_error(error,ss.di.df,ss.msg));
}
if (error != ERR_DEVICEOPENERROR) {
GSM_TerminateConnection(&ss);
dbgprintf("Closing done\n");
}
if (error == ERR_DEVICEOPENERROR) break;
j++;
}
num--;
#endif
}
#if defined(WIN32) || defined(HAVE_PTHREAD)
#ifdef HAVE_PTHREAD
pthread_t Thread[100];
#endif
OneDeviceInfo SearchDevices[60];
void MakeSearchThread(int i)
{
num++;
#ifdef HAVE_PTHREAD
if (pthread_create(&Thread[i],NULL,(void *)SearchPhoneThread,&SearchDevices[i])!=0) {
dbgprintf("Error creating thread\n");
}
#else
if (CreateThread((LPSECURITY_ATTRIBUTES)NULL,0,
(LPTHREAD_START_ROUTINE)SearchPhoneThread,&SearchDevices[i],
0,NULL)==NULL) {
dbgprintf("Error creating thread\n");
}
#endif
}
static void SearchPhone(int argc, char *argv[])
{
int i,dev = 0, dev2 = 0;
SearchOutput = false;
if (argc == 3 && mystrncasecmp(argv[2], "-debug",0)) SearchOutput = true;
num = 0;
#ifdef WIN32
# ifdef GSM_ENABLE_IRDADEVICE
sprintf(SearchDevices[dev].Device,"");
sprintf(SearchDevices[dev].Connections[0].Connection,"irdaphonet");
sprintf(SearchDevices[dev].Connections[1].Connection,"irdaat");
SearchDevices[dev].Connections[2].Connection[0] = 0;
dev++;
# endif
# ifdef GSM_ENABLE_SERIALDEVICE
dev2 = dev;
for(i=0;i<20;i++) {
sprintf(SearchDevices[dev2].Device,"com%i:",i+1);
sprintf(SearchDevices[dev2].Connections[0].Connection,"fbusdlr3");
sprintf(SearchDevices[dev2].Connections[1].Connection,"fbus");
sprintf(SearchDevices[dev2].Connections[2].Connection,"at19200");
sprintf(SearchDevices[dev2].Connections[3].Connection,"mbus");
SearchDevices[dev2].Connections[4].Connection[0] = 0;
dev2++;
}
# endif
#endif
#ifdef __linux__
# ifdef GSM_ENABLE_IRDADEVICE
for(i=0;i<6;i++) {
sprintf(SearchDevices[dev].Device,"/dev/ircomm%i",i);
sprintf(SearchDevices[dev].Connections[0].Connection,"irdaphonet");
sprintf(SearchDevices[dev].Connections[1].Connection,"at19200");
SearchDevices[dev].Connections[2].Connection[0] = 0;
dev++;
}
# endif
# ifdef GSM_ENABLE_SERIALDEVICE
dev2 = dev;
for(i=0;i<10;i++) {
sprintf(SearchDevices[dev2].Device,"/dev/ttyS%i",i);
sprintf(SearchDevices[dev2].Connections[0].Connection,"fbusdlr3");
sprintf(SearchDevices[dev2].Connections[1].Connection,"fbus");
sprintf(SearchDevices[dev2].Connections[2].Connection,"at19200");
sprintf(SearchDevices[dev2].Connections[3].Connection,"mbus");
SearchDevices[dev2].Connections[4].Connection[0] = 0;
dev2++;
}
for(i=0;i<8;i++) {
sprintf(SearchDevices[dev2].Device,"/dev/ttyD00%i",i);
sprintf(SearchDevices[dev2].Connections[0].Connection,"fbusdlr3");
sprintf(SearchDevices[dev2].Connections[1].Connection,"fbus");
sprintf(SearchDevices[dev2].Connections[2].Connection,"at19200");
sprintf(SearchDevices[dev2].Connections[3].Connection,"mbus");
SearchDevices[dev2].Connections[4].Connection[0] = 0;
dev2++;
}
for(i=0;i<4;i++) {
sprintf(SearchDevices[dev2].Device,"/dev/usb/tts/%i",i);
sprintf(SearchDevices[dev2].Connections[0].Connection,"fbusdlr3");
sprintf(SearchDevices[dev2].Connections[1].Connection,"fbus");
sprintf(SearchDevices[dev2].Connections[2].Connection,"at19200");
sprintf(SearchDevices[dev2].Connections[3].Connection,"mbus");
SearchDevices[dev2].Connections[4].Connection[0] = 0;
dev2++;
}
# endif
#endif
for(i=0;i<dev;i++) MakeSearchThread(i);
while (num != 0) my_sleep(5);
for(i=dev;i<dev2;i++) MakeSearchThread(i);
while (num != 0) my_sleep(5);
}
#endif /*Support for threads */
static void NokiaGetADC(int argc, char *argv[])
{
GSM_Init(true);
#ifdef GSM_ENABLE_NOKIA_DCT3
DCT3GetADC(argc,argv);
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
DCT4GetADC(argc, argv);
#endif
GSM_Terminate();
}
static void NokiaDisplayTest(int argc, char *argv[])
{
GSM_Init(true);
#ifdef GSM_ENABLE_NOKIA_DCT3
DCT3DisplayTest(argc,argv);
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
DCT4DisplayTest(argc, argv);
#endif
GSM_Terminate();
}
static void NokiaGetT9(int argc, char *argv[])
{
GSM_Init(true);
#ifdef GSM_ENABLE_NOKIA_DCT3
DCT3GetT9(argc,argv);
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
DCT4GetT9(argc, argv);
#endif
GSM_Terminate();
}
static void NokiaVibraTest(int argc, char *argv[])
{
GSM_Init(true);
#ifdef GSM_ENABLE_NOKIA_DCT3
DCT3VibraTest(argc,argv);
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
DCT4VibraTest(argc, argv);
#endif
GSM_Terminate();
}
static GSM_Parameters Parameters[] = {
{"--identify", 0, 0, Identify, {H_Info,0}, ""},
{"--version", 0, 0, Version, {H_Other,0}, ""},
{"--getdisplaystatus", 0, 0, GetDisplayStatus, {H_Info,0}, ""},
{"--monitor", 0, 1, Monitor, {H_Info,H_Network,H_Call,0}, "[times]"},
{"--setautonetworklogin", 0, 0, SetAutoNetworkLogin, {H_Network,0}, ""},
{"--listnetworks", 0, 1, ListNetworks, {H_Network,0}, "[country]"},
{"--getgprspoint", 1, 2, GetGPRSPoint, {H_Nokia,H_Network,0}, "start [stop]"},
{"--addfolder", 2, 2, AddFolder, {H_Filesystem,0}, "parentfolderID name"},
{"--getfilesystem", 0, 1, GetFileSystem, {H_Filesystem,0}, "[-flatall|-flat]"},
{"--getfilesystemstatus", 0, 0, GetFileSystemStatus, {H_Filesystem,0}, ""},
{"--getfiles", 1,40, GetFiles, {H_Filesystem,0}, "ID1, ID2, ..."},
{"--getfilefolder", 1,40, GetFileFolder, {H_Filesystem,0}, "ID1, ID2, ..."},
{"--addfile", 2, 6, AddFile, {H_Filesystem,0}, "folderID name [-type JAR|BMP|PNG|GIF|JPG|MIDI|WBMP|AMR|3GP|NRT][-readonly][-protected][-system][-hidden][-newtime]"},
{"--nokiaaddfile", 2, 5, NokiaAddFile, {H_Filesystem,H_Nokia,0}, "MMSUnreadInbox|MMSReadInbox|MMSOutbox|MMSDrafts|MMSSent file sender title"},
{"--nokiaaddfile", 2, 5, NokiaAddFile, {H_Filesystem,H_Nokia,0}, "Application|Game file [-readonly]"},
{"--nokiaaddfile", 2, 5, NokiaAddFile, {H_Filesystem,H_Nokia,0}, "Gallery|Tones file [-name name][-protected][-readonly][-system][-hidden][-newtime]"},
{"--deletefiles", 1,20, DeleteFiles, {H_Filesystem,0}, "fileID"},
{"--playringtone", 1, 1, PlayRingtone, {H_Ringtone,0}, "file"},
{"--playsavedringtone", 1, 1, DCT4PlaySavedRingtone, {H_Ringtone,0}, ""},
{"--getdatetime", 0, 0, GetDateTime, {H_DateTime,0}, ""},
{"--setdatetime", 0, 0, SetDateTime, {H_DateTime,0}, ""},
{"--getalarm", 0, 0, GetAlarm, {H_DateTime,0}, ""},
{"--setalarm", 2, 2, SetAlarm, {H_DateTime,0}, "hour minute"},
{"--resetphonesettings", 1, 1, ResetPhoneSettings, {H_Settings,0}, "PHONE|DEV|UIF|ALL|FACTORY"},
{"--getmemory", 2, 4, GetMemory, {H_Memory,0}, "DC|MC|RC|ON|VM|SM|ME|FD start [stop [-nonempty]]"},
{"--getallmemory", 1, 2, GetAllMemory, {H_Memory,0}, "DC|MC|RC|ON|VM|SM|ME|FD"},
{"--searchmemory", 1, 1, SearchMemory, {H_Memory,0}, "text"},
{"--listmemorycategory", 1, 1, ListMemoryCategory, {H_Memory, H_Category,0}, "text|number"},
{"--getfmstation", 1, 2, GetFMStation, {H_FM,0}, "start [stop]"},
{"--getsmsc", 1, 2, GetSMSC, {H_SMS,0}, "start [stop]"},
{"--getsms", 2, 3, GetSMS, {H_SMS,0}, "folder start [stop]"},
{"--deletesms", 2, 3, DeleteSMS, {H_SMS,0}, "folder start [stop]"},
{"--deleteallsms", 1, 1, DeleteAllSMS, {H_SMS,0}, "folder"},
{"--getsmsfolders", 0, 0, GetSMSFolders, {H_SMS,0}, ""},
{"--getallsms", 0, 0, GetAllSMS, {H_SMS,0}, ""},
{"--geteachsms", 0, 0, GetEachSMS, {H_SMS,0}, ""},
#define SMS_TEXT_OPTIONS "[-inputunicode][-16bit][-flash][-len len][-autolen len][-unicode][-enablevoice][-disablevoice][-enablefax][-disablefax][-enableemail][-disableemail][-voidsms][-replacemessages ID][-replacefile file]"
#define SMS_PICTURE_OPTIONS "[-text text][-unicode][-alcatelbmmi]"
#define SMS_PROFILE_OPTIONS "[-name name][-bitmap bitmap][-ringtone ringtone]"
#define SMS_EMS_OPTIONS "[-unicode][-16bit][-format lcrasbiut][-text text][-unicodefiletext file][-defsound ID][-defanimation ID][-tone10 file][-tone10long file][-tone12 file][-tone12long file][-toneSE file][-toneSElong file][-fixedbitmap file][-variablebitmap file][-variablebitmaplong file][-animation frames file1 ...][-protected number]"
#define SMS_SMSTEMPLATE_OPTIONS "[-unicode][-text text][-unicodefiletext file][-defsound ID][-defanimation ID][-tone10 file][-tone10long file][-tone12 file][-tone12long file][-toneSE file][-toneSElong file][-variablebitmap file][-variablebitmaplong file][-animation frames file1 ...]"
#define SMS_ANIMATION_OPTIONS ""
#define SMS_OPERATOR_OPTIONS "[-netcode netcode][-biglogo]"
#define SMS_SAVE_OPTIONS "[-folder id][-unread][-read][-unsent][-sent][-sender number]"
#define SMS_SEND_OPTIONS "[-report][-validity HOUR|6HOURS|DAY|3DAYS|WEEK|MAX][-save [-folder number]]"
#define SMS_COMMON_OPTIONS "[-smscset number][-smscnumber number][-reply][-maxsms num]"
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,0}, "TEXT " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS SMS_TEXT_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_Ringtone,0}, "RINGTONE file " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_Logo,0}, "OPERATOR file " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS SMS_OPERATOR_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_Logo,0}, "CALLER file " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_Logo,0}, "PICTURE file " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS SMS_PICTURE_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_Logo,0}, "ANIMATION frames file1 file2... " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS SMS_ANIMATION_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_MMS,0}, "MMSINDICATOR URL Title Sender " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_WAP,0}, "WAPINDICATOR URL Title " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
#ifdef GSM_ENABLE_BACKUP
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_WAP,0}, "BOOKMARK file location " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_WAP,0}, "WAPSETTINGS file location DATA|GPRS " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_MMS,0}, "MMSSETTINGS file location " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_Calendar,0}, "CALENDAR file location " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_ToDo,0}, "TODO file location " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_Memory,0}, "VCARD10|VCARD21 file SM|ME location [-nokia]" SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS},
#endif
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,H_Settings,0}, "PROFILE " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS SMS_PROFILE_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,0}, "EMS " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS SMS_EMS_OPTIONS},
{"--savesms", 1,30, SendSaveDisplaySMS, {H_SMS,0}, "SMSTEMPLATE " SMS_SAVE_OPTIONS SMS_COMMON_OPTIONS SMS_SMSTEMPLATE_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,0}, "TEXT destination " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS SMS_TEXT_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_Ringtone,0}, "RINGTONE destination file " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_Logo,0}, "OPERATOR destination file " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS SMS_OPERATOR_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_Logo,0}, "CALLER destination file " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_Logo,0}, "PICTURE destination file " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS SMS_PICTURE_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_Logo,0}, "ANIMATION destination frames file1 file2... " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS SMS_ANIMATION_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_MMS,0}, "MMSINDICATOR destination URL Title Sender " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_WAP,0}, "WAPINDICATOR destination URL Title " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
#ifdef GSM_ENABLE_BACKUP
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_WAP,0}, "BOOKMARK destination file location " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_WAP,0}, "WAPSETTINGS destination file location DATA|GPRS " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_MMS,0}, "MMSSETTINGS destination file location " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_Calendar,0}, "CALENDAR destination file location " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_ToDo,0}, "TODO destination file location " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_Memory,0}, "VCARD10|VCARD21 destination file SM|ME location [-nokia]" SMS_SEND_OPTIONS SMS_COMMON_OPTIONS},
#endif
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_Settings,0}, "PROFILE destination " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS ""SMS_PROFILE_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,0}, "EMS destination " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS SMS_EMS_OPTIONS},
{"--sendsms", 2,30, SendSaveDisplaySMS, {H_SMS,0}, "SMSTEMPLATE destination " SMS_SEND_OPTIONS SMS_COMMON_OPTIONS SMS_SMSTEMPLATE_OPTIONS},
{"--displaysms", 2,30, SendSaveDisplaySMS, {H_SMS,0}, "... (options like in sendsms)"},
{"--addsmsfolder", 1, 1, AddSMSFolder, {H_SMS,0}, "name"},
#ifdef HAVE_MYSQL_MYSQL_H
{"--smsd", 2, 2, SMSDaemon, {H_SMS,H_Other,0}, "MYSQL configfile"},
#endif
{"--smsd", 2, 2, SMSDaemon, {H_SMS,H_Other,0}, "FILES configfile"},
{"--sendsmsdsms", 2,30, SendSaveDisplaySMS, {H_SMS,H_Other,0}, "TEXT|WAPSETTINGS|... destination FILES|MYSQL configfile ... (options like in sendsms)"},
{"--getringtone", 1, 2, GetRingtone, {H_Ringtone,0}, "location [file]"},
{"--getphoneringtone", 1, 2, GetRingtone, {H_Ringtone,0}, "location [file]"},
{"--getringtoneslist", 0, 0, GetRingtonesList, {H_Ringtone,0}, ""},
{"--setringtone", 1, 6, SetRingtone, {H_Ringtone,0}, "file [-location location][-scale][-name name]"},
{"--nokiacomposer", 1, 1, NokiaComposer, {H_Ringtone,H_Nokia,0}, "file"},
{"--copyringtone", 2, 3, CopyRingtone, {H_Ringtone,0}, "source destination [RTTL|BINARY]"},
{"--getussd", 1, 1, GetUSSD, {H_Call,0}, "code"},
{"--dialvoice", 1, 2, DialVoice, {H_Call,0}, "number [show|hide]"},
{"--getspeeddial", 1, 2, GetSpeedDial, {H_Call,H_Memory,0}, "start [stop]"},
{"--cancelcall", 0, 1, CancelCall, {H_Call,0}, "[ID]"},
{"--answercall", 0, 1, AnswerCall, {H_Call,0}, "[ID]"},
{"--unholdcall", 1, 1, UnholdCall, {H_Call,0}, "ID"},
{"--holdcall", 1, 1, HoldCall, {H_Call,0}, "ID"},
{"--conferencecall", 1, 1, ConferenceCall, {H_Call,0}, "ID"},
{"--splitcall", 1, 1, SplitCall, {H_Call,0}, "ID"},
{"--switchcall", 0, 1, SwitchCall, {H_Call,0}, "[ID]"},
{"--transfercall", 0, 1, TransferCall, {H_Call,0}, "[ID]"},
{"--divert", 3, 5, CallDivert, {H_Call,0}, "get|set all|busy|noans|outofreach all|voice|fax|data [number timeout]"},
{"--canceldiverts", 0, 0, CancelAllDiverts, {H_Call,0}, ""},
{"--senddtmf", 1, 1, SendDTMF, {H_Call,0}, "sequence"},
{"--getcalendarsettings", 0, 0, GetCalendarSettings, {H_Calendar,H_Settings,0}, ""},
{"--getalltodo", 0, 0, GetAllToDo, {H_ToDo,0}, ""},
{"--listtodocategory", 1, 1, ListToDoCategory, {H_ToDo, H_Category,0}, "text|number"},
{"--gettodo", 1, 2, GetToDo, {H_ToDo,0}, "start [stop]"},
{"--deletetodo", 1, 2, DeleteToDo, {H_ToDo,0}, "start [stop]"},
{"--getallnotes", 0, 0, GetAllNotes, {H_Note,0}, ""},
{"--deletecalendar", 1, 2, DeleteCalendar, {H_Calendar,0}, "start [stop]"},
{"--getallcalendar", 0, 0, GetAllCalendar, {H_Calendar,0}, ""},
{"--getcalendar", 1, 2, GetCalendar, {H_Calendar,0}, "start [stop]"},
{"--getcategory", 2, 3, GetCategory, {H_Category,H_ToDo,H_Memory,0}, "TODO|PHONEBOOK start [stop]"},
{"--getallcategory", 1, 1, GetAllCategories, {H_Category,H_ToDo,H_Memory,0}, "TODO|PHONEBOOK"},
{"--reset", 1, 1, Reset, {H_Other,0}, "SOFT|HARD"},
{"--getprofile", 1, 2, GetProfile, {H_Settings,0}, "start [stop]"},
{"--getsecuritystatus", 0, 0, GetSecurityStatus, {H_Info,0}, ""},
{"--entersecuritycode", 2, 2, EnterSecurityCode, {H_Other,0}, "PIN|PUK|PIN2|PUK2 code"},
{"--deletewapbookmark", 1, 2, DeleteWAPBookmark, {H_WAP,0}, "start [stop]"},
{"--getwapbookmark", 1, 2, GetWAPBookmark, {H_WAP,0}, "start [stop]"},
{"--getwapsettings", 1, 2, GetWAPMMSSettings, {H_WAP,0}, "start [stop]"},
{"--getmmssettings", 1, 2, GetWAPMMSSettings, {H_MMS,0}, "start [stop]"},
{"--getsyncmlsettings", 1, 2, GetSyncMLSettings, {H_WAP,0}, "start [stop]"},
{"--getchatsettings", 1, 2, GetChatSettings, {H_WAP,0}, "start [stop]"},
{"--savemmsfile", 3, 15,SaveMMSFile, {H_MMS,0}, "file [-subject text][-text text]"},
{"--getbitmap", 1, 3, GetBitmap, {H_Logo,0}, "STARTUP [file]"},
{"--getbitmap", 1, 3, GetBitmap, {H_Logo,0}, "CALLER location [file]"},
{"--getbitmap", 1, 3, GetBitmap, {H_Logo,0}, "OPERATOR [file]"},
{"--getbitmap", 1, 3, GetBitmap, {H_Logo,0}, "PICTURE location [file]"},
{"--getbitmap", 1, 3, GetBitmap, {H_Logo,0}, "TEXT"},
{"--getbitmap", 1, 3, GetBitmap, {H_Logo,0}, "DEALER"},
{"--setbitmap", 1, 4, SetBitmap, {H_Logo,0}, "STARTUP file|1|2|3"},
{"--setbitmap", 1, 4, SetBitmap, {H_Logo,0}, "COLOURSTARTUP [fileID]"},
{"--setbitmap", 1, 4, SetBitmap, {H_Logo,0}, "WALLPAPER fileID"},
{"--setbitmap", 1, 4, SetBitmap, {H_Logo,0}, "CALLER location [file]"},
{"--setbitmap", 1, 4, SetBitmap, {H_Logo,0}, "OPERATOR [file [netcode]]"},
{"--setbitmap", 1, 4, SetBitmap, {H_Logo,0}, "COLOUROPERATOR [fileID [netcode]]"},
{"--setbitmap", 1, 4, SetBitmap, {H_Logo,0}, "PICTURE file location [text]"},
{"--setbitmap", 1, 4, SetBitmap, {H_Logo,0}, "TEXT text"},
{"--setbitmap", 1, 4, SetBitmap, {H_Logo,0}, "DEALER text"},
{"--copybitmap", 1, 3, CopyBitmap, {H_Logo,0}, "inputfile [outputfile [OPERATOR|PICTURE|STARTUP|CALLER]]"},
{"--presskeysequence", 1, 1, PressKeySequence, {H_Other,0}, "mMnNpPuUdD+-123456789*0#gGrRwW"},
#if defined(WIN32) || defined(HAVE_PTHREAD)
{"--searchphone", 0, 1, SearchPhone, {H_Other,0}, "[-debug]"},
#endif
#ifdef GSM_ENABLE_BACKUP
{"--savefile", 4, 5, SaveFile, {H_Backup,H_Calendar,0}, "CALENDAR target.vcs file location"},
{"--savefile", 4, 5, SaveFile, {H_Backup,H_ToDo,0}, "TODO target.vcs file location"},
{"--savefile", 4, 5, SaveFile, {H_Backup,H_Memory,0}, "VCARD10|VCARD21 target.vcf file SM|ME location"},
{"--savefile", 4, 5, SaveFile, {H_Backup,H_WAP,0}, "BOOKMARK target.url file location"},
{"--backup", 1, 2, Backup, {H_Backup,H_Memory,H_Calendar,H_ToDo,H_Category,H_Ringtone,H_WAP,H_FM,0}, "file [-yes]"},
{"--backupsms", 1, 1, BackupSMS, {H_Backup,H_SMS,0}, "file"},
{"--restore", 1, 1, Restore, {H_Backup,H_Memory,H_Calendar,H_ToDo,H_Category,H_Ringtone,H_WAP,H_FM,0}, "file"},
{"--addnew", 1, 1, AddNew, {H_Backup,H_Memory,H_Calendar,H_ToDo,H_Category,H_Ringtone,H_WAP,H_FM,0}, "file"},
{"--restoresms", 1, 1, RestoreSMS, {H_Backup,H_SMS,0}, "file"},
{"--addsms", 2, 2, AddSMS, {H_Backup,H_SMS,0}, "folder file"},
#endif
{"--clearall", 0, 0, ClearAll, {H_Memory,H_Calendar,H_ToDo,H_Category,H_Ringtone,H_WAP,H_FM,0}, ""},
{"--networkinfo", 0, 0, NetworkInfo, {H_Network,0}, ""},
#ifdef GSM_ENABLE_AT
{"--siemenssatnetmon", 0, 0, ATSIEMENSSATNetmon, {H_Siemens,H_Network,0}, ""},
{"--siemensnetmonact", 1, 1, ATSIEMENSActivateNetmon, {H_Siemens,H_Network,0}, "netmon_type (1-full, 2-simple)"},
{"--siemensnetmonitor", 1, 1, ATSIEMENSNetmonitor, {H_Siemens,H_Network,0}, "test"},
#endif
#ifdef GSM_ENABLE_NOKIA6110
{"--nokiagetoperatorname", 0, 0, DCT3GetOperatorName, {H_Nokia,H_Network,0}, ""},
{"--nokiasetoperatorname", 0, 2, DCT3SetOperatorName, {H_Nokia,H_Network,0}, "[networkcode name]"},
{"--nokiadisplayoutput", 0, 0, DCT3DisplayOutput, {H_Nokia,0}, ""},
#endif
#ifdef GSM_ENABLE_NOKIA_DCT3
{"--nokianetmonitor", 1, 1, DCT3netmonitor, {H_Nokia,H_Network,0}, "test"},
{"--nokianetmonitor36", 0, 0, DCT3ResetTest36, {H_Nokia,0}, ""},
{"--nokiadebug", 1, 2, DCT3SetDebug, {H_Nokia,H_Network,0}, "filename [[v11-22][,v33-44]...]"},
#endif
#ifdef GSM_ENABLE_NOKIA_DCT4
{"--nokiasetvibralevel", 1, 1, DCT4SetVibraLevel, {H_Nokia,H_Other,0}, "level"},
{"--nokiagetvoicerecord", 1, 1, DCT4GetVoiceRecord, {H_Nokia,H_Other,0}, "location"},
#ifdef GSM_ENABLE_NOKIA6510
{"--nokiasetlights", 2, 2, DCT4SetLight, {H_Nokia,H_Tests,0}, "keypad|display|torch on|off"},
{"--nokiatuneradio", 0, 0, DCT4TuneRadio, {H_Nokia,H_FM,0}, ""},
#endif
{"--nokiamakecamerashoot", 0, 0, DCT4MakeCameraShoot, {H_Nokia,H_Other,0}, ""},
{"--nokiagetscreendump", 0, 0, DCT4GetScreenDump, {H_Nokia,H_Other,0}, ""},
#endif
#if defined(GSM_ENABLE_NOKIA_DCT3) || defined(GSM_ENABLE_NOKIA_DCT4)
{"--nokiavibratest", 0, 0, NokiaVibraTest, {H_Nokia,H_Tests,0}, ""},
{"--nokiagett9", 0, 0, NokiaGetT9, {H_Nokia,H_SMS,0}, ""},
{"--nokiadisplaytest", 1, 1, NokiaDisplayTest, {H_Nokia,H_Tests,0}, "number"},
{"--nokiagetadc", 0, 0, NokiaGetADC, {H_Nokia,H_Tests,0}, ""},
{"--nokiasecuritycode", 0, 0, NokiaSecurityCode, {H_Nokia,H_Info,0}, ""},
{"--nokiaselftests", 0, 0, NokiaSelfTests, {H_Nokia,H_Tests,0}, ""},
{"--nokiasetphonemenus", 0, 0, NokiaSetPhoneMenus, {H_Nokia,H_Other,0}, ""},
#endif
#ifdef DEBUG
{"--decodesniff", 2, 3, decodesniff, {H_Decode,0}, "MBUS2|IRDA file [phonemodel]"},
{"--decodebinarydump", 1, 2, decodebinarydump, {H_Decode,0}, "file [phonemodel]"},
{"--makeconverttable", 1, 1, MakeConvertTable, {H_Decode,0}, "file"},
#endif
{"", 0, 0, NULL }
};
static HelpCategoryDescriptions HelpDescriptions[] = {
{H_Call, "call", "Calls",},
{H_SMS, "sms", "SMS and EMS"},
{H_Memory, "memory", "Memory (phonebooks and calls)"},
{H_Filesystem, "filesystem", "Filesystem"},
{H_Logo, "logo", "Logo and pictures"},
{H_Ringtone, "ringtone", "Ringtones"},
{H_Calendar, "calendar", "Calendar notes"},
{H_ToDo, "todo", "To do lists"},
{H_Note, "note", "Notes"},
{H_DateTime, "datetime", "Date, time and alarms"},
{H_Category, "category", "Categories"},
#ifdef GSM_ENABLE_BACKUP
{H_Backup, "backup", "Backing up and restoring"},
#endif
#if defined(GSM_ENABLE_NOKIA_DCT3) || defined(GSM_ENABLE_NOKIA_DCT4)
{H_Nokia, "nokia", "Nokia specific"},
#endif
#ifdef GSM_ENABLE_AT
{H_Siemens, "siemens", "Siemens specific"},
#endif
{H_Network, "network", "Network"},
{H_WAP, "wap", "WAP settings and bookmarks"},
{H_MMS, "mms", "MMS and MMS settings"},
{H_Tests, "tests", "Phone tests"},
{H_FM, "fm", "FM radio"},
{H_Info, "info", "Phone information"},
{H_Settings, "settings", "Phone settings"},
#ifdef DEBUG
{H_Decode, "decode", "Dumps decoding"},
#endif
{H_Other, "other", "Functions that don't fit elsewhere"},
{0, NULL, NULL}
};
void HelpHeader(void)
{
printmsg("[Gammu version %s built %s %s]\n\n",VERSION,__TIME__,__DATE__);
}
static void HelpGeneral(void)
{
int i=0;
HelpHeader();
printmsg("Usage: gammu [confign] [nothing|text|textall|binary|errors] [options]\n\n");
printmsg("First parameter optionally specifies which config section to use (all are probed by default).\n");
printmsg("Second parameter optionally controls debug level, next one specifies actions.\n\n");
/* We might want to put here some most used commands */
printmsg("For more details, call help on specific topic (gammu --help topic). Topics are:\n\n");
while (HelpDescriptions[i].category != 0) {
printf("%11s - %s\n", HelpDescriptions[i].option, HelpDescriptions[i].description);
i++;
}
printf("\n");
}
static void HelpSplit(int cols, int len, unsigned char *buff)
{
int l, len2, pos, split;
bool in_opt,first=true;
char *remain, spaces[50], buffer[500];
if (cols == 0) {
printf(" %s\n", buff);
} else {
printf(" ");
spaces[0] = 0;
len2 = strlen(buff);
if (len + len2 < cols) {
printf("%s\n", buff);
} else {
for(l = 0; l < len; l++) strcat(spaces, " ");
remain = buff;
while (strlen(remain) > 0) {
split = 0;
pos = 0;
in_opt = false;
if (!first) printf(spaces);
while (pos < cols - len && remain[pos] != 0) {
if (in_opt && remain[pos] == ']') {
in_opt = false;
split = pos;
} else if (remain[pos] == '[') {
in_opt = true;
} else if (!in_opt && remain[pos] == ' ') {
split = pos - 1;
}
pos++;
}
/* Can not be split */
if (split == 0) {
printf("%s\n", remain);
remain += strlen(remain);
} else {
first = false;
split++;
strncpy(buffer, remain, split);
buffer[split] = 0;
printf("%s\n", buffer);
remain += split;
if (remain[0] == ' ') remain++;
}
}
}
}
}
static void Help(int argc, char *argv[])
{
int i = 0, j = 0, k, cols;
bool disp;
#ifdef TIOCGWINSZ
struct winsize w;
#endif
#if defined(WIN32) || defined(DJGPP)
#else
char *columns;
#endif
/* Just --help */
if (argc == 2) {
HelpGeneral();
return;
}
if (!strcmp(argv[2],"all")) {
HelpHeader();
} else {
while (HelpDescriptions[i].category != 0) {
if (mystrncasecmp(argv[2], HelpDescriptions[i].option,strlen(argv[2]))) break;
i++;
}
if (HelpDescriptions[i].category == 0) {
HelpGeneral();
printmsg("Unknown help topic specified!\n");
return;
}
HelpHeader();
printmsg("Gammu parameters, topic: %s\n\n", HelpDescriptions[i].description);
}
#if defined(WIN32) || defined(DJGPP)
cols = 80;
#else
cols = 0;
/* If stdout is a tty, we will wrap to columns it has */
if (isatty(1)) {
#ifdef TIOCGWINSZ
if (ioctl(2, TIOCGWINSZ, &w) == 0) {
if (w.ws_col > 0) cols = w.ws_col;
}
#endif
if (cols == 0) {
columns = getenv("COLUMNS");
if (columns != NULL) {
cols = atoi(columns);
if (cols <= 0) cols = 0;
}
}
if (cols == 0) {
/* Fallback */
cols = 80;
}
}
#endif
while (Parameters[j].Function != NULL) {
k = 0;
disp = false;
if (!strcmp(argv[2],"all")) {
if (j==0) disp = true;
if (j!=0) {
if (strcmp(Parameters[j].help,Parameters[j-1].help)) {
disp = true;
} else {
if (strcmp(Parameters[j].parameter,Parameters[j-1].parameter)) {
disp = true;
}
}
}
} else {
while (Parameters[j].help_cat[k] != 0) {
if (Parameters[j].help_cat[k] == HelpDescriptions[i].category) {
disp = true;
break;
}
k++;
}
}
if (disp) {
printf("%s", Parameters[j].parameter);
if (Parameters[j].help[0] == 0) {
printf("\n");
} else {
HelpSplit(cols - 1, strlen(Parameters[j].parameter) + 1, Parameters[j].help);
}
}
j++;
}
}
int main(int argc, char *argv[])
{
int z = 0,start=0,i;
int only_config = -1;
#if !defined(WIN32) && !defined(DJGPP) && defined(LOCALE_PATH)
char *locale, locale_file[201];
#endif
char *cp;
bool count_failed = false;
s.opened = false;
s.msg = NULL;
s.ConfigNum = 0;
setlocale(LC_ALL, "");
#ifdef DEBUG
di.dl = DL_TEXTALL;
di.df = stdout;
#endif
/* Any parameters? */
if (argc == 1) {
HelpGeneral();
printmsg("Too few parameters!\n");
exit(1);
}
/* Help? */
if (strncmp(argv[1 + start], "--help", 6) == 0) {
Help(argc - start, argv + start);
exit(1);
}
/* Is first parameter numeric? If so treat it as config that should be loaded. */
if (isdigit(argv[1][0])) {
only_config = atoi(argv[1]);
if (only_config >= 0) start++; else only_config = -1;
}
cfg = GSM_FindGammuRC();
if (cfg == NULL) printmsg("Warning: No configuration file found!\n");
for (i = 0; i <= MAX_CONFIG_NUM; i++) {
if (cfg!=NULL) {
cp = INI_GetValue(cfg, "gammu", "gammucoding", false);
if (cp) di.coding = cp;
s.Config[i].Localize = INI_GetValue(cfg, "gammu", "gammuloc", false);
if (s.Config[i].Localize) {
s.msg=INI_ReadFile(s.Config[i].Localize, true);
} else {
#if !defined(WIN32) && !defined(DJGPP) && defined(LOCALE_PATH)
locale = setlocale(LC_MESSAGES, NULL);
if (locale != NULL) {
snprintf(locale_file, 200, "%s/gammu_%c%c.txt",
LOCALE_PATH,
tolower(locale[0]),
tolower(locale[1]));
s.msg = INI_ReadFile(locale_file, true);
}
#endif
}
}
/* Wanted user specific configuration? */
if (only_config != -1) {
/* Here we get only in first for loop */
if (!GSM_ReadConfig(cfg, &s.Config[0], only_config)) break;
} else {
if (!GSM_ReadConfig(cfg, &s.Config[i], i) && i != 0) break;
}
s.ConfigNum++;
/* We want to use only one file descriptor for global and state machine debug output */
s.Config[i].UseGlobalDebugFile = true;
/* It makes no sense to open several debug logs... */
if (i != 0) {
strcpy(s.Config[i].DebugLevel, s.Config[0].DebugLevel);
free(s.Config[i].DebugFile);
s.Config[i].DebugFile = strdup(s.Config[0].DebugFile);
} else {
/* Just for first config */
/* When user gave debug level on command line */
if (argc > 1 + start && GSM_SetDebugLevel(argv[1 + start], &di)) {
/* Debug level from command line will be used with phone too */
strcpy(s.Config[i].DebugLevel,argv[1 + start]);
start++;
} else {
/* Try to set debug level from config file */
GSM_SetDebugLevel(s.Config[i].DebugLevel, &di);
}
/* If user gave debug file in gammurc, we will use it */
error=GSM_SetDebugFile(s.Config[i].DebugFile, &di);
Print_Error(error);
}
/* We wanted to read just user specified configuration. */
if (only_config != -1) {break;}
}
/* Do we have enough parameters? */
if (argc == 1 + start) {
HelpGeneral();
printmsg("Too few parameters!\n");
exit(-2);
}
/* Check used version vs. compiled */
if (!mystrncasecmp(GetGammuVersion(),VERSION,0)) {
printmsg("ERROR: version of installed libGammu.so (%s) is different to version of Gammu (%s)\n",
GetGammuVersion(),VERSION);
exit(-1);
}
/* Check parameters */
while (Parameters[z].Function != NULL) {
if (mystrncasecmp(Parameters[z].parameter,argv[1+start], 0)) {
if (argc-2-start >= Parameters[z].min_arg && argc-2-start <= Parameters[z].max_arg) {
Parameters[z].Function(argc - start, argv + start);
break;
} else {
count_failed = true;
}
}
z++;
}
/* Tell user when we did nothing */
if (Parameters[z].Function == NULL) {
HelpGeneral();
if (count_failed) {
printmsg("Bad parameter count!\n");
} else {
printmsg("Bad option!\n");
}
}
/* Close debug output if opened */
if (di.df!=stdout) fclose(di.df);
exit(0);
}
/* How should editor hadle tabs in this file? Add editor commands here.
* vim: noexpandtab sw=8 ts=8 sts=8:
*/
diff --git a/kabc/addressbook.cpp b/kabc/addressbook.cpp
index d037d2f..ad0f702 100644
--- a/kabc/addressbook.cpp
+++ b/kabc/addressbook.cpp
@@ -1,1076 +1,1198 @@
/*
This file is part of libkabc.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/*
Enhanced Version of the file for platform independent KDE tools.
Copyright (c) 2004 Ulf Schenk
$Id$
*/
/*US
#include <qfile.h>
#include <qregexp.h>
#include <qtimer.h>
#include <kapplication.h>
#include <kinstance.h>
#include <kstandarddirs.h>
#include "errorhandler.h"
*/
#include <qptrlist.h>
#include <qtextstream.h>
#include <qfile.h>
#include <qregexp.h>
#include <kglobal.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <libkcal/syncdefines.h>
#include <libkdepim/phoneaccess.h>
#include "addressbook.h"
#include "resource.h"
#include "vcardconverter.h"
#include "vcardparser/vcardtool.h"
//US #include "addressbook.moc"
using namespace KABC;
struct AddressBook::AddressBookData
{
Addressee::List mAddressees;
Addressee::List mRemovedAddressees;
Field::List mAllFields;
KConfig *mConfig;
KRES::Manager<Resource> *mManager;
//US ErrorHandler *mErrorHandler;
};
struct AddressBook::Iterator::IteratorData
{
Addressee::List::Iterator mIt;
};
struct AddressBook::ConstIterator::ConstIteratorData
{
Addressee::List::ConstIterator mIt;
};
AddressBook::Iterator::Iterator()
{
d = new IteratorData;
}
AddressBook::Iterator::Iterator( const AddressBook::Iterator &i )
{
d = new IteratorData;
d->mIt = i.d->mIt;
}
AddressBook::Iterator &AddressBook::Iterator::operator=( const AddressBook::Iterator &i )
{
if( this == &i ) return *this; // guard against self assignment
delete d; // delete the old data the Iterator was completely constructed before
d = new IteratorData;
d->mIt = i.d->mIt;
return *this;
}
AddressBook::Iterator::~Iterator()
{
delete d;
}
const Addressee &AddressBook::Iterator::operator*() const
{
return *(d->mIt);
}
Addressee &AddressBook::Iterator::operator*()
{
return *(d->mIt);
}
Addressee *AddressBook::Iterator::operator->()
{
return &(*(d->mIt));
}
AddressBook::Iterator &AddressBook::Iterator::operator++()
{
(d->mIt)++;
return *this;
}
AddressBook::Iterator &AddressBook::Iterator::operator++(int)
{
(d->mIt)++;
return *this;
}
AddressBook::Iterator &AddressBook::Iterator::operator--()
{
(d->mIt)--;
return *this;
}
AddressBook::Iterator &AddressBook::Iterator::operator--(int)
{
(d->mIt)--;
return *this;
}
bool AddressBook::Iterator::operator==( const Iterator &it )
{
return ( d->mIt == it.d->mIt );
}
bool AddressBook::Iterator::operator!=( const Iterator &it )
{
return ( d->mIt != it.d->mIt );
}
AddressBook::ConstIterator::ConstIterator()
{
d = new ConstIteratorData;
}
AddressBook::ConstIterator::ConstIterator( const AddressBook::ConstIterator &i )
{
d = new ConstIteratorData;
d->mIt = i.d->mIt;
}
AddressBook::ConstIterator &AddressBook::ConstIterator::operator=( const AddressBook::ConstIterator &i )
{
if( this == &i ) return *this; // guard for self assignment
delete d; // delete the old data because the Iterator was really constructed before
d = new ConstIteratorData;
d->mIt = i.d->mIt;
return *this;
}
AddressBook::ConstIterator::~ConstIterator()
{
delete d;
}
const Addressee &AddressBook::ConstIterator::operator*() const
{
return *(d->mIt);
}
const Addressee* AddressBook::ConstIterator::operator->() const
{
return &(*(d->mIt));
}
AddressBook::ConstIterator &AddressBook::ConstIterator::operator++()
{
(d->mIt)++;
return *this;
}
AddressBook::ConstIterator &AddressBook::ConstIterator::operator++(int)
{
(d->mIt)++;
return *this;
}
AddressBook::ConstIterator &AddressBook::ConstIterator::operator--()
{
(d->mIt)--;
return *this;
}
AddressBook::ConstIterator &AddressBook::ConstIterator::operator--(int)
{
(d->mIt)--;
return *this;
}
bool AddressBook::ConstIterator::operator==( const ConstIterator &it )
{
return ( d->mIt == it.d->mIt );
}
bool AddressBook::ConstIterator::operator!=( const ConstIterator &it )
{
return ( d->mIt != it.d->mIt );
}
AddressBook::AddressBook()
{
init(0, "contact");
}
AddressBook::AddressBook( const QString &config )
{
init(config, "contact");
}
AddressBook::AddressBook( const QString &config, const QString &family )
{
init(config, family);
}
// the default family is "contact"
void AddressBook::init(const QString &config, const QString &family )
{
blockLSEchange = false;
d = new AddressBookData;
QString fami = family;
if (config != 0) {
if ( family == "syncContact" ) {
qDebug("creating sync config ");
fami = "contact";
KConfig* con = new KConfig( locateLocal("config", "syncContactrc") );
con->setGroup( "General" );
con->writeEntry( "ResourceKeys", QString("sync") );
con->writeEntry( "Standard", QString("sync") );
con->setGroup( "Resource_sync" );
con->writeEntry( "FileName", config );
con->writeEntry( "FileFormat", QString("vcard") );
con->writeEntry( "ResourceIdentifier", QString("sync") );
con->writeEntry( "ResourceName", QString("sync_res") );
if ( config.right(4) == ".xml" )
con->writeEntry( "ResourceType", QString("qtopia") );
else if ( config == "sharp" ) {
con->writeEntry( "ResourceType", QString("sharp") );
} else {
con->writeEntry( "ResourceType", QString("file") );
}
//con->sync();
d->mConfig = con;
}
else
d->mConfig = new KConfig( locateLocal("config", config) );
// qDebug("AddressBook::init 1 config=%s",config.latin1() );
}
else {
d->mConfig = 0;
// qDebug("AddressBook::init 1 config=0");
}
//US d->mErrorHandler = 0;
d->mManager = new KRES::Manager<Resource>( fami, false );
d->mManager->readConfig( d->mConfig );
if ( family == "syncContact" ) {
KRES::Manager<Resource> *manager = d->mManager;
KRES::Manager<Resource>::ActiveIterator it;
for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) {
(*it)->setAddressBook( this );
if ( !(*it)->open() )
error( QString( "Unable to open resource '%1'!" ).arg( (*it)->resourceName() ) );
}
Resource *res = standardResource();
if ( !res ) {
qDebug("ERROR: no standard resource");
res = manager->createResource( "file" );
if ( res )
{
addResource( res );
}
else
qDebug(" No resource available!!!");
}
setStandardResource( res );
manager->writeConfig();
}
addCustomField( i18n( "Department" ), KABC::Field::Organization,
"X-Department", "KADDRESSBOOK" );
addCustomField( i18n( "Profession" ), KABC::Field::Organization,
"X-Profession", "KADDRESSBOOK" );
addCustomField( i18n( "Assistant's Name" ), KABC::Field::Organization,
"X-AssistantsName", "KADDRESSBOOK" );
addCustomField( i18n( "Manager's Name" ), KABC::Field::Organization,
"X-ManagersName", "KADDRESSBOOK" );
addCustomField( i18n( "Spouse's Name" ), KABC::Field::Personal,
"X-SpousesName", "KADDRESSBOOK" );
addCustomField( i18n( "Office" ), KABC::Field::Personal,
"X-Office", "KADDRESSBOOK" );
addCustomField( i18n( "IM Address" ), KABC::Field::Personal,
"X-IMAddress", "KADDRESSBOOK" );
addCustomField( i18n( "Anniversary" ), KABC::Field::Personal,
"X-Anniversary", "KADDRESSBOOK" );
//US added this field to become compatible with Opie/qtopia addressbook
// values can be "female" or "male" or "". An empty field represents undefined.
addCustomField( i18n( "Gender" ), KABC::Field::Personal,
"X-Gender", "KADDRESSBOOK" );
addCustomField( i18n( "Children" ), KABC::Field::Personal,
"X-Children", "KADDRESSBOOK" );
addCustomField( i18n( "FreeBusyUrl" ), KABC::Field::Personal,
"X-FreeBusyUrl", "KADDRESSBOOK" );
addCustomField( i18n( "ExternalID" ), KABC::Field::Personal,
"X-ExternalID", "KADDRESSBOOK" );
}
AddressBook::~AddressBook()
{
delete d->mConfig; d->mConfig = 0;
delete d->mManager; d->mManager = 0;
//US delete d->mErrorHandler; d->mErrorHandler = 0;
delete d; d = 0;
}
bool AddressBook::load()
{
-
clear();
-
KRES::Manager<Resource>::ActiveIterator it;
bool ok = true;
for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it )
if ( !(*it)->load() ) {
- error( i18n("Unable to load resource '%1'").arg( (*it)->resourceName() ) );
+ qDebug( i18n("Unable to load resource '%1'").arg( (*it)->resourceName() ) );
ok = false;
+ } else {
+ qDebug( i18n("Resource loaded: '%1'").arg( (*it)->resourceName() ) );
}
-
// mark all addressees as unchanged
Addressee::List::Iterator addrIt;
for ( addrIt = d->mAddressees.begin(); addrIt != d->mAddressees.end(); ++addrIt ) {
(*addrIt).setChanged( false );
QString id = (*addrIt).custom( "KADDRESSBOOK", "X-ExternalID" );
if ( !id.isEmpty() ) {
//qDebug("setId aa %s ", id.latin1());
(*addrIt).setIDStr(id );
}
}
blockLSEchange = true;
return ok;
}
bool AddressBook::save( Ticket *ticket )
{
kdDebug(5700) << "AddressBook::save()"<< endl;
if ( ticket->resource() ) {
deleteRemovedAddressees();
return ticket->resource()->save( ticket );
}
return false;
}
void AddressBook::export2File( QString fileName )
{
QFile outFile( fileName );
if ( !outFile.open( IO_WriteOnly ) ) {
QString text = i18n( "<qt>Unable to open file <b>%1</b> for export.</qt>" );
KMessageBox::error( 0, text.arg( fileName ) );
return ;
}
QTextStream t( &outFile );
t.setEncoding( QTextStream::UnicodeUTF8 );
Iterator it;
KABC::VCardConverter::Version version;
version = KABC::VCardConverter::v3_0;
for ( it = begin(); it != end(); ++it ) {
if ( !(*it).IDStr().isEmpty() ) {
(*it).insertCustom( "KADDRESSBOOK", "X-ExternalID", (*it).IDStr() );
}
KABC::VCardConverter converter;
QString vcard;
//Resource *resource() const;
converter.addresseeToVCard( *it, vcard, version );
t << vcard << "\r\n";
}
t << "\r\n\r\n";
outFile.close();
}
+// if QStringList uids is empty, all are exported
+bool AddressBook::export2PhoneFormat( QStringList uids ,QString fileName )
+{
+ KABC::VCardConverter converter;
+ QString datastream;
+ Iterator it;
+ bool all = uids.isEmpty();
+ for ( it = begin(); it != end(); ++it ) {
+ // for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) {
+ if ( ! all ) {
+ if ( ! ( uids.contains((*it).uid() ) ))
+ continue;
+ }
+ KABC::Addressee a = ( *it );
+ if ( a.isEmpty() )
+ continue;
+ a.simplifyEmails();
+ a.simplifyPhoneNumbers();
+ a.simplifyPhoneNumberTypes();
+ a.simplifyAddresses();
+
+ QString vcard;
+ QString vcardnew;
+ converter.addresseeToVCard( a, vcard );
+ int start = 0;
+ int next;
+ while ( (next = vcard.find("TYPE=", start) )>= 0 ) {
+ int semi = vcard.find(";", next);
+ int dopp = vcard.find(":", next);
+ int sep;
+ if ( semi < dopp && semi >= 0 )
+ sep = semi ;
+ else
+ sep = dopp;
+ vcardnew +=vcard.mid( start, next - start);
+ vcardnew +=vcard.mid( next+5,sep -next -5 ).upper();
+ start = sep;
+ }
+ vcardnew += vcard.mid( start,vcard.length() );
+ vcard = "";
+ start = 0;
+ while ( (next = vcardnew.find("ADR", start) )>= 0 ) {
+ int sep = vcardnew.find(":", next);
+ vcard +=vcardnew.mid( start, next - start+3);
+ start = sep;
+ }
+ vcard += vcardnew.mid( start,vcardnew.length() );
+ vcard.replace ( QRegExp(";;;") , "" );
+ vcard.replace ( QRegExp(";;") , "" );
+ datastream += vcard;
+
+ }
+
+ QFile outFile(fileName);
+ if ( outFile.open(IO_WriteOnly) ) {
+ datastream.replace ( QRegExp("VERSION:3.0") , "VERSION:2.1" );
+ QTextStream t( &outFile ); // use a text stream
+ t.setEncoding( QTextStream::UnicodeUTF8 );
+ t <<datastream;
+ t << "\r\n\r\n";
+ outFile.close();
+
+ } else {
+ qDebug("Error open temp file ");
+ return false;
+ }
+ return true;
+
+}
void AddressBook::importFromFile( QString fileName, bool replaceLabel, bool removeOld )
{
if ( removeOld )
setUntagged();
KABC::Addressee::List list;
QFile file( fileName );
file.open( IO_ReadOnly );
QByteArray rawData = file.readAll();
file.close();
QString data;
if ( replaceLabel ) {
data = QString::fromLatin1( rawData.data(), rawData.size() + 1 );
data.replace ( QRegExp("LABEL") , "ADR" );
data.replace ( QRegExp("CHARSET=ISO-8859-1") , "" );
} else
data = QString::fromUtf8( rawData.data(), rawData.size() + 1 );
KABC::VCardTool tool;
list = tool.parseVCards( data );
KABC::Addressee::List::Iterator it;
for ( it = list.begin(); it != list.end(); ++it ) {
+ QString id = (*it).custom( "KADDRESSBOOK", "X-ExternalID" );
+ if ( !id.isEmpty() )
+ (*it).setIDStr(id );
(*it).setResource( 0 );
if ( replaceLabel )
(*it).removeVoice();
if ( removeOld )
(*it).setTagged( true );
insertAddressee( (*it), false, true );
}
if ( removeOld )
removeUntagged();
}
void AddressBook::setUntagged()
{
Iterator ait;
for ( ait = begin(); ait != end(); ++ait ) {
(*ait).setTagged( false );
}
}
void AddressBook::removeUntagged()
{
Iterator ait;
bool todelete = false;
Iterator todel;
for ( ait = begin(); ait != end(); ++ait ) {
if ( todelete )
removeAddressee( todel );
if (!(*ait).tagged()) {
todelete = true;
todel = ait;
} else
todelete = false;
}
if ( todelete )
removeAddressee( todel );
deleteRemovedAddressees();
}
void AddressBook::smplifyAddressees()
{
Iterator ait;
for ( ait = begin(); ait != end(); ++ait ) {
(*ait).simplifyEmails();
(*ait).simplifyPhoneNumbers();
(*ait).simplifyPhoneNumberTypes();
(*ait).simplifyAddresses();
}
}
void AddressBook::preparePhoneSync( QString currentSyncDevice, bool isPreSync )
{
Iterator ait;
for ( ait = begin(); ait != end(); ++ait ) {
QString id = (*ait).IDStr();
(*ait).setIDStr( ":");
(*ait).setExternalUID( id );
(*ait).setOriginalExternalUID( id );
if ( isPreSync )
(*ait).setTempSyncStat( SYNC_TEMPSTATE_NEW_EXTERNAL );
- else
+ else {
(*ait).setTempSyncStat( SYNC_TEMPSTATE_NEW_ID );
+ (*ait).setID( currentSyncDevice,id );
+
+ }
+ }
+}
+void AddressBook::findNewExtIds( QString fileName, QString currentSyncDevice )
+{
+
+ setUntagged();
+ KABC::Addressee::List list;
+ QFile file( fileName );
+ file.open( IO_ReadOnly );
+ QByteArray rawData = file.readAll();
+ file.close();
+ QString data;
+
+ data = QString::fromUtf8( rawData.data(), rawData.size() + 1 );
+ KABC::VCardTool tool;
+ list = tool.parseVCards( data );
+ KABC::Addressee::List::Iterator it;
+ for ( it = list.begin(); it != list.end(); ++it ) {
+ Iterator ait;
+ for ( ait = begin(); ait != end(); ++ait ) {
+ if ( !(*ait).tagged() ) {
+ if ( (*ait).containsAdr(*it)) {
+ (*ait).setTagged(true);
+ QString id = (*it).custom( "KADDRESSBOOK", "X-ExternalID" );
+ (*it).setIDStr( ":");
+ (*it).setID( currentSyncDevice,id );
+ (*it).setExternalUID( id );
+ (*it).setTempSyncStat( SYNC_TEMPSTATE_NEW_ID );
+ (*it).setUid( ( (*ait).uid() ));
+ break;
+ }
+ }
+
+ }
+ if ( ait == end() )
+ qDebug("ERROR:: no ext ID found for uid: %s", (*it).uid().latin1());
+ }
+ clear();
+ for ( it = list.begin(); it != list.end(); ++it ) {
+ insertAddressee( (*it) );
}
}
+
bool AddressBook::saveABphone( QString fileName )
{
- smplifyAddressees();
+ //smplifyAddressees();
qDebug("saveABphone:: saving AB... ");
- if ( ! saveAB() )
+ if ( ! export2PhoneFormat( QStringList() ,fileName ) )
return false;
qDebug("saveABphone:: writing to phone... ");
if ( !PhoneAccess::writeToPhone( fileName) ) {
return false;
}
qDebug("saveABphone:: re-reading from phone... ");
if ( !PhoneAccess::readFromPhone( fileName) ) {
return false;
}
- qDebug("reloading phone book... ");
- if ( !load() )
- return false;
return true;
}
bool AddressBook::saveAB()
{
bool ok = true;
deleteRemovedAddressees();
Iterator ait;
for ( ait = begin(); ait != end(); ++ait ) {
if ( !(*ait).IDStr().isEmpty() ) {
(*ait).insertCustom( "KADDRESSBOOK", "X-ExternalID", (*ait).IDStr() );
}
}
KRES::Manager<Resource>::ActiveIterator it;
KRES::Manager<Resource> *manager = d->mManager;
+ qDebug("SaveAB::saving..." );
for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) {
+ qDebug("SaveAB::checking resource..." );
+ if ( (*it)->readOnly() )
+ qDebug("readonly." );
+ if ( (*it)->isOpen() )
+ qDebug("open" );
+
if ( !(*it)->readOnly() && (*it)->isOpen() ) {
Ticket *ticket = requestSaveTicket( *it );
-// qDebug("StdAddressBook::save '%s'", (*it)->resourceName().latin1() );
+ qDebug("StdAddressBook::save '%s'", (*it)->resourceName().latin1() );
if ( !ticket ) {
- error( i18n( "Unable to save to resource '%1'. It is locked." )
+ qDebug( i18n( "Unable to save to resource '%1'. It is locked." )
.arg( (*it)->resourceName() ) );
return false;
}
//if ( !save( ticket ) )
if ( ticket->resource() ) {
if ( ! ticket->resource()->save( ticket ) )
ok = false;
+ else
+ qDebug("StdAddressBook::saved '%s'", ticket->resource()->resourceName().latin1() );
+
} else
ok = false;
}
}
return ok;
}
AddressBook::Iterator AddressBook::begin()
{
Iterator it = Iterator();
it.d->mIt = d->mAddressees.begin();
return it;
}
AddressBook::ConstIterator AddressBook::begin() const
{
ConstIterator it = ConstIterator();
it.d->mIt = d->mAddressees.begin();
return it;
}
AddressBook::Iterator AddressBook::end()
{
Iterator it = Iterator();
it.d->mIt = d->mAddressees.end();
return it;
}
AddressBook::ConstIterator AddressBook::end() const
{
ConstIterator it = ConstIterator();
it.d->mIt = d->mAddressees.end();
return it;
}
void AddressBook::clear()
{
d->mAddressees.clear();
}
Ticket *AddressBook::requestSaveTicket( Resource *resource )
{
kdDebug(5700) << "AddressBook::requestSaveTicket()" << endl;
if ( !resource )
{
qDebug("AddressBook::requestSaveTicket no resource" );
resource = standardResource();
}
KRES::Manager<Resource>::ActiveIterator it;
for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) {
if ( (*it) == resource ) {
if ( (*it)->readOnly() || !(*it)->isOpen() )
return 0;
else
return (*it)->requestSaveTicket();
}
}
return 0;
}
-
+//void insertAddressee( const Addressee &, bool setRev = true, bool takeResource = false);
void AddressBook::insertAddressee( const Addressee &a, bool setRev, bool takeResource )
{
if ( blockLSEchange && setRev && a.uid().left( 19 ) == QString("last-syncAddressee-") ) {
//qDebug("block insert ");
return;
}
//qDebug("inserting.... %s ",a.uid().latin1() );
bool found = false;
Addressee::List::Iterator it;
for ( it = d->mAddressees.begin(); it != d->mAddressees.end(); ++it ) {
if ( a.uid() == (*it).uid() ) {
bool changed = false;
Addressee addr = a;
if ( addr != (*it) )
changed = true;
if ( takeResource ) {
Resource * res = (*it).resource();
(*it) = a;
(*it).setResource( res );
} else {
(*it) = a;
if ( (*it).resource() == 0 )
(*it).setResource( standardResource() );
}
if ( changed ) {
if ( setRev ) {
// get rid of micro seconds
QDateTime dt = QDateTime::currentDateTime();
QTime t = dt.time();
dt.setTime( QTime (t.hour (), t.minute (), t.second () ) );
(*it).setRevision( dt );
}
(*it).setChanged( true );
}
found = true;
} else {
if ( (*it).uid().left( 19 ) == QString("last-syncAddressee-") ) {
QString name = (*it).uid().mid( 19 );
Addressee b = a;
QString id = b.getID( name );
if ( ! id.isEmpty() ) {
QString des = (*it).note();
int startN;
if( (startN = des.find( id ) ) >= 0 ) {
int endN = des.find( ",", startN+1 );
des = des.left( startN ) + des.mid( endN+1 );
(*it).setNote( des );
}
}
}
}
}
if ( found )
return;
d->mAddressees.append( a );
Addressee& addr = d->mAddressees.last();
if ( addr.resource() == 0 )
addr.setResource( standardResource() );
addr.setChanged( true );
}
void AddressBook::removeAddressee( const Addressee &a )
{
Iterator it;
Iterator it2;
bool found = false;
for ( it = begin(); it != end(); ++it ) {
if ( a.uid() == (*it).uid() ) {
found = true;
it2 = it;
} else {
if ( (*it).uid().left( 19 ) == QString("last-syncAddressee-") ) {
QString name = (*it).uid().mid( 19 );
Addressee b = a;
QString id = b.getID( name );
if ( ! id.isEmpty() ) {
QString des = (*it).note();
if( des.find( id ) < 0 ) {
des += id + ",";
(*it).setNote( des );
}
}
}
}
}
if ( found )
removeAddressee( it2 );
}
void AddressBook::removeSyncAddressees( bool removeDeleted )
{
Iterator it = begin();
Iterator it2 ;
QDateTime dt ( QDate( 2004,1,1) );
while ( it != end() ) {
(*it).setRevision( dt );
(*it).removeCustom( "KADDRESSBOOK", "X-ExternalID" );
(*it).setIDStr("");
if ( ( (*it).tempSyncStat() == SYNC_TEMPSTATE_DELETE && removeDeleted )|| (*it).uid().left( 19 ) == QString("last-syncAddressee-")) {
it2 = it;
//qDebug("removing %s ",(*it).uid().latin1() );
++it;
removeAddressee( it2 );
} else {
//qDebug("skipping %s ",(*it).uid().latin1() );
++it;
}
}
deleteRemovedAddressees();
}
void AddressBook::removeAddressee( const Iterator &it )
{
d->mRemovedAddressees.append( (*it) );
d->mAddressees.remove( it.d->mIt );
}
AddressBook::Iterator AddressBook::find( const Addressee &a )
{
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( a.uid() == (*it).uid() ) {
return it;
}
}
return end();
}
Addressee AddressBook::findByUid( const QString &uid )
{
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( uid == (*it).uid() ) {
return *it;
}
}
return Addressee();
}
void AddressBook::preExternSync( AddressBook* aBook, const QString& csd )
{
//qDebug("AddressBook::preExternSync ");
AddressBook::Iterator it;
for ( it = begin(); it != end(); ++it ) {
(*it).setID( csd, (*it).externalUID() );
(*it).computeCsum( csd );
}
mergeAB( aBook ,csd );
}
void AddressBook::postExternSync( AddressBook* aBook , const QString& csd)
{
//qDebug("AddressBook::postExternSync ");
AddressBook::Iterator it;
for ( it = begin(); it != end(); ++it ) {
// qDebug("check uid %s ", (*it).uid().latin1() );
if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_ID ||
(*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_CSUM ) {
Addressee ad = aBook->findByUid( ( (*it).uid() ));
if ( ad.isEmpty() ) {
qDebug("postExternSync:ERROR addressee is empty: %s ", (*it).uid().latin1());
} else {
(*it).computeCsum( csd );
if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_ID )
ad.setID( csd, (*it).externalUID() );
ad.setCsum( csd, (*it).getCsum( csd ) );
aBook->insertAddressee( ad );
}
}
}
}
bool AddressBook::containsExternalUid( const QString& uid )
{
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( uid == (*it).externalUID( ) )
return true;
}
return false;
}
Addressee AddressBook::findByExternUid( const QString& uid , const QString& profile )
{
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( uid == (*it).getID( profile ) )
return (*it);
}
return Addressee();
}
void AddressBook::mergeAB( AddressBook *aBook, const QString& profile )
{
Iterator it;
Addressee ad;
for ( it = begin(); it != end(); ++it ) {
ad = aBook->findByExternUid( (*it).externalUID(), profile );
if ( !ad.isEmpty() ) {
(*it).mergeContact( ad );
}
}
#if 0
// test only
for ( it = begin(); it != end(); ++it ) {
qDebug("uid %s ", (*it).uid().latin1());
}
#endif
}
#if 0
Addressee::List AddressBook::getExternLastSyncAddressees()
{
Addressee::List results;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( (*it).uid().left( 19 ) == "last-syncAddressee-" ) {
if ( (*it).familyName().left(4) == "!E: " )
results.append( *it );
}
}
return results;
}
#endif
void AddressBook::resetTempSyncStat()
{
Iterator it;
for ( it = begin(); it != end(); ++it ) {
(*it).setTempSyncStat ( SYNC_TEMPSTATE_INITIAL );
}
}
QStringList AddressBook:: uidList()
{
QStringList results;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
results.append( (*it).uid() );
}
return results;
}
Addressee::List AddressBook::allAddressees()
{
return d->mAddressees;
}
Addressee::List AddressBook::findByName( const QString &name )
{
Addressee::List results;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( name == (*it).realName() ) {
results.append( *it );
}
}
return results;
}
Addressee::List AddressBook::findByEmail( const QString &email )
{
Addressee::List results;
QStringList mailList;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
mailList = (*it).emails();
for ( QStringList::Iterator ite = mailList.begin(); ite != mailList.end(); ++ite ) {
if ( email == (*ite) ) {
results.append( *it );
}
}
}
return results;
}
Addressee::List AddressBook::findByCategory( const QString &category )
{
Addressee::List results;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( (*it).hasCategory( category) ) {
results.append( *it );
}
}
return results;
}
void AddressBook::dump() const
{
kdDebug(5700) << "AddressBook::dump() --- begin ---" << endl;
ConstIterator it;
for( it = begin(); it != end(); ++it ) {
(*it).dump();
}
kdDebug(5700) << "AddressBook::dump() --- end ---" << endl;
}
QString AddressBook::identifier()
{
QStringList identifier;
KRES::Manager<Resource>::ActiveIterator it;
for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) {
if ( !(*it)->identifier().isEmpty() )
identifier.append( (*it)->identifier() );
}
return identifier.join( ":" );
}
Field::List AddressBook::fields( int category )
{
if ( d->mAllFields.isEmpty() ) {
d->mAllFields = Field::allFields();
}
if ( category == Field::All ) return d->mAllFields;
Field::List result;
Field::List::ConstIterator it;
for( it = d->mAllFields.begin(); it != d->mAllFields.end(); ++it ) {
if ( (*it)->category() & category ) result.append( *it );
}
return result;
}
bool AddressBook::addCustomField( const QString &label, int category,
const QString &key, const QString &app )
{
if ( d->mAllFields.isEmpty() ) {
d->mAllFields = Field::allFields();
}
//US QString a = app.isNull() ? KGlobal::instance()->instanceName() : app;
QString a = app.isNull() ? KGlobal::getAppName() : app;
QString k = key.isNull() ? label : key;
Field *field = Field::createCustomField( label, category, k, a );
if ( !field ) return false;
d->mAllFields.append( field );
return true;
}
QDataStream &KABC::operator<<( QDataStream &s, const AddressBook &ab )
{
if (!ab.d) return s;
return s << ab.d->mAddressees;
}
QDataStream &KABC::operator>>( QDataStream &s, AddressBook &ab )
{
if (!ab.d) return s;
s >> ab.d->mAddressees;
return s;
}
bool AddressBook::addResource( Resource *resource )
{
if ( !resource->open() ) {
kdDebug(5700) << "AddressBook::addResource(): can't add resource" << endl;
return false;
}
resource->setAddressBook( this );
d->mManager->add( resource );
return true;
}
bool AddressBook::removeResource( Resource *resource )
{
resource->close();
if ( resource == standardResource() )
d->mManager->setStandardResource( 0 );
resource->setAddressBook( 0 );
d->mManager->remove( resource );
return true;
}
QPtrList<Resource> AddressBook::resources()
{
QPtrList<Resource> list;
// qDebug("AddressBook::resources() 1");
KRES::Manager<Resource>::ActiveIterator it;
for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it )
list.append( *it );
return list;
}
/*US
void AddressBook::setErrorHandler( ErrorHandler *handler )
{
delete d->mErrorHandler;
d->mErrorHandler = handler;
}
*/
void AddressBook::error( const QString& msg )
{
/*US
if ( !d->mErrorHandler ) // create default error handler
d->mErrorHandler = new ConsoleErrorHandler;
if ( d->mErrorHandler )
d->mErrorHandler->error( msg );
else
kdError(5700) << "no error handler defined" << endl;
*/
kdDebug(5700) << "msg" << endl;
qDebug(msg);
}
void AddressBook::deleteRemovedAddressees()
{
Addressee::List::Iterator it;
for ( it = d->mRemovedAddressees.begin(); it != d->mRemovedAddressees.end(); ++it ) {
Resource *resource = (*it).resource();
if ( resource && !resource->readOnly() && resource->isOpen() )
resource->removeAddressee( *it );
}
d->mRemovedAddressees.clear();
}
void AddressBook::setStandardResource( Resource *resource )
{
// qDebug("AddressBook::setStandardResource 1");
d->mManager->setStandardResource( resource );
}
Resource *AddressBook::standardResource()
{
return d->mManager->standardResource();
}
KRES::Manager<Resource> *AddressBook::resourceManager()
{
return d->mManager;
}
void AddressBook::cleanUp()
{
KRES::Manager<Resource>::ActiveIterator it;
for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) {
if ( !(*it)->readOnly() && (*it)->isOpen() )
(*it)->cleanUp();
}
}
diff --git a/kabc/addressbook.h b/kabc/addressbook.h
index cc755d1..df9048b 100644
--- a/kabc/addressbook.h
+++ b/kabc/addressbook.h
@@ -1,346 +1,348 @@
/*
This file is part of libkabc.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/*
Enhanced Version of the file for platform independent KDE tools.
Copyright (c) 2004 Ulf Schenk
$Id$
*/
#ifndef KABC_ADDRESSBOOK_H
#define KABC_ADDRESSBOOK_H
#include <qobject.h>
#include <kresources/manager.h>
#include <qptrlist.h>
#include "addressee.h"
#include "field.h"
namespace KABC {
class ErrorHandler;
class Resource;
class Ticket;
/**
@short Address Book
This class provides access to a collection of address book entries.
*/
class AddressBook : public QObject
{
Q_OBJECT
friend QDataStream &operator<<( QDataStream &, const AddressBook & );
friend QDataStream &operator>>( QDataStream &, AddressBook & );
friend class StdAddressBook;
public:
/**
@short Address Book Iterator
This class provides an iterator for address book entries.
*/
class Iterator
{
public:
Iterator();
Iterator( const Iterator & );
~Iterator();
Iterator &operator=( const Iterator & );
const Addressee &operator*() const;
Addressee &operator*();
Addressee* operator->();
Iterator &operator++();
Iterator &operator++(int);
Iterator &operator--();
Iterator &operator--(int);
bool operator==( const Iterator &it );
bool operator!=( const Iterator &it );
struct IteratorData;
IteratorData *d;
};
/**
@short Address Book Const Iterator
This class provides a const iterator for address book entries.
*/
class ConstIterator
{
public:
ConstIterator();
ConstIterator( const ConstIterator & );
~ConstIterator();
ConstIterator &operator=( const ConstIterator & );
const Addressee &operator*() const;
const Addressee* operator->() const;
ConstIterator &operator++();
ConstIterator &operator++(int);
ConstIterator &operator--();
ConstIterator &operator--(int);
bool operator==( const ConstIterator &it );
bool operator!=( const ConstIterator &it );
struct ConstIteratorData;
ConstIteratorData *d;
};
/**
Constructs a address book object.
@param format File format class.
*/
AddressBook();
AddressBook( const QString &config );
AddressBook( const QString &config, const QString &family );
virtual ~AddressBook();
/**
Requests a ticket for saving the addressbook. Calling this function locks
the addressbook for all other processes. If the address book is already
locked the function returns 0. You need the returned @ref Ticket object
for calling the @ref save() function.
@see save()
*/
Ticket *requestSaveTicket( Resource *resource=0 );
/**
Load address book from file.
*/
bool load();
/**
Save address book. The address book is saved to the file, the Ticket
object has been requested for by @ref requestSaveTicket().
@param ticket a ticket object returned by @ref requestSaveTicket()
*/
bool save( Ticket *ticket );
bool saveAB( );
bool saveABphone( QString fileName );
void smplifyAddressees();
void preparePhoneSync( QString currentSyncDevice, bool isPreSync );
void export2File( QString fileName );
+ bool export2PhoneFormat( QStringList uids ,QString fileName );
void importFromFile( QString fileName, bool replaceLabel = false, bool removeOld = false );
void setUntagged();
void removeUntagged();
+ void findNewExtIds( QString fileName, QString currentSyncDevice );
/**
Returns a iterator for first entry of address book.
*/
Iterator begin();
/**
Returns a const iterator for first entry of address book.
*/
ConstIterator begin() const;
/**
Returns a iterator for first entry of address book.
*/
Iterator end();
/**
Returns a const iterator for first entry of address book.
*/
ConstIterator end() const;
/**
Removes all entries from address book.
*/
void clear();
/**
Insert an Addressee object into address book. If an object with the same
unique id already exists in the address book it it replaced by the new
one. If not the new object is appended to the address book.
*/
void insertAddressee( const Addressee &, bool setRev = true, bool takeResource = false);
/**
Removes entry from the address book.
*/
void removeAddressee( const Addressee & );
/**
This is like @ref removeAddressee() just above, with the difference that
the first element is a iterator, returned by @ref begin().
*/
void removeAddressee( const Iterator & );
/**
Find the specified entry in address book. Returns end(), if the entry
couldn't be found.
*/
Iterator find( const Addressee & );
/**
Find the entry specified by an unique id. Returns an empty Addressee
object, if the address book does not contain an entry with this id.
*/
Addressee findByUid( const QString & );
/**
Returns a list of all addressees in the address book. This list can
be sorted with @ref KABC::AddresseeList for example.
*/
Addressee::List allAddressees();
/**
Find all entries with the specified name in the address book. Returns
an empty list, if no entries could be found.
*/
Addressee::List findByName( const QString & );
/**
Find all entries with the specified email address in the address book.
Returns an empty list, if no entries could be found.
*/
Addressee::List findByEmail( const QString & );
/**
Find all entries wich have the specified category in the address book.
Returns an empty list, if no entries could be found.
*/
Addressee::List findByCategory( const QString & );
/**
Return a string identifying this addressbook.
*/
virtual QString identifier();
/**
Used for debug output.
*/
void dump() const;
void emitAddressBookLocked() { emit addressBookLocked( this ); }
void emitAddressBookUnlocked() { emit addressBookUnlocked( this ); }
void emitAddressBookChanged() { emit addressBookChanged( this ); }
/**
Return list of all Fields known to the address book which are associated
with the given field category.
*/
Field::List fields( int category = Field::All );
/**
Add custom field to address book.
@param label User visible label of the field.
@param category Ored list of field categories.
@param key Identifier used as key for reading and writing the field.
@param app String used as application key for reading and writing
the field.
*/
bool addCustomField( const QString &label, int category = Field::All,
const QString &key = QString::null,
const QString &app = QString::null );
/**
Add address book resource.
*/
bool addResource( Resource * );
/**
Remove address book resource.
*/
bool removeResource( Resource * );
/**
Return pointer list of all resources.
*/
QPtrList<Resource> resources();
/**
Set the @p ErrorHandler, that is used by @ref error() to
provide gui-independend error messages.
*/
void setErrorHandler( ErrorHandler * );
/**
Shows gui independend error messages.
*/
void error( const QString& );
/**
Query all resources to clean up their lock files
*/
void cleanUp();
// sync stuff
//Addressee::List getExternLastSyncAddressees();
void resetTempSyncStat();
QStringList uidList();
void removeSyncAddressees( bool removeDeleted = false );
void mergeAB( AddressBook *aBook, const QString& profile );
Addressee findByExternUid( const QString& uid , const QString& profile );
bool containsExternalUid( const QString& uid );
void preExternSync( AddressBook* aBook, const QString& csd );
void postExternSync( AddressBook* aBook, const QString& csd );
signals:
/**
Emitted, when the address book has changed on disk.
*/
void addressBookChanged( AddressBook * );
/**
Emitted, when the address book has been locked for writing.
*/
void addressBookLocked( AddressBook * );
/**
Emitted, when the address book has been unlocked.
*/
void addressBookUnlocked( AddressBook * );
protected:
void deleteRemovedAddressees();
void setStandardResource( Resource * );
Resource *standardResource();
KRES::Manager<Resource> *resourceManager();
void init(const QString &config, const QString &family);
private:
//US QPtrList<Resource> mDummy; // Remove in KDE 4
struct AddressBookData;
AddressBookData *d;
bool blockLSEchange;
};
QDataStream &operator<<( QDataStream &, const AddressBook & );
QDataStream &operator>>( QDataStream &, AddressBook & );
}
#endif
diff --git a/kabc/addressee.cpp b/kabc/addressee.cpp
index 607ae26..548305a 100644
--- a/kabc/addressee.cpp
+++ b/kabc/addressee.cpp
@@ -1,1947 +1,1987 @@
/*** Warning! This file has been generated by the script makeaddressee ***/
/*
This file is part of libkabc.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/*
Enhanced Version of the file for platform independent KDE tools.
Copyright (c) 2004 Ulf Schenk
$Id$
*/
#include <kconfig.h>
#include <ksharedptr.h>
#include <kdebug.h>
#include <kapplication.h>
#include <klocale.h>
#include <kidmanager.h>
//US
#include <kstandarddirs.h>
#include <libkcal/syncdefines.h>
//US #include "resource.h"
#include "addressee.h"
using namespace KABC;
static bool matchBinaryPattern( int value, int pattern );
static bool matchBinaryPatternA( int value, int pattern );
static bool matchBinaryPatternP( int value, int pattern );
struct Addressee::AddresseeData : public KShared
{
QString uid;
QString name;
QString formattedName;
QString familyName;
QString givenName;
QString additionalName;
QString prefix;
QString suffix;
QString nickName;
QDateTime birthday;
QString mailer;
TimeZone timeZone;
Geo geo;
QString title;
QString role;
QString organization;
QString note;
QString productId;
QDateTime revision;
QString sortString;
QString externalUID;
QString originalExternalUID;
KURL url;
Secrecy secrecy;
Picture logo;
Picture photo;
Sound sound;
Agent agent;
QString mExternalId;
PhoneNumber::List phoneNumbers;
Address::List addresses;
Key::List keys;
QStringList emails;
QStringList categories;
QStringList custom;
int mTempSyncStat;
Resource *resource;
bool empty :1;
bool changed :1;
bool tagged :1;
};
Addressee::Addressee()
{
mData = new AddresseeData;
mData->empty = true;
mData->changed = false;
mData->resource = 0;
mData->mExternalId = ":";
mData->revision = QDateTime ( QDate( 2003,1,1));
mData->mTempSyncStat = SYNC_TEMPSTATE_INITIAL;
}
Addressee::~Addressee()
{
}
Addressee::Addressee( const Addressee &a )
{
mData = a.mData;
}
Addressee &Addressee::operator=( const Addressee &a )
{
mData = a.mData;
return (*this);
}
Addressee Addressee::copy()
{
Addressee a;
*(a.mData) = *mData;
return a;
}
void Addressee::detach()
{
if ( mData.count() == 1 ) return;
*this = copy();
}
bool Addressee::operator==( const Addressee &a ) const
{
if ( uid() != a.uid() ) return false;
if ( mData->name != a.mData->name ) return false;
if ( mData->formattedName != a.mData->formattedName ) return false;
if ( mData->familyName != a.mData->familyName ) return false;
if ( mData->givenName != a.mData->givenName ) return false;
if ( mData->additionalName != a.mData->additionalName ) return false;
if ( mData->prefix != a.mData->prefix ) return false;
if ( mData->suffix != a.mData->suffix ) return false;
if ( mData->nickName != a.mData->nickName ) return false;
if ( mData->birthday != a.mData->birthday ) return false;
if ( mData->mailer != a.mData->mailer ) return false;
if ( mData->timeZone != a.mData->timeZone ) return false;
if ( mData->geo != a.mData->geo ) return false;
if ( mData->title != a.mData->title ) return false;
if ( mData->role != a.mData->role ) return false;
if ( mData->organization != a.mData->organization ) return false;
if ( mData->note != a.mData->note ) return false;
if ( mData->productId != a.mData->productId ) return false;
//if ( mData->revision != a.mData->revision ) return false;
if ( mData->sortString != a.mData->sortString ) return false;
if ( mData->secrecy != a.mData->secrecy ) return false;
if ( mData->logo != a.mData->logo ) return false;
if ( mData->photo != a.mData->photo ) return false;
if ( mData->sound != a.mData->sound ) return false;
if ( mData->agent != a.mData->agent ) return false;
if ( ( mData->url.isValid() || a.mData->url.isValid() ) &&
( mData->url != a.mData->url ) ) return false;
if ( mData->phoneNumbers != a.mData->phoneNumbers ) return false;
if ( mData->addresses != a.mData->addresses ) return false;
if ( mData->keys != a.mData->keys ) return false;
if ( mData->emails != a.mData->emails ) return false;
if ( mData->categories != a.mData->categories ) return false;
if ( mData->custom != a.mData->custom ) return false;
return true;
}
bool Addressee::operator!=( const Addressee &a ) const
{
return !( a == *this );
}
bool Addressee::isEmpty() const
{
return mData->empty;
}
ulong Addressee::getCsum4List( const QStringList & attList)
{
int max = attList.count();
ulong cSum = 0;
int j,k,i;
int add;
for ( i = 0; i < max ; ++i ) {
QString s = attList[i];
if ( ! s.isEmpty() ){
j = s.length();
for ( k = 0; k < j; ++k ) {
int mul = k +1;
add = s[k].unicode ();
if ( k < 16 )
mul = mul * mul;
int ii = i+1;
add = add * mul *ii*ii*ii;
cSum += add;
}
}
}
//QString dump = attList.join(",");
//qDebug("csum: %d %s", cSum,dump.latin1());
return cSum;
}
void Addressee::computeCsum(const QString &dev)
{
QStringList l;
if ( !mData->name.isEmpty() ) l.append(mData->name);
if ( !mData->formattedName.isEmpty() ) l.append(mData->formattedName );
if ( !mData->familyName.isEmpty() ) l.append( mData->familyName );
if ( !mData->givenName.isEmpty() ) l.append(mData->givenName );
if ( !mData->additionalName ) l.append( mData->additionalName );
if ( !mData->prefix.isEmpty() ) l.append( mData->prefix );
if ( !mData->suffix.isEmpty() ) l.append( mData->suffix );
if ( !mData->nickName.isEmpty() ) l.append( mData->nickName );
if ( mData->birthday.isValid() ) l.append( mData->birthday.toString() );
if ( !mData->mailer.isEmpty() ) l.append( mData->mailer );
if ( mData->timeZone.isValid() ) l.append( mData->timeZone.asString() );
if ( mData->geo.isValid() ) l.append( mData->geo.asString() );
if ( !mData->title .isEmpty() ) l.append( mData->title );
if ( !mData->role.isEmpty() ) l.append( mData->role );
if ( !mData->organization.isEmpty() ) l.append( mData->organization );
if ( !mData->note.isEmpty() ) l.append( mData->note );
if ( !mData->productId.isEmpty() ) l.append(mData->productId );
if ( !mData->sortString.isEmpty() ) l.append( mData->sortString );
if ( mData->secrecy.isValid() ) l.append( mData->secrecy.asString());
// if ( !mData->logo.isEmpty() ) l.append( );
//if ( !mData->photo.isEmpty() ) l.append( );
//if ( !mData->sound.isEmpty() ) l.append( );
//if ( !mData->agent.isEmpty() ) l.append( );
//if ( mData->url.isValid() ) l.append( );
#if 0
if ( !mData->phoneNumbers.isEmpty() ) l.append( );
if ( !mData->addresses.isEmpty() ) l.append( );
//if ( !mData->keys.isEmpty() ) l.append( );
if ( !mData->emails.isEmpty() ) l.append( );
if ( !mData->categories .isEmpty() ) l.append( );
if ( !mData->custom.isEmpty() ) l.append( );
#endif
KABC::PhoneNumber::List phoneNumbers;
KABC::PhoneNumber::List::Iterator phoneIter;
QStringList t;
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter )
t.append( ( *phoneIter ).number()+QString::number( ( *phoneIter ).type() ) );
t.sort();
uint iii;
for ( iii = 0; iii < t.count(); ++iii)
l.append( t[iii] );
t = mData->emails;
t.sort();
for ( iii = 0; iii < t.count(); ++iii)
l.append( t[iii] );
t = mData->categories;
t.sort();
for ( iii = 0; iii < t.count(); ++iii)
l.append( t[iii] );
t = mData->custom;
t.sort();
for ( iii = 0; iii < t.count(); ++iii)
l.append( t[iii] );
KABC::Address::List::Iterator addressIter;
for ( addressIter = mData->addresses.begin(); addressIter != mData->addresses.end();
++addressIter ) {
t = (*addressIter).asList();
t.sort();
for ( iii = 0; iii < t.count(); ++iii)
l.append( t[iii] );
}
uint cs = getCsum4List(l);
// qDebug("CSUM computed %d %s %s", cs,QString::number (cs ).latin1(), uid().latin1() );
setCsum( dev, QString::number (cs ));
}
void Addressee::mergeContact( const Addressee& ad )
{
detach();
if ( mData->name.isEmpty() ) mData->name = ad.mData->name;
if ( mData->formattedName.isEmpty() ) mData->formattedName = ad.mData->formattedName;
if ( mData->familyName.isEmpty() ) mData->familyName = ad.mData->familyName;
if ( mData->givenName.isEmpty() ) mData->givenName = ad.mData->givenName ;
if ( mData->additionalName ) mData->additionalName = ad.mData->additionalName;
if ( mData->prefix.isEmpty() ) mData->prefix = ad.mData->prefix;
if ( mData->suffix.isEmpty() ) mData->suffix = ad.mData->suffix;
if ( mData->nickName.isEmpty() ) mData->nickName = ad.mData->nickName;
if ( !mData->birthday.isValid() )
if ( ad.mData->birthday.isValid())
mData->birthday = ad.mData->birthday;
if ( mData->mailer.isEmpty() ) mData->mailer = ad.mData->mailer;
if ( !mData->timeZone.isValid() ) mData->timeZone = ad.mData->timeZone;
if ( !mData->geo.isValid() ) mData->geo = ad.mData->geo;
if ( mData->title .isEmpty() ) mData->title = ad.mData->title ;
if ( mData->role.isEmpty() ) mData->role = ad.mData->role ;
if ( mData->organization.isEmpty() ) mData->organization = ad.mData->organization ;
if ( mData->note.isEmpty() ) mData->note = ad.mData->note ;
if ( mData->productId.isEmpty() ) mData->productId = ad.mData->productId;
if ( mData->sortString.isEmpty() ) mData->sortString = ad.mData->sortString;
if ( !mData->secrecy.isValid() ) mData->secrecy = ad.mData->secrecy;
if ( ( !mData->url.isValid() && ad.mData->url.isValid() ) ) mData->url = ad.mData->url ;
+ PhoneNumber::List phoneAD = phoneNumbers();
+ PhoneNumber::List::Iterator phoneItAD;
+ bool found = false;
+ for ( phoneItAD = phoneAD.begin(); phoneItAD != phoneAD.end(); ++phoneItAD ) {
+
+ }
// pending:
// merging phonenumbers
// merging addresses
// merging emails;
// merging categories;
// merging custom;
// merging keys
- qDebug("merge contact %s ", ad.uid().latin1());
+ //qDebug("merge contact %s ", ad.uid().latin1());
setUid( ad.uid() );
setRevision( ad.revision() );
}
bool Addressee::removeVoice()
{
PhoneNumber::List phoneN = phoneNumbers();
PhoneNumber::List::Iterator phoneIt;
bool found = false;
for ( phoneIt = phoneN.begin(); phoneIt != phoneN.end(); ++phoneIt ) {
if ( (*phoneIt).type() & PhoneNumber::Voice) { // voice found
if ((*phoneIt).type() - PhoneNumber::Voice ) {
(*phoneIt).setType((*phoneIt).type() - PhoneNumber::Voice );
insertPhoneNumber( (*phoneIt) );
found = true;
}
}
}
return found;
}
+
+bool Addressee::containsAdr(const Addressee& ad )
+{
+ if ( ! ad.mData->familyName.isEmpty() ) if ( mData->familyName != ad.mData->familyName) return false;
+ if ( ! ad.mData->givenName.isEmpty() )if ( mData->givenName != ad.mData->givenName ) return false;
+ if ( ad.mData->url.isValid() ) if (mData->url != ad.mData->url) return false ;
+ if ( ! ad.mData->role.isEmpty() ) if (mData->role != ad.mData->role) return false ;
+ if ( ! ad.mData->organization.isEmpty() ) if (mData->organization != ad.mData->organization) return false ;
+ if ( ! ad.mData->note.isEmpty() ) if (mData->note != ad.mData->note) return false ;
+ if ( ! ad.mData->title .isEmpty() ) if (mData->title != ad.mData->title ) return false ;
+
+ // compare phone numbers
+ PhoneNumber::List phoneN = ad.phoneNumbers();
+ PhoneNumber::List::Iterator phoneIt;
+ bool found = false;
+ for ( phoneIt = phoneN.begin(); phoneIt != phoneN.end(); ++phoneIt ) {
+ bool found = false;
+ PhoneNumber::List phoneL = ad.phoneNumbers();
+ PhoneNumber::List::Iterator phoneItL;
+ for ( phoneItL = phoneL.begin(); phoneItL != phoneL.end(); ++phoneItL ) {
+ if ( ( *phoneItL ).number() == ( *phoneIt ).number() ) {
+ found = true;
+ break;
+ }
+ }
+ if ( ! found )
+ return false;
+ }
+ return true;
+
+}
void Addressee::simplifyAddresses()
{
- if ( mData->addresses.count() < 3 ) return ;
+ int max = 2;
+ if ( mData->url.isValid() )
+ max = 1;
+ if ( mData->addresses.count() <= max ) return ;
int count = 0;
Address::List list;
Address::List::Iterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
- if ( count > 1 )
+ if ( count >= max )
list.append( *it );
++count;
}
for( it = list.begin(); it != list.end(); ++it ) {
removeAddress( (*it) );
}
}
// removes all emails but the first
// needed by phone sync
void Addressee::simplifyEmails()
{
if ( mData->emails.count() == 0 ) return ;
QString email = mData->emails.first();
detach();
mData->emails.clear();
mData->emails.append( email );
}
void Addressee::simplifyPhoneNumbers()
{
KABC::PhoneNumber::List removeNumbers;
KABC::PhoneNumber::List::Iterator phoneIter;
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter ) {
if ( ! ( *phoneIter ).simplifyNumber() )
removeNumbers.append( ( *phoneIter ) );
}
for ( phoneIter = removeNumbers.begin(); phoneIter != removeNumbers.end();
++phoneIter ) {
removePhoneNumber(( *phoneIter ));
}
}
void Addressee::simplifyPhoneNumberTypes()
{
KABC::PhoneNumber::List::Iterator phoneIter;
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter )
( *phoneIter ).simplifyType();
}
void Addressee::removeID(const QString &prof)
{
detach();
mData->mExternalId = KIdManager::removeId ( mData->mExternalId, prof);
}
void Addressee::setID( const QString & prof , const QString & id )
{
detach();
mData->mExternalId = KIdManager::setId ( mData->mExternalId, prof, id );
//qDebug("setID2 %s %s %s",mData->mExternalId.latin1(), prof.latin1(), id.latin1() );
}
void Addressee::setTempSyncStat( int id )
{
if ( mData->mTempSyncStat == id ) return;
detach();
mData->mTempSyncStat = id;
}
int Addressee::tempSyncStat() const
{
return mData->mTempSyncStat;
}
QString Addressee::getID( const QString & prof)
{
return KIdManager::getId ( mData->mExternalId, prof );
}
void Addressee::setCsum( const QString & prof , const QString & id )
{
detach();
//qDebug("setcsum1 %s %s %s",mData->mExternalId.latin1(), prof.latin1(), id.latin1() );
mData->mExternalId = KIdManager::setCsum ( mData->mExternalId, prof, id );
//qDebug("setcsum2 %s ",mData->mExternalId.latin1() );
}
QString Addressee::getCsum( const QString & prof)
{
return KIdManager::getCsum ( mData->mExternalId, prof );
}
void Addressee::setIDStr( const QString & s )
{
detach();
mData->mExternalId = s;
}
QString Addressee::IDStr() const
{
return mData->mExternalId;
}
void Addressee::setExternalUID( const QString &id )
{
if ( id == mData->externalUID ) return;
detach();
mData->empty = false;
mData->externalUID = id;
}
QString Addressee::externalUID() const
{
return mData->externalUID;
}
void Addressee::setOriginalExternalUID( const QString &id )
{
if ( id == mData->originalExternalUID ) return;
detach();
mData->empty = false;
//qDebug("*******Set orig uid %s ", id.latin1());
mData->originalExternalUID = id;
}
QString Addressee::originalExternalUID() const
{
return mData->originalExternalUID;
}
void Addressee::setUid( const QString &id )
{
if ( id == mData->uid ) return;
detach();
//qDebug("****setuid %s ", id.latin1());
mData->empty = false;
mData->uid = id;
}
QString Addressee::uid() const
{
if ( mData->uid.isEmpty() )
mData->uid = KApplication::randomString( 10 );
return mData->uid;
}
QString Addressee::uidLabel()
{
return i18n("Unique Identifier");
}
void Addressee::setName( const QString &name )
{
if ( name == mData->name ) return;
detach();
mData->empty = false;
mData->name = name;
}
QString Addressee::name() const
{
return mData->name;
}
QString Addressee::nameLabel()
{
return i18n("Name");
}
void Addressee::setFormattedName( const QString &formattedName )
{
if ( formattedName == mData->formattedName ) return;
detach();
mData->empty = false;
mData->formattedName = formattedName;
}
QString Addressee::formattedName() const
{
return mData->formattedName;
}
QString Addressee::formattedNameLabel()
{
return i18n("Formatted Name");
}
void Addressee::setFamilyName( const QString &familyName )
{
if ( familyName == mData->familyName ) return;
detach();
mData->empty = false;
mData->familyName = familyName;
}
QString Addressee::familyName() const
{
return mData->familyName;
}
QString Addressee::familyNameLabel()
{
return i18n("Family Name");
}
void Addressee::setGivenName( const QString &givenName )
{
if ( givenName == mData->givenName ) return;
detach();
mData->empty = false;
mData->givenName = givenName;
}
QString Addressee::givenName() const
{
return mData->givenName;
}
QString Addressee::givenNameLabel()
{
return i18n("Given Name");
}
void Addressee::setAdditionalName( const QString &additionalName )
{
if ( additionalName == mData->additionalName ) return;
detach();
mData->empty = false;
mData->additionalName = additionalName;
}
QString Addressee::additionalName() const
{
return mData->additionalName;
}
QString Addressee::additionalNameLabel()
{
return i18n("Additional Names");
}
void Addressee::setPrefix( const QString &prefix )
{
if ( prefix == mData->prefix ) return;
detach();
mData->empty = false;
mData->prefix = prefix;
}
QString Addressee::prefix() const
{
return mData->prefix;
}
QString Addressee::prefixLabel()
{
return i18n("Honorific Prefixes");
}
void Addressee::setSuffix( const QString &suffix )
{
if ( suffix == mData->suffix ) return;
detach();
mData->empty = false;
mData->suffix = suffix;
}
QString Addressee::suffix() const
{
return mData->suffix;
}
QString Addressee::suffixLabel()
{
return i18n("Honorific Suffixes");
}
void Addressee::setNickName( const QString &nickName )
{
if ( nickName == mData->nickName ) return;
detach();
mData->empty = false;
mData->nickName = nickName;
}
QString Addressee::nickName() const
{
return mData->nickName;
}
QString Addressee::nickNameLabel()
{
return i18n("Nick Name");
}
void Addressee::setBirthday( const QDateTime &birthday )
{
if ( birthday == mData->birthday ) return;
detach();
mData->empty = false;
mData->birthday = birthday;
}
QDateTime Addressee::birthday() const
{
return mData->birthday;
}
QString Addressee::birthdayLabel()
{
return i18n("Birthday");
}
QString Addressee::homeAddressStreetLabel()
{
return i18n("Home Address Street");
}
QString Addressee::homeAddressLocalityLabel()
{
return i18n("Home Address Locality");
}
QString Addressee::homeAddressRegionLabel()
{
return i18n("Home Address Region");
}
QString Addressee::homeAddressPostalCodeLabel()
{
return i18n("Home Address Postal Code");
}
QString Addressee::homeAddressCountryLabel()
{
return i18n("Home Address Country");
}
QString Addressee::homeAddressLabelLabel()
{
return i18n("Home Address Label");
}
QString Addressee::businessAddressStreetLabel()
{
return i18n("Business Address Street");
}
QString Addressee::businessAddressLocalityLabel()
{
return i18n("Business Address Locality");
}
QString Addressee::businessAddressRegionLabel()
{
return i18n("Business Address Region");
}
QString Addressee::businessAddressPostalCodeLabel()
{
return i18n("Business Address Postal Code");
}
QString Addressee::businessAddressCountryLabel()
{
return i18n("Business Address Country");
}
QString Addressee::businessAddressLabelLabel()
{
return i18n("Business Address Label");
}
QString Addressee::homePhoneLabel()
{
return i18n("Home Phone");
}
QString Addressee::businessPhoneLabel()
{
return i18n("Business Phone");
}
QString Addressee::mobilePhoneLabel()
{
return i18n("Mobile Phone");
}
QString Addressee::homeFaxLabel()
{
return i18n("Home Fax");
}
QString Addressee::businessFaxLabel()
{
return i18n("Business Fax");
}
QString Addressee::carPhoneLabel()
{
return i18n("Car Phone");
}
QString Addressee::isdnLabel()
{
return i18n("ISDN");
}
QString Addressee::pagerLabel()
{
return i18n("Pager");
}
QString Addressee::sipLabel()
{
return i18n("SIP");
}
QString Addressee::emailLabel()
{
return i18n("Email Address");
}
void Addressee::setMailer( const QString &mailer )
{
if ( mailer == mData->mailer ) return;
detach();
mData->empty = false;
mData->mailer = mailer;
}
QString Addressee::mailer() const
{
return mData->mailer;
}
QString Addressee::mailerLabel()
{
return i18n("Mail Client");
}
void Addressee::setTimeZone( const TimeZone &timeZone )
{
if ( timeZone == mData->timeZone ) return;
detach();
mData->empty = false;
mData->timeZone = timeZone;
}
TimeZone Addressee::timeZone() const
{
return mData->timeZone;
}
QString Addressee::timeZoneLabel()
{
return i18n("Time Zone");
}
void Addressee::setGeo( const Geo &geo )
{
if ( geo == mData->geo ) return;
detach();
mData->empty = false;
mData->geo = geo;
}
Geo Addressee::geo() const
{
return mData->geo;
}
QString Addressee::geoLabel()
{
return i18n("Geographic Position");
}
void Addressee::setTitle( const QString &title )
{
if ( title == mData->title ) return;
detach();
mData->empty = false;
mData->title = title;
}
QString Addressee::title() const
{
return mData->title;
}
QString Addressee::titleLabel()
{
return i18n("Title");
}
void Addressee::setRole( const QString &role )
{
if ( role == mData->role ) return;
detach();
mData->empty = false;
mData->role = role;
}
QString Addressee::role() const
{
return mData->role;
}
QString Addressee::roleLabel()
{
return i18n("Role");
}
void Addressee::setOrganization( const QString &organization )
{
if ( organization == mData->organization ) return;
detach();
mData->empty = false;
mData->organization = organization;
}
QString Addressee::organization() const
{
return mData->organization;
}
QString Addressee::organizationLabel()
{
return i18n("Organization");
}
void Addressee::setNote( const QString &note )
{
if ( note == mData->note ) return;
detach();
mData->empty = false;
mData->note = note;
}
QString Addressee::note() const
{
return mData->note;
}
QString Addressee::noteLabel()
{
return i18n("Note");
}
void Addressee::setProductId( const QString &productId )
{
if ( productId == mData->productId ) return;
detach();
mData->empty = false;
mData->productId = productId;
}
QString Addressee::productId() const
{
return mData->productId;
}
QString Addressee::productIdLabel()
{
return i18n("Product Identifier");
}
void Addressee::setRevision( const QDateTime &revision )
{
if ( revision == mData->revision ) return;
detach();
mData->empty = false;
mData->revision = revision;
}
QDateTime Addressee::revision() const
{
return mData->revision;
}
QString Addressee::revisionLabel()
{
return i18n("Revision Date");
}
void Addressee::setSortString( const QString &sortString )
{
if ( sortString == mData->sortString ) return;
detach();
mData->empty = false;
mData->sortString = sortString;
}
QString Addressee::sortString() const
{
return mData->sortString;
}
QString Addressee::sortStringLabel()
{
return i18n("Sort String");
}
void Addressee::setUrl( const KURL &url )
{
if ( url == mData->url ) return;
detach();
mData->empty = false;
mData->url = url;
}
KURL Addressee::url() const
{
return mData->url;
}
QString Addressee::urlLabel()
{
return i18n("URL");
}
void Addressee::setSecrecy( const Secrecy &secrecy )
{
if ( secrecy == mData->secrecy ) return;
detach();
mData->empty = false;
mData->secrecy = secrecy;
}
Secrecy Addressee::secrecy() const
{
return mData->secrecy;
}
QString Addressee::secrecyLabel()
{
return i18n("Security Class");
}
void Addressee::setLogo( const Picture &logo )
{
if ( logo == mData->logo ) return;
detach();
mData->empty = false;
mData->logo = logo;
}
Picture Addressee::logo() const
{
return mData->logo;
}
QString Addressee::logoLabel()
{
return i18n("Logo");
}
void Addressee::setPhoto( const Picture &photo )
{
if ( photo == mData->photo ) return;
detach();
mData->empty = false;
mData->photo = photo;
}
Picture Addressee::photo() const
{
return mData->photo;
}
QString Addressee::photoLabel()
{
return i18n("Photo");
}
void Addressee::setSound( const Sound &sound )
{
if ( sound == mData->sound ) return;
detach();
mData->empty = false;
mData->sound = sound;
}
Sound Addressee::sound() const
{
return mData->sound;
}
QString Addressee::soundLabel()
{
return i18n("Sound");
}
void Addressee::setAgent( const Agent &agent )
{
if ( agent == mData->agent ) return;
detach();
mData->empty = false;
mData->agent = agent;
}
Agent Addressee::agent() const
{
return mData->agent;
}
QString Addressee::agentLabel()
{
return i18n("Agent");
}
void Addressee::setNameFromString( const QString &str )
{
setFormattedName( str );
setName( str );
static bool first = true;
static QStringList titles;
static QStringList suffixes;
static QStringList prefixes;
if ( first ) {
first = false;
titles += i18n( "Dr." );
titles += i18n( "Miss" );
titles += i18n( "Mr." );
titles += i18n( "Mrs." );
titles += i18n( "Ms." );
titles += i18n( "Prof." );
suffixes += i18n( "I" );
suffixes += i18n( "II" );
suffixes += i18n( "III" );
suffixes += i18n( "Jr." );
suffixes += i18n( "Sr." );
prefixes += "van";
prefixes += "von";
prefixes += "de";
KConfig config( locateLocal( "config", "kabcrc") );
config.setGroup( "General" );
titles += config.readListEntry( "Prefixes" );
titles.remove( "" );
prefixes += config.readListEntry( "Inclusions" );
prefixes.remove( "" );
suffixes += config.readListEntry( "Suffixes" );
suffixes.remove( "" );
}
// clear all name parts
setPrefix( "" );
setGivenName( "" );
setAdditionalName( "" );
setFamilyName( "" );
setSuffix( "" );
if ( str.isEmpty() )
return;
int i = str.find(',');
if( i < 0 ) {
QStringList parts = QStringList::split( " ", str );
int leftOffset = 0;
int rightOffset = parts.count() - 1;
QString suffix;
while ( rightOffset >= 0 ) {
if ( suffixes.contains( parts[ rightOffset ] ) ) {
suffix.prepend(parts[ rightOffset ] + (suffix.isEmpty() ? "" : " "));
rightOffset--;
} else
break;
}
setSuffix( suffix );
if ( rightOffset < 0 )
return;
if ( rightOffset - 1 >= 0 && prefixes.contains( parts[ rightOffset - 1 ].lower() ) ) {
setFamilyName( parts[ rightOffset - 1 ] + " " + parts[ rightOffset ] );
rightOffset--;
} else
setFamilyName( parts[ rightOffset ] );
QString prefix;
while ( leftOffset < rightOffset ) {
if ( titles.contains( parts[ leftOffset ] ) ) {
prefix.append( ( prefix.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
} else
break;
}
setPrefix( prefix );
if ( leftOffset < rightOffset ) {
setGivenName( parts[ leftOffset ] );
leftOffset++;
}
QString additionalName;
while ( leftOffset < rightOffset ) {
additionalName.append( ( additionalName.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
}
setAdditionalName( additionalName );
} else {
QString part1 = str.left( i );
QString part2 = str.mid( i + 1 );
QStringList parts = QStringList::split( " ", part1 );
int leftOffset = 0;
int rightOffset = parts.count() - 1;
QString suffix;
while ( rightOffset >= 0 ) {
if ( suffixes.contains( parts[ rightOffset ] ) ) {
suffix.prepend(parts[ rightOffset ] + (suffix.isEmpty() ? "" : " "));
rightOffset--;
} else
break;
}
setSuffix( suffix );
if ( rightOffset - 1 >= 0 && prefixes.contains( parts[ rightOffset - 1 ].lower() ) ) {
setFamilyName( parts[ rightOffset - 1 ] + " " + parts[ rightOffset ] );
rightOffset--;
} else
setFamilyName( parts[ rightOffset ] );
QString prefix;
while ( leftOffset < rightOffset ) {
if ( titles.contains( parts[ leftOffset ] ) ) {
prefix.append( ( prefix.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
} else
break;
}
parts = QStringList::split( " ", part2 );
leftOffset = 0;
rightOffset = parts.count();
while ( leftOffset < rightOffset ) {
if ( titles.contains( parts[ leftOffset ] ) ) {
prefix.append( ( prefix.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
} else
break;
}
setPrefix( prefix );
if ( leftOffset < rightOffset ) {
setGivenName( parts[ leftOffset ] );
leftOffset++;
}
QString additionalName;
while ( leftOffset < rightOffset ) {
additionalName.append( ( additionalName.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
}
setAdditionalName( additionalName );
}
}
QString Addressee::realName() const
{
if ( !formattedName().isEmpty() )
return formattedName();
QString n = assembledName();
if ( n.isEmpty() )
n = name();
return n;
}
QString Addressee::assembledName() const
{
QString name = prefix() + " " + givenName() + " " + additionalName() + " " +
familyName() + " " + suffix();
return name.simplifyWhiteSpace();
}
QString Addressee::fullEmail( const QString &email ) const
{
QString e;
if ( email.isNull() ) {
e = preferredEmail();
} else {
e = email;
}
if ( e.isEmpty() ) return QString::null;
QString text;
if ( realName().isEmpty() )
text = e;
else
text = assembledName() + " <" + e + ">";
return text;
}
void Addressee::insertEmail( const QString &email, bool preferred )
{
detach();
QStringList::Iterator it = mData->emails.find( email );
if ( it != mData->emails.end() ) {
if ( !preferred || it == mData->emails.begin() ) return;
mData->emails.remove( it );
mData->emails.prepend( email );
} else {
if ( preferred ) {
mData->emails.prepend( email );
} else {
mData->emails.append( email );
}
}
}
void Addressee::removeEmail( const QString &email )
{
detach();
QStringList::Iterator it = mData->emails.find( email );
if ( it == mData->emails.end() ) return;
mData->emails.remove( it );
}
QString Addressee::preferredEmail() const
{
if ( mData->emails.count() == 0 ) return QString::null;
else return mData->emails.first();
}
QStringList Addressee::emails() const
{
return mData->emails;
}
void Addressee::setEmails( const QStringList& emails ) {
detach();
mData->emails = emails;
}
void Addressee::insertPhoneNumber( const PhoneNumber &phoneNumber )
{
detach();
mData->empty = false;
PhoneNumber::List::Iterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( (*it).id() == phoneNumber.id() ) {
*it = phoneNumber;
return;
}
}
mData->phoneNumbers.append( phoneNumber );
}
void Addressee::removePhoneNumber( const PhoneNumber &phoneNumber )
{
detach();
PhoneNumber::List::Iterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( (*it).id() == phoneNumber.id() ) {
mData->phoneNumbers.remove( it );
return;
}
}
}
PhoneNumber Addressee::phoneNumber( int type ) const
{
PhoneNumber phoneNumber( "", type );
PhoneNumber::List::ConstIterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( matchBinaryPatternP( (*it).type(), type ) ) {
if ( (*it).type() & PhoneNumber::Pref )
return (*it);
else if ( phoneNumber.number().isEmpty() )
phoneNumber = (*it);
}
}
return phoneNumber;
}
PhoneNumber::List Addressee::phoneNumbers() const
{
return mData->phoneNumbers;
}
PhoneNumber::List Addressee::phoneNumbers( int type ) const
{
PhoneNumber::List list;
PhoneNumber::List::ConstIterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( matchBinaryPattern( (*it).type(), type ) ) {
list.append( *it );
}
}
return list;
}
PhoneNumber Addressee::findPhoneNumber( const QString &id ) const
{
PhoneNumber::List::ConstIterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( (*it).id() == id ) {
return *it;
}
}
return PhoneNumber();
}
void Addressee::insertKey( const Key &key )
{
detach();
mData->empty = false;
Key::List::Iterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).id() == key.id() ) {
*it = key;
return;
}
}
mData->keys.append( key );
}
void Addressee::removeKey( const Key &key )
{
detach();
Key::List::Iterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).id() == key.id() ) {
mData->keys.remove( key );
return;
}
}
}
Key Addressee::key( int type, QString customTypeString ) const
{
Key::List::ConstIterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).type() == type ) {
if ( type == Key::Custom ) {
if ( customTypeString.isEmpty() ) {
return *it;
} else {
if ( (*it).customTypeString() == customTypeString )
return (*it);
}
} else {
return *it;
}
}
}
return Key( QString(), type );
}
void Addressee::setKeys( const Key::List& list ) {
detach();
mData->keys = list;
}
Key::List Addressee::keys() const
{
return mData->keys;
}
Key::List Addressee::keys( int type, QString customTypeString ) const
{
Key::List list;
Key::List::ConstIterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).type() == type ) {
if ( type == Key::Custom ) {
if ( customTypeString.isEmpty() ) {
list.append(*it);
} else {
if ( (*it).customTypeString() == customTypeString )
list.append(*it);
}
} else {
list.append(*it);
}
}
}
return list;
}
Key Addressee::findKey( const QString &id ) const
{
Key::List::ConstIterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).id() == id ) {
return *it;
}
}
return Key();
}
QString Addressee::asString() const
{
return "Smith, agent Smith...";
}
void Addressee::dump() const
{
return;
kdDebug(5700) << "Addressee {" << endl;
kdDebug(5700) << " Uid: '" << uid() << "'" << endl;
kdDebug(5700) << " Name: '" << name() << "'" << endl;
kdDebug(5700) << " FormattedName: '" << formattedName() << "'" << endl;
kdDebug(5700) << " FamilyName: '" << familyName() << "'" << endl;
kdDebug(5700) << " GivenName: '" << givenName() << "'" << endl;
kdDebug(5700) << " AdditionalName: '" << additionalName() << "'" << endl;
kdDebug(5700) << " Prefix: '" << prefix() << "'" << endl;
kdDebug(5700) << " Suffix: '" << suffix() << "'" << endl;
kdDebug(5700) << " NickName: '" << nickName() << "'" << endl;
kdDebug(5700) << " Birthday: '" << birthday().toString() << "'" << endl;
kdDebug(5700) << " Mailer: '" << mailer() << "'" << endl;
kdDebug(5700) << " TimeZone: '" << timeZone().asString() << "'" << endl;
kdDebug(5700) << " Geo: '" << geo().asString() << "'" << endl;
kdDebug(5700) << " Title: '" << title() << "'" << endl;
kdDebug(5700) << " Role: '" << role() << "'" << endl;
kdDebug(5700) << " Organization: '" << organization() << "'" << endl;
kdDebug(5700) << " Note: '" << note() << "'" << endl;
kdDebug(5700) << " ProductId: '" << productId() << "'" << endl;
kdDebug(5700) << " Revision: '" << revision().toString() << "'" << endl;
kdDebug(5700) << " SortString: '" << sortString() << "'" << endl;
kdDebug(5700) << " Url: '" << url().url() << "'" << endl;
kdDebug(5700) << " Secrecy: '" << secrecy().asString() << "'" << endl;
kdDebug(5700) << " Logo: '" << logo().asString() << "'" << endl;
kdDebug(5700) << " Photo: '" << photo().asString() << "'" << endl;
kdDebug(5700) << " Sound: '" << sound().asString() << "'" << endl;
kdDebug(5700) << " Agent: '" << agent().asString() << "'" << endl;
kdDebug(5700) << " Emails {" << endl;
QStringList e = emails();
QStringList::ConstIterator it;
for( it = e.begin(); it != e.end(); ++it ) {
kdDebug(5700) << " " << (*it) << endl;
}
kdDebug(5700) << " }" << endl;
kdDebug(5700) << " PhoneNumbers {" << endl;
PhoneNumber::List p = phoneNumbers();
PhoneNumber::List::ConstIterator it2;
for( it2 = p.begin(); it2 != p.end(); ++it2 ) {
kdDebug(5700) << " Type: " << int((*it2).type()) << " Number: " << (*it2).number() << endl;
}
kdDebug(5700) << " }" << endl;
Address::List a = addresses();
Address::List::ConstIterator it3;
for( it3 = a.begin(); it3 != a.end(); ++it3 ) {
(*it3).dump();
}
kdDebug(5700) << " Keys {" << endl;
Key::List k = keys();
Key::List::ConstIterator it4;
for( it4 = k.begin(); it4 != k.end(); ++it4 ) {
kdDebug(5700) << " Type: " << int((*it4).type()) <<
" Key: " << (*it4).textData() <<
" CustomString: " << (*it4).customTypeString() << endl;
}
kdDebug(5700) << " }" << endl;
kdDebug(5700) << "}" << endl;
}
void Addressee::insertAddress( const Address &address )
{
detach();
mData->empty = false;
Address::List::Iterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( (*it).id() == address.id() ) {
*it = address;
return;
}
}
mData->addresses.append( address );
}
void Addressee::removeAddress( const Address &address )
{
detach();
Address::List::Iterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( (*it).id() == address.id() ) {
mData->addresses.remove( it );
return;
}
}
}
Address Addressee::address( int type ) const
{
Address address( type );
Address::List::ConstIterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( matchBinaryPatternA( (*it).type(), type ) ) {
if ( (*it).type() & Address::Pref )
return (*it);
else if ( address.isEmpty() )
address = (*it);
}
}
return address;
}
Address::List Addressee::addresses() const
{
return mData->addresses;
}
Address::List Addressee::addresses( int type ) const
{
Address::List list;
Address::List::ConstIterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( matchBinaryPattern( (*it).type(), type ) ) {
list.append( *it );
}
}
return list;
}
Address Addressee::findAddress( const QString &id ) const
{
Address::List::ConstIterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( (*it).id() == id ) {
return *it;
}
}
return Address();
}
void Addressee::insertCategory( const QString &c )
{
detach();
mData->empty = false;
if ( mData->categories.contains( c ) ) return;
mData->categories.append( c );
}
void Addressee::removeCategory( const QString &c )
{
detach();
QStringList::Iterator it = mData->categories.find( c );
if ( it == mData->categories.end() ) return;
mData->categories.remove( it );
}
bool Addressee::hasCategory( const QString &c ) const
{
return ( mData->categories.contains( c ) );
}
void Addressee::setCategories( const QStringList &c )
{
detach();
mData->empty = false;
mData->categories = c;
}
QStringList Addressee::categories() const
{
return mData->categories;
}
void Addressee::insertCustom( const QString &app, const QString &name,
const QString &value )
{
if ( value.isNull() || name.isEmpty() || app.isEmpty() ) return;
detach();
mData->empty = false;
QString qualifiedName = app + "-" + name + ":";
QStringList::Iterator it;
for( it = mData->custom.begin(); it != mData->custom.end(); ++it ) {
if ( (*it).startsWith( qualifiedName ) ) {
(*it) = qualifiedName + value;
return;
}
}
mData->custom.append( qualifiedName + value );
}
void Addressee::removeCustom( const QString &app, const QString &name)
{
detach();
QString qualifiedName = app + "-" + name + ":";
QStringList::Iterator it;
for( it = mData->custom.begin(); it != mData->custom.end(); ++it ) {
if ( (*it).startsWith( qualifiedName ) ) {
mData->custom.remove( it );
return;
}
}
}
QString Addressee::custom( const QString &app, const QString &name ) const
{
QString qualifiedName = app + "-" + name + ":";
QString value;
QStringList::ConstIterator it;
for( it = mData->custom.begin(); it != mData->custom.end(); ++it ) {
if ( (*it).startsWith( qualifiedName ) ) {
value = (*it).mid( (*it).find( ":" ) + 1 );
break;
}
}
return value;
}
void Addressee::setCustoms( const QStringList &l )
{
detach();
mData->empty = false;
mData->custom = l;
}
QStringList Addressee::customs() const
{
return mData->custom;
}
void Addressee::parseEmailAddress( const QString &rawEmail, QString &fullName,
QString &email)
{
int startPos, endPos, len;
QString partA, partB, result;
char endCh = '>';
startPos = rawEmail.find('<');
if (startPos < 0)
{
startPos = rawEmail.find('(');
endCh = ')';
}
if (startPos < 0)
{
// We couldn't find any separators, so we assume the whole string
// is the email address
email = rawEmail;
fullName = "";
}
else
{
// We have a start position, try to find an end
endPos = rawEmail.find(endCh, startPos+1);
if (endPos < 0)
{
// We couldn't find the end of the email address. We can only
// assume the entire string is the email address.
email = rawEmail;
fullName = "";
}
else
{
// We have a start and end to the email address
// Grab the name part
fullName = rawEmail.left(startPos).stripWhiteSpace();
// grab the email part
email = rawEmail.mid(startPos+1, endPos-startPos-1).stripWhiteSpace();
// Check that we do not have any extra characters on the end of the
// strings
len = fullName.length();
if (fullName[0]=='"' && fullName[len-1]=='"')
fullName = fullName.mid(1, len-2);
else if (fullName[0]=='<' && fullName[len-1]=='>')
fullName = fullName.mid(1, len-2);
else if (fullName[0]=='(' && fullName[len-1]==')')
fullName = fullName.mid(1, len-2);
}
}
}
void Addressee::setResource( Resource *resource )
{
detach();
mData->resource = resource;
}
Resource *Addressee::resource() const
{
return mData->resource;
}
//US
QString Addressee::resourceLabel()
{
return i18n("Resource");
}
void Addressee::setChanged( bool value )
{
detach();
mData->changed = value;
}
bool Addressee::changed() const
{
return mData->changed;
}
void Addressee::setTagged( bool value )
{
detach();
mData->tagged = value;
}
bool Addressee::tagged() const
{
return mData->tagged;
}
QDataStream &KABC::operator<<( QDataStream &s, const Addressee &a )
{
if (!a.mData) return s;
s << a.uid();
s << a.mData->name;
s << a.mData->formattedName;
s << a.mData->familyName;
s << a.mData->givenName;
s << a.mData->additionalName;
s << a.mData->prefix;
s << a.mData->suffix;
s << a.mData->nickName;
s << a.mData->birthday;
s << a.mData->mailer;
s << a.mData->timeZone;
s << a.mData->geo;
s << a.mData->title;
s << a.mData->role;
s << a.mData->organization;
s << a.mData->note;
s << a.mData->productId;
s << a.mData->revision;
s << a.mData->sortString;
s << a.mData->url;
s << a.mData->secrecy;
s << a.mData->logo;
s << a.mData->photo;
s << a.mData->sound;
s << a.mData->agent;
s << a.mData->phoneNumbers;
s << a.mData->addresses;
s << a.mData->emails;
s << a.mData->categories;
s << a.mData->custom;
s << a.mData->keys;
return s;
}
QDataStream &KABC::operator>>( QDataStream &s, Addressee &a )
{
if (!a.mData) return s;
s >> a.mData->uid;
s >> a.mData->name;
s >> a.mData->formattedName;
s >> a.mData->familyName;
s >> a.mData->givenName;
s >> a.mData->additionalName;
s >> a.mData->prefix;
s >> a.mData->suffix;
s >> a.mData->nickName;
s >> a.mData->birthday;
s >> a.mData->mailer;
s >> a.mData->timeZone;
s >> a.mData->geo;
s >> a.mData->title;
s >> a.mData->role;
s >> a.mData->organization;
s >> a.mData->note;
s >> a.mData->productId;
s >> a.mData->revision;
s >> a.mData->sortString;
s >> a.mData->url;
s >> a.mData->secrecy;
s >> a.mData->logo;
s >> a.mData->photo;
s >> a.mData->sound;
s >> a.mData->agent;
s >> a.mData->phoneNumbers;
s >> a.mData->addresses;
s >> a.mData->emails;
s >> a.mData->categories;
s >> a.mData->custom;
s >> a.mData->keys;
a.mData->empty = false;
return s;
}
bool matchBinaryPattern( int value, int pattern )
{
/**
We want to match all telephonnumbers/addresses which have the bits in the
pattern set. More are allowed.
if pattern == 0 we have a special handling, then we want only those with
exactly no bit set.
*/
if ( pattern == 0 )
return ( value == 0 );
else
return ( pattern == ( pattern & value ) );
}
bool matchBinaryPatternP( int value, int pattern )
{
if ( pattern == 0 )
return ( value == 0 );
else
return ( (pattern |PhoneNumber::Pref ) == ( value |PhoneNumber::Pref ) );
}
bool matchBinaryPatternA( int value, int pattern )
{
if ( pattern == 0 )
return ( value == 0 );
else
return ( (pattern | Address::Pref) == ( value | Address::Pref ) );
}
diff --git a/kabc/addressee.h b/kabc/addressee.h
index 0aa2c51..03138f6 100644
--- a/kabc/addressee.h
+++ b/kabc/addressee.h
@@ -1,852 +1,853 @@
/*** Warning! This file has been generated by the script makeaddressee ***/
/*
This file is part of libkabc.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/*
Enhanced Version of the file for platform independent KDE tools.
Copyright (c) 2004 Ulf Schenk
$Id$
*/
#ifndef KABC_ADDRESSEE_H
#define KABC_ADDRESSEE_H
#include <qdatetime.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qvaluelist.h>
#include <ksharedptr.h>
#include <kurl.h>
#include "address.h"
#include "agent.h"
#include "geo.h"
#include "key.h"
#include "phonenumber.h"
#include "picture.h"
#include "secrecy.h"
#include "sound.h"
#include "timezone.h"
namespace KABC {
class Resource;
/**
@short address book entry
This class represents an entry in the address book.
The data of this class is implicitly shared. You can pass this class by value.
If you need the name of a field for presenting it to the user you should use
the functions ending in Label(). They return a translated string which can be
used as label for the corresponding field.
About the name fields:
givenName() is the first name and familyName() the last name. In some
countries the family name comes first, that's the reason for the
naming. formattedName() is the full name with the correct formatting.
It is used as an override, when the correct formatting can't be generated
from the other name fields automatically.
realName() returns a fully formatted name(). It uses formattedName, if set,
otherwise it constucts the name from the name fields. As fallback, if
nothing else is set it uses name().
name() is the NAME type of RFC2426. It can be used as internal name for the
data enty, but shouldn't be used for displaying the data to the user.
*/
class Addressee
{
friend QDataStream &operator<<( QDataStream &, const Addressee & );
friend QDataStream &operator>>( QDataStream &, Addressee & );
public:
typedef QValueList<Addressee> List;
/**
Construct an empty address book entry.
*/
Addressee();
~Addressee();
Addressee( const Addressee & );
Addressee &operator=( const Addressee & );
bool operator==( const Addressee & ) const;
bool operator!=( const Addressee & ) const;
// sync stuff
void setTempSyncStat(int id);
int tempSyncStat() const;
void setIDStr( const QString & );
QString IDStr() const;
void setID( const QString &, const QString & );
QString getID( const QString & );
void setCsum( const QString &, const QString & );
QString getCsum( const QString & );
void removeID(const QString &);
void computeCsum(const QString &dev);
ulong getCsum4List( const QStringList & attList);
/**
Return, if the address book entry is empty.
*/
bool isEmpty() const;
void setExternalUID( const QString &id );
QString externalUID() const;
void setOriginalExternalUID( const QString &id );
QString originalExternalUID() const;
void mergeContact( const Addressee& ad );
void simplifyEmails();
void simplifyAddresses();
void simplifyPhoneNumbers();
void simplifyPhoneNumberTypes();
bool removeVoice();
+ bool containsAdr(const Addressee& addr );
/**
Set unique identifier.
*/
void setUid( const QString &uid );
/**
Return unique identifier.
*/
QString uid() const;
/**
Return translated label for uid field.
*/
static QString uidLabel();
/**
Set name.
*/
void setName( const QString &name );
/**
Return name.
*/
QString name() const;
/**
Return translated label for name field.
*/
static QString nameLabel();
/**
Set formatted name.
*/
void setFormattedName( const QString &formattedName );
/**
Return formatted name.
*/
QString formattedName() const;
/**
Return translated label for formattedName field.
*/
static QString formattedNameLabel();
/**
Set family name.
*/
void setFamilyName( const QString &familyName );
/**
Return family name.
*/
QString familyName() const;
/**
Return translated label for familyName field.
*/
static QString familyNameLabel();
/**
Set given name.
*/
void setGivenName( const QString &givenName );
/**
Return given name.
*/
QString givenName() const;
/**
Return translated label for givenName field.
*/
static QString givenNameLabel();
/**
Set additional names.
*/
void setAdditionalName( const QString &additionalName );
/**
Return additional names.
*/
QString additionalName() const;
/**
Return translated label for additionalName field.
*/
static QString additionalNameLabel();
/**
Set honorific prefixes.
*/
void setPrefix( const QString &prefix );
/**
Return honorific prefixes.
*/
QString prefix() const;
/**
Return translated label for prefix field.
*/
static QString prefixLabel();
/**
Set honorific suffixes.
*/
void setSuffix( const QString &suffix );
/**
Return honorific suffixes.
*/
QString suffix() const;
/**
Return translated label for suffix field.
*/
static QString suffixLabel();
/**
Set nick name.
*/
void setNickName( const QString &nickName );
/**
Return nick name.
*/
QString nickName() const;
/**
Return translated label for nickName field.
*/
static QString nickNameLabel();
/**
Set birthday.
*/
void setBirthday( const QDateTime &birthday );
/**
Return birthday.
*/
QDateTime birthday() const;
/**
Return translated label for birthday field.
*/
static QString birthdayLabel();
/**
Return translated label for homeAddressStreet field.
*/
static QString homeAddressStreetLabel();
/**
Return translated label for homeAddressLocality field.
*/
static QString homeAddressLocalityLabel();
/**
Return translated label for homeAddressRegion field.
*/
static QString homeAddressRegionLabel();
/**
Return translated label for homeAddressPostalCode field.
*/
static QString homeAddressPostalCodeLabel();
/**
Return translated label for homeAddressCountry field.
*/
static QString homeAddressCountryLabel();
/**
Return translated label for homeAddressLabel field.
*/
static QString homeAddressLabelLabel();
/**
Return translated label for businessAddressStreet field.
*/
static QString businessAddressStreetLabel();
/**
Return translated label for businessAddressLocality field.
*/
static QString businessAddressLocalityLabel();
/**
Return translated label for businessAddressRegion field.
*/
static QString businessAddressRegionLabel();
/**
Return translated label for businessAddressPostalCode field.
*/
static QString businessAddressPostalCodeLabel();
/**
Return translated label for businessAddressCountry field.
*/
static QString businessAddressCountryLabel();
/**
Return translated label for businessAddressLabel field.
*/
static QString businessAddressLabelLabel();
/**
Return translated label for homePhone field.
*/
static QString homePhoneLabel();
/**
Return translated label for businessPhone field.
*/
static QString businessPhoneLabel();
/**
Return translated label for mobilePhone field.
*/
static QString mobilePhoneLabel();
/**
Return translated label for homeFax field.
*/
static QString homeFaxLabel();
/**
Return translated label for businessFax field.
*/
static QString businessFaxLabel();
/**
Return translated label for carPhone field.
*/
static QString carPhoneLabel();
/**
Return translated label for isdn field.
*/
static QString isdnLabel();
/**
Return translated label for pager field.
*/
static QString pagerLabel();
/**
Return translated label for sip field.
*/
static QString sipLabel();
/**
Return translated label for email field.
*/
static QString emailLabel();
/**
Set mail client.
*/
void setMailer( const QString &mailer );
/**
Return mail client.
*/
QString mailer() const;
/**
Return translated label for mailer field.
*/
static QString mailerLabel();
/**
Set time zone.
*/
void setTimeZone( const TimeZone &timeZone );
/**
Return time zone.
*/
TimeZone timeZone() const;
/**
Return translated label for timeZone field.
*/
static QString timeZoneLabel();
/**
Set geographic position.
*/
void setGeo( const Geo &geo );
/**
Return geographic position.
*/
Geo geo() const;
/**
Return translated label for geo field.
*/
static QString geoLabel();
/**
Set title.
*/
void setTitle( const QString &title );
/**
Return title.
*/
QString title() const;
/**
Return translated label for title field.
*/
static QString titleLabel();
/**
Set role.
*/
void setRole( const QString &role );
/**
Return role.
*/
QString role() const;
/**
Return translated label for role field.
*/
static QString roleLabel();
/**
Set organization.
*/
void setOrganization( const QString &organization );
/**
Return organization.
*/
QString organization() const;
/**
Return translated label for organization field.
*/
static QString organizationLabel();
/**
Set note.
*/
void setNote( const QString &note );
/**
Return note.
*/
QString note() const;
/**
Return translated label for note field.
*/
static QString noteLabel();
/**
Set product identifier.
*/
void setProductId( const QString &productId );
/**
Return product identifier.
*/
QString productId() const;
/**
Return translated label for productId field.
*/
static QString productIdLabel();
/**
Set revision date.
*/
void setRevision( const QDateTime &revision );
/**
Return revision date.
*/
QDateTime revision() const;
/**
Return translated label for revision field.
*/
static QString revisionLabel();
/**
Set sort string.
*/
void setSortString( const QString &sortString );
/**
Return sort string.
*/
QString sortString() const;
/**
Return translated label for sortString field.
*/
static QString sortStringLabel();
/**
Set URL.
*/
void setUrl( const KURL &url );
/**
Return URL.
*/
KURL url() const;
/**
Return translated label for url field.
*/
static QString urlLabel();
/**
Set security class.
*/
void setSecrecy( const Secrecy &secrecy );
/**
Return security class.
*/
Secrecy secrecy() const;
/**
Return translated label for secrecy field.
*/
static QString secrecyLabel();
/**
Set logo.
*/
void setLogo( const Picture &logo );
/**
Return logo.
*/
Picture logo() const;
/**
Return translated label for logo field.
*/
static QString logoLabel();
/**
Set photo.
*/
void setPhoto( const Picture &photo );
/**
Return photo.
*/
Picture photo() const;
/**
Return translated label for photo field.
*/
static QString photoLabel();
/**
Set sound.
*/
void setSound( const Sound &sound );
/**
Return sound.
*/
Sound sound() const;
/**
Return translated label for sound field.
*/
static QString soundLabel();
/**
Set agent.
*/
void setAgent( const Agent &agent );
/**
Return agent.
*/
Agent agent() const;
/**
Return translated label for agent field.
*/
static QString agentLabel();
/**
Set name fields by parsing the given string and trying to associate the
parts of the string with according fields. This function should probably
be a bit more clever.
*/
void setNameFromString( const QString & );
/**
Return the name of the addressee. This is calculated from all the name
fields.
*/
QString realName() const;
/**
Return the name that consists of all name parts.
*/
QString assembledName() const;
/**
Return email address including real name.
@param email Email address to be used to construct the full email string.
If this is QString::null the preferred email address is used.
*/
QString fullEmail( const QString &email=QString::null ) const;
/**
Insert an email address. If the email address already exists in this
addressee it is not duplicated.
@param email Email address
@param preferred Set to true, if this is the preferred email address of
the addressee.
*/
void insertEmail( const QString &email, bool preferred=false );
/**
Remove email address. If the email address doesn't exist, nothing happens.
*/
void removeEmail( const QString &email );
/**
Return preferred email address. This is the first email address or the
last one added with @ref insertEmail() with a set preferred parameter.
*/
QString preferredEmail() const;
/**
Return list of all email addresses.
*/
QStringList emails() const;
/**
Set the emails to @param.
The first email address gets the preferred one!
@param list The list of email addresses.
*/
void setEmails( const QStringList& list);
/**
Insert a phone number. If a phone number with the same id already exists
in this addressee it is not duplicated.
*/
void insertPhoneNumber( const PhoneNumber &phoneNumber );
/**
Remove phone number. If no phone number with the given id exists for this
addresse nothing happens.
*/
void removePhoneNumber( const PhoneNumber &phoneNumber );
/**
Return phone number, which matches the given type.
*/
PhoneNumber phoneNumber( int type ) const;
/**
Return list of all phone numbers.
*/
PhoneNumber::List phoneNumbers() const;
/**
Return list of phone numbers with a special type.
*/
PhoneNumber::List phoneNumbers( int type ) const;
/**
Return phone number with the given id.
*/
PhoneNumber findPhoneNumber( const QString &id ) const;
/**
Insert a key. If a key with the same id already exists
in this addressee it is not duplicated.
*/
void insertKey( const Key &key );
/**
Remove a key. If no key with the given id exists for this
addresse nothing happens.
*/
void removeKey( const Key &key );
/**
Return key, which matches the given type.
If @p type == Key::Custom you can specify a string
that should match. If you leave the string empty, the first
key with a custom value is returned.
*/
Key key( int type, QString customTypeString = QString::null ) const;
/**
Return list of all keys.
*/
Key::List keys() const;
/**
Set the list of keys
@param keys The keys to be set.
*/
void setKeys( const Key::List& keys);
/**
Return list of keys with a special type.
If @p type == Key::Custom you can specify a string
that should match. If you leave the string empty, all custom
keys will be returned.
*/
Key::List keys( int type, QString customTypeString = QString::null ) const;
/**
Return key with the given id.
*/
Key findKey( const QString &id ) const;
/**
Insert an address. If an address with the same id already exists
in this addressee it is not duplicated.
*/
void insertAddress( const Address &address );
/**
Remove address. If no address with the given id exists for this
addresse nothing happens.
*/
void removeAddress( const Address &address );
/**
Return address, which matches the given type.
*/
Address address( int type ) const;
/**
Return list of all addresses.
*/
Address::List addresses() const;
/**
Return list of addresses with a special type.
*/
Address::List addresses( int type ) const;
/**
Return address with the given id.
*/
Address findAddress( const QString &id ) const;
/**
Insert category. If the category already exists it is not duplicated.
*/
void insertCategory( const QString & );
/**
Remove category.
*/
void removeCategory( const QString & );
/**
Return, if addressee has the given category.
*/
bool hasCategory( const QString & ) const;
/**
Set categories to given value.
*/
void setCategories( const QStringList & );
/**
Return list of all set categories.
*/
QStringList categories() const;
/**
Insert custom entry. The entry is identified by the name of the inserting
application and a unique name. If an entry with the given app and name
already exists its value is replaced with the new given value.
*/
void insertCustom( const QString &app, const QString &name,
const QString &value );
/**
Remove custom entry.
*/
void removeCustom( const QString &app, const QString &name );
/**
Return value of custom entry, identified by app and entry name.
*/
QString custom( const QString &app, const QString &name ) const;
/**
Set all custom entries.
*/
void setCustoms( const QStringList & );
/**
Return list of all custom entries.
*/
QStringList customs() const;
/**
Parse full email address. The result is given back in fullName and email.
*/
static void parseEmailAddress( const QString &rawEmail, QString &fullName,
QString &email );
/**
Debug output.
*/
void dump() const;
/**
Returns string representation of the addressee.
*/
QString asString() const;
/**
Set resource where the addressee is from.
*/
void setResource( Resource *resource );
/**
Return pointer to resource.
*/
Resource *resource() const;
/**
Return resourcelabel.
*/
//US
static QString resourceLabel();
/**
Mark addressee as changed.
*/
void setChanged( bool value );
/**
Return whether the addressee is changed.
*/
bool changed() const;
void setTagged( bool value );
bool tagged() const;
private:
Addressee copy();
void detach();
struct AddresseeData;
mutable KSharedPtr<AddresseeData> mData;
};
QDataStream &operator<<( QDataStream &, const Addressee & );
QDataStream &operator>>( QDataStream &, Addressee & );
}
#endif
diff --git a/kabc/phonenumber.cpp b/kabc/phonenumber.cpp
index e5abc0e..6e94c7e 100644
--- a/kabc/phonenumber.cpp
+++ b/kabc/phonenumber.cpp
@@ -1,225 +1,223 @@
/*
This file is part of libkabc.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/*
Enhanced Version of the file for platform independent KDE tools.
Copyright (c) 2004 Ulf Schenk
$Id$
*/
#include <kapplication.h>
#include <klocale.h>
#include "phonenumber.h"
using namespace KABC;
PhoneNumber::PhoneNumber() :
mType( Home )
{
init();
}
PhoneNumber::PhoneNumber( const QString &number, int type ) :
mType( type ), mNumber( number )
{
init();
}
PhoneNumber::~PhoneNumber()
{
}
void PhoneNumber::init()
{
mId = KApplication::randomString( 8 );
}
bool PhoneNumber::operator==( const PhoneNumber &p ) const
{
if ( mNumber != p.mNumber ) return false;
if ( mType != p.mType ) return false;
return true;
}
bool PhoneNumber::operator!=( const PhoneNumber &p ) const
{
return !( p == *this );
}
bool PhoneNumber::simplifyNumber()
{
QString Number;
int i;
Number = mNumber.stripWhiteSpace ();
mNumber = "";
- if ( Number.at(0) == '+' )
- mNumber += "+";
for ( i = 0; i < Number.length(); ++i) {
- if ( Number.at(i).isDigit() )
+ if ( Number.at(i).isDigit() || Number.at(i) == '+'|| Number.at(i) == '*'|| Number.at(i) == '#' )
mNumber += Number.at(i);
}
return ( mNumber.length() > 0 );
}
// make cellphone compatible
void PhoneNumber::simplifyType()
{
if ( mType & Fax ) mType = Fax;
else if ( mType & Cell ) mType = Cell;
else if ( mType & Work ) mType = Work ;
else if ( mType & Home ) mType = Home;
else mType = Pref;
}
void PhoneNumber::setId( const QString &id )
{
mId = id;
}
QString PhoneNumber::id() const
{
return mId;
}
void PhoneNumber::setNumber( const QString &number )
{
mNumber = number;
}
QString PhoneNumber::number() const
{
return mNumber;
}
void PhoneNumber::setType( int type )
{
mType = type;
}
int PhoneNumber::type() const
{
return mType;
}
QString PhoneNumber::typeLabel() const
{
QString label;
bool first = true;
TypeList list = typeList();
TypeList::Iterator it;
for ( it = list.begin(); it != list.end(); ++it ) {
if ( ( type() & (*it) ) && ( (*it) != Pref ) ) {
label.append( ( first ? "" : "/" ) + typeLabel( *it ) );
if ( first )
first = false;
}
}
return label;
}
QString PhoneNumber::label() const
{
return typeLabel( type() );
}
PhoneNumber::TypeList PhoneNumber::typeList()
{
TypeList list;
list << Home << Work << Msg << Pref << Voice << Fax << Cell << Video
<< Bbs << Modem << Car << Isdn << Pcs << Pager << Sip;
return list;
}
QString PhoneNumber::label( int type )
{
return typeLabel( type );
}
QString PhoneNumber::typeLabel( int type )
{
QString typeString;
if ((type & Home) == Home)
typeString += i18n("Home");
else if ((type & Work) == Work)
typeString += i18n("Work");
if (!typeString.isEmpty())
typeString += " ";
if ((type & Cell) == Cell)
typeString += i18n("Mobile");
else if ((type & Fax) == Fax)
typeString += i18n("Fax");
else if ((type & Msg) == Msg)
typeString += i18n("Messenger");
else if ((type & Voice) == Voice) {
// add nothing in case of the Voice flag
// typeString += i18n("Voice");
}
else if ((type & Video) == Video)
typeString += i18n("Video");
else if ((type & Bbs) == Bbs)
typeString += i18n("Mailbox");
else if ((type & Modem) == Modem)
typeString += i18n("Modem");
else if ((type & Car) == Car)
typeString += i18n("Car");
else if ((type & Isdn) == Isdn)
typeString += i18n("ISDN");
else if ((type & Pcs) == Pcs)
typeString += i18n("PCS");
else if ((type & Pager) == Pager)
typeString += i18n("Pager");
else if ((type & Sip) == Sip)
typeString += i18n("SIP");
// add the prefered flag
if (!typeString.isEmpty())
typeString += " ";
if ((type & Pref) == Pref)
typeString += i18n("(p)");
//if we still have no match, return "other"
if (typeString.isEmpty())
return i18n("Other");
return typeString;
}
QDataStream &KABC::operator<<( QDataStream &s, const PhoneNumber &phone )
{
return s << phone.mId << phone.mType << phone.mNumber;
}
QDataStream &KABC::operator>>( QDataStream &s, PhoneNumber &phone )
{
s >> phone.mId >> phone.mType >> phone.mNumber;
return s;
}
diff --git a/kaddressbook/kabcore.cpp b/kaddressbook/kabcore.cpp
index a7967cb..cd261f6 100644
--- a/kaddressbook/kabcore.cpp
+++ b/kaddressbook/kabcore.cpp
@@ -1,2924 +1,2872 @@
/*
This file is part of KAddressbook.
Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
/*s
Enhanced Version of the file for platform independent KDE tools.
Copyright (c) 2004 Ulf Schenk
$Id$
*/
#include "kabcore.h"
#include <stdaddressbook.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <qtimer.h>
#include <qlabel.h>
#include <qregexp.h>
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qpushbutton.h>
#include <qprogressbar.h>
#include <libkdepim/phoneaccess.h>
#ifndef KAB_EMBEDDED
#include <qclipboard.h>
#include <qdir.h>
#include <qfile.h>
#include <qapplicaton.h>
#include <qprogressbar.h>
#include <qlayout.h>
#include <qregexp.h>
#include <qvbox.h>
#include <kabc/addresseelist.h>
#include <kabc/errorhandler.h>
#include <kabc/resource.h>
#include <kabc/vcardconverter.h>
#include <kapplication.h>
#include <kactionclasses.h>
#include <kcmultidialog.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <kkeydialog.h>
#include <kmessagebox.h>
#include <kprinter.h>
#include <kprotocolinfo.h>
#include <kresources/selectdialog.h>
#include <kstandarddirs.h>
#include <ktempfile.h>
#include <kxmlguiclient.h>
#include <kaboutdata.h>
#include <libkdepim/categoryselectdialog.h>
#include "addresseeutil.h"
#include "addresseeeditordialog.h"
#include "extensionmanager.h"
#include "kstdaction.h"
#include "kaddressbookservice.h"
#include "ldapsearchdialog.h"
#include "printing/printingwizard.h"
#else // KAB_EMBEDDED
#include <kapplication.h>
#include "KDGanttMinimizeSplitter.h"
#include "kaddressbookmain.h"
#include "kactioncollection.h"
#include "addresseedialog.h"
//US
#include <addresseeview.h>
#include <qapp.h>
#include <qmenubar.h>
//#include <qtoolbar.h>
#include <qmessagebox.h>
#include <kdebug.h>
#include <kiconloader.h> // needed for SmallIcon
#include <kresources/kcmkresources.h>
#include <ktoolbar.h>
//#include <qlabel.h>
#ifndef DESKTOP_VERSION
#include <qpe/ir.h>
#include <qpe/qpemenubar.h>
#include <qtopia/qcopenvelope_qws.h>
#else
#include <qmenubar.h>
#endif
#endif // KAB_EMBEDDED
#include "kcmconfigs/kcmkabconfig.h"
#include "kcmconfigs/kcmkdepimconfig.h"
#include "kpimglobalprefs.h"
#include "externalapphandler.h"
#include <kresources/selectdialog.h>
#include <kmessagebox.h>
#include <picture.h>
#include <resource.h>
//US#include <qsplitter.h>
#include <qmap.h>
#include <qdir.h>
#include <qfile.h>
#include <qvbox.h>
#include <qlayout.h>
#include <qclipboard.h>
#include <qtextstream.h>
#include <libkdepim/categoryselectdialog.h>
#include <kabc/vcardconverter.h>
#include "addresseeutil.h"
#include "undocmds.h"
#include "addresseeeditordialog.h"
#include "viewmanager.h"
#include "details/detailsviewcontainer.h"
#include "kabprefs.h"
#include "xxportmanager.h"
#include "incsearchwidget.h"
#include "jumpbuttonbar.h"
#include "extensionmanager.h"
#include "addresseeconfig.h"
#include <kcmultidialog.h>
#ifdef _WIN32_
#include "kaimportoldialog.h"
#else
#include <unistd.h>
#endif
// sync includes
#include <libkdepim/ksyncprofile.h>
#include <libkdepim/ksyncprefsdialog.h>
class KAex2phonePrefs : public QDialog
{
public:
KAex2phonePrefs( QWidget *parent=0, const char *name=0 ) :
QDialog( parent, name, true )
{
setCaption( i18n("Export to phone options") );
QVBoxLayout* lay = new QVBoxLayout( this );
lay->setSpacing( 3 );
lay->setMargin( 3 );
QLabel *lab;
lay->addWidget(lab = new QLabel( i18n("Please read Help-Sync Howto\nto know what settings to use."), this ) );
lab->setAlignment (AlignHCenter );
QHBox* temphb;
temphb = new QHBox( this );
new QLabel( i18n("I/O device: "), temphb );
mPhoneDevice = new QLineEdit( temphb);
lay->addWidget( temphb );
temphb = new QHBox( this );
new QLabel( i18n("Connection: "), temphb );
mPhoneConnection = new QLineEdit( temphb);
lay->addWidget( temphb );
temphb = new QHBox( this );
new QLabel( i18n("Model(opt.): "), temphb );
mPhoneModel = new QLineEdit( temphb);
lay->addWidget( temphb );
- mWriteToSim= new QCheckBox( i18n("Write Contacts to SIM card\n(if not, write to phone memory)"), this );
- lay->addWidget( mWriteToSim );
+ // mWriteToSim = new QCheckBox( i18n("Write Contacts to SIM card\n(if not, write to phone memory)"), this );
+ // lay->addWidget( mWriteToSim );
lay->addWidget(lab = new QLabel( i18n("NOTE: This will remove all old\ncontact data on phone!"), this ) );
lab->setAlignment (AlignHCenter );
QPushButton * ok = new QPushButton( i18n("Export to mobile phone!"), this );
lay->addWidget( ok );
QPushButton * cancel = new QPushButton( i18n("Cancel"), this );
lay->addWidget( cancel );
connect ( ok,SIGNAL(clicked() ),this , SLOT ( accept() ) );
connect (cancel, SIGNAL(clicked() ), this, SLOT ( reject()) );
resize( 220, 240 );
}
public:
QLineEdit* mPhoneConnection, *mPhoneDevice, *mPhoneModel;
QCheckBox* mWriteToSim;
};
bool pasteWithNewUid = true;
#ifdef KAB_EMBEDDED
KABCore::KABCore( KAddressBookMain *client, bool readWrite, QWidget *parent, const char *name )
: QWidget( parent, name ), KSyncInterface(), mGUIClient( client ), mViewManager( 0 ),
mExtensionManager( 0 ),mConfigureDialog( 0 ),/*US mLdapSearchDialog( 0 ),*/
mReadWrite( readWrite ), mModified( false ), mMainWindow(client)
#else //KAB_EMBEDDED
KABCore::KABCore( KXMLGUIClient *client, bool readWrite, QWidget *parent, const char *name )
: QWidget( parent, name ), KSyncInterface(), mGUIClient( client ), mViewManager( 0 ),
mExtensionManager( 0 ), mConfigureDialog( 0 ), mLdapSearchDialog( 0 ),
mReadWrite( readWrite ), mModified( false )
#endif //KAB_EMBEDDED
{
// syncManager = new KSyncManager((QWidget*)this, (KSyncInterface*)this, KSyncManager::KAPI, KABPrefs::instance(), syncMenu);
// syncManager->setBlockSave(false);
mExtensionBarSplitter = 0;
mIsPart = !parent->inherits( "KAddressBookMain" );
mAddressBook = KABC::StdAddressBook::self();
KABC::StdAddressBook::setAutomaticSave( false );
#ifndef KAB_EMBEDDED
mAddressBook->setErrorHandler( new KABC::GUIErrorHandler );
#endif //KAB_EMBEDDED
connect( mAddressBook, SIGNAL( addressBookChanged( AddressBook * ) ),
SLOT( addressBookChanged() ) );
#if 0
// LP moved to addressbook init method
mAddressBook->addCustomField( i18n( "Department" ), KABC::Field::Organization,
"X-Department", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Profession" ), KABC::Field::Organization,
"X-Profession", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Assistant's Name" ), KABC::Field::Organization,
"X-AssistantsName", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Manager's Name" ), KABC::Field::Organization,
"X-ManagersName", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Spouse's Name" ), KABC::Field::Personal,
"X-SpousesName", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Office" ), KABC::Field::Personal,
"X-Office", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "IM Address" ), KABC::Field::Personal,
"X-IMAddress", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Anniversary" ), KABC::Field::Personal,
"X-Anniversary", "KADDRESSBOOK" );
//US added this field to become compatible with Opie/qtopia addressbook
// values can be "female" or "male" or "". An empty field represents undefined.
mAddressBook->addCustomField( i18n( "Gender" ), KABC::Field::Personal,
"X-Gender", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Children" ), KABC::Field::Personal,
"X-Children", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "FreeBusyUrl" ), KABC::Field::Personal,
"X-FreeBusyUrl", "KADDRESSBOOK" );
#endif
initGUI();
mIncSearchWidget->setFocus();
connect( mViewManager, SIGNAL( selected( const QString& ) ),
SLOT( setContactSelected( const QString& ) ) );
connect( mViewManager, SIGNAL( executed( const QString& ) ),
SLOT( executeContact( const QString& ) ) );
connect( mViewManager, SIGNAL( deleteRequest( ) ),
SLOT( deleteContacts( ) ) );
connect( mViewManager, SIGNAL( modified() ),
SLOT( setModified() ) );
connect( mExtensionManager, SIGNAL( modified( const KABC::Addressee::List& ) ), this, SLOT( extensionModified( const KABC::Addressee::List& ) ) );
connect( mExtensionManager, SIGNAL( changedActiveExtension( int ) ), this, SLOT( extensionChanged( int ) ) );
connect( mXXPortManager, SIGNAL( modified() ),
SLOT( setModified() ) );
connect( mJumpButtonBar, SIGNAL( jumpToLetter( const QString& ) ),
SLOT( incrementalSearch( const QString& ) ) );
connect( mIncSearchWidget, SIGNAL( fieldChanged() ),
mJumpButtonBar, SLOT( recreateButtons() ) );
connect( mDetails, SIGNAL( sendEmail( const QString& ) ),
SLOT( sendMail( const QString& ) ) );
connect( ExternalAppHandler::instance(), SIGNAL (requestForNameEmailUidList(const QString&, const QString&)),this, SLOT(requestForNameEmailUidList(const QString&, const QString&)));
connect( ExternalAppHandler::instance(), SIGNAL (requestForDetails(const QString&, const QString&, const QString&, const QString&, const QString&)),this, SLOT(requestForDetails(const QString&, const QString&, const QString&, const QString&, const QString&)));
connect( ExternalAppHandler::instance(), SIGNAL (requestForBirthdayList(const QString&, const QString&)),this, SLOT(requestForBirthdayList(const QString&, const QString&)));
#ifndef KAB_EMBEDDED
connect( mViewManager, SIGNAL( urlDropped( const KURL& ) ),
mXXPortManager, SLOT( importVCard( const KURL& ) ) );
connect( mDetails, SIGNAL( browse( const QString& ) ),
SLOT( browse( const QString& ) ) );
mAddressBookService = new KAddressBookService( this );
#endif //KAB_EMBEDDED
mEditorDialog = 0;
createAddresseeEditorDialog( this );
setModified( false );
}
KABCore::~KABCore()
{
// save();
//saveSettings();
//KABPrefs::instance()->writeConfig();
delete AddresseeConfig::instance();
mAddressBook = 0;
KABC::StdAddressBook::close();
delete syncManager;
}
void KABCore::recieve( QString fn )
{
//qDebug("KABCore::recieve ");
mAddressBook->importFromFile( fn, true );
mViewManager->refreshView();
topLevelWidget()->raise();
}
void KABCore::restoreSettings()
{
mMultipleViewsAtOnce = KABPrefs::instance()->mMultipleViewsAtOnce;
bool state;
if (mMultipleViewsAtOnce)
state = KABPrefs::instance()->mDetailsPageVisible;
else
state = false;
mActionDetails->setChecked( state );
setDetailsVisible( state );
state = KABPrefs::instance()->mJumpButtonBarVisible;
mActionJumpBar->setChecked( state );
setJumpButtonBarVisible( state );
/*US
QValueList<int> splitterSize = KABPrefs::instance()->mDetailsSplitter;
if ( splitterSize.count() == 0 ) {
splitterSize.append( width() / 2 );
splitterSize.append( width() / 2 );
}
mMiniSplitter->setSizes( splitterSize );
if ( mExtensionBarSplitter ) {
splitterSize = KABPrefs::instance()->mExtensionsSplitter;
if ( splitterSize.count() == 0 ) {
splitterSize.append( width() / 2 );
splitterSize.append( width() / 2 );
}
mExtensionBarSplitter->setSizes( splitterSize );
}
*/
mViewManager->restoreSettings();
mIncSearchWidget->setCurrentItem( KABPrefs::instance()->mCurrentIncSearchField );
mExtensionManager->restoreSettings();
#ifdef DESKTOP_VERSION
int wid = width();
if ( wid < 10 )
wid = 400;
#else
int wid = QApplication::desktop()->width();
if ( wid < 640 )
wid = QApplication::desktop()->height();
#endif
QValueList<int> splitterSize;// = KABPrefs::instance()->mDetailsSplitter;
if ( true /*splitterSize.count() == 0*/ ) {
splitterSize.append( wid / 2 );
splitterSize.append( wid / 2 );
}
mMiniSplitter->setSizes( splitterSize );
if ( mExtensionBarSplitter ) {
//splitterSize = KABPrefs::instance()->mExtensionsSplitter;
if ( true /*splitterSize.count() == 0*/ ) {
splitterSize.append( wid / 2 );
splitterSize.append( wid / 2 );
}
mExtensionBarSplitter->setSizes( splitterSize );
}
}
void KABCore::saveSettings()
{
KABPrefs::instance()->mJumpButtonBarVisible = mActionJumpBar->isChecked();
if ( mExtensionBarSplitter )
KABPrefs::instance()->mExtensionsSplitter = mExtensionBarSplitter->sizes();
KABPrefs::instance()->mDetailsPageVisible = mActionDetails->isChecked();
KABPrefs::instance()->mDetailsSplitter = mMiniSplitter->sizes();
#ifndef KAB_EMBEDDED
KABPrefs::instance()->mExtensionsSplitter = mExtensionBarSplitter->sizes();
KABPrefs::instance()->mDetailsSplitter = mDetailsSplitter->sizes();
#endif //KAB_EMBEDDED
mExtensionManager->saveSettings();
mViewManager->saveSettings();
KABPrefs::instance()->mCurrentIncSearchField = mIncSearchWidget->currentItem();
}
KABC::AddressBook *KABCore::addressBook() const
{
return mAddressBook;
}
KConfig *KABCore::config()
{
#ifndef KAB_EMBEDDED
return KABPrefs::instance()->config();
#else //KAB_EMBEDDED
return KABPrefs::instance()->getConfig();
#endif //KAB_EMBEDDED
}
KActionCollection *KABCore::actionCollection() const
{
return mGUIClient->actionCollection();
}
KABC::Field *KABCore::currentSearchField() const
{
if (mIncSearchWidget)
return mIncSearchWidget->currentField();
else
return 0;
}
QStringList KABCore::selectedUIDs() const
{
return mViewManager->selectedUids();
}
KABC::Resource *KABCore::requestResource( QWidget *parent )
{
QPtrList<KABC::Resource> kabcResources = addressBook()->resources();
QPtrList<KRES::Resource> kresResources;
QPtrListIterator<KABC::Resource> resIt( kabcResources );
KABC::Resource *resource;
while ( ( resource = resIt.current() ) != 0 ) {
++resIt;
if ( !resource->readOnly() ) {
KRES::Resource *res = static_cast<KRES::Resource*>( resource );
if ( res )
kresResources.append( res );
}
}
KRES::Resource *res = KRES::SelectDialog::getResource( kresResources, parent );
return static_cast<KABC::Resource*>( res );
}
#ifndef KAB_EMBEDDED
KAboutData *KABCore::createAboutData()
#else //KAB_EMBEDDED
void KABCore::createAboutData()
#endif //KAB_EMBEDDED
{
#ifndef KAB_EMBEDDED
KAboutData *about = new KAboutData( "kaddressbook", I18N_NOOP( "KAddressBook" ),
"3.1", I18N_NOOP( "The KDE Address Book" ),
KAboutData::License_GPL_V2,
I18N_NOOP( "(c) 1997-2003, The KDE PIM Team" ) );
about->addAuthor( "Tobias Koenig", I18N_NOOP( "Current maintainer " ), "tokoe@kde.org" );
about->addAuthor( "Don Sanders", I18N_NOOP( "Original author " ) );
about->addAuthor( "Cornelius Schumacher",
I18N_NOOP( "Co-maintainer, libkabc port, CSV import/export " ),
"schumacher@kde.org" );
about->addAuthor( "Mike Pilone", I18N_NOOP( "GUI and framework redesign " ),
"mpilone@slac.com" );
about->addAuthor( "Greg Stern", I18N_NOOP( "DCOP interface" ) );
about->addAuthor( "Mark Westcott", I18N_NOOP( "Contact pinning" ) );
about->addAuthor( "Michel Boyer de la Giroday", I18N_NOOP( "LDAP Lookup\n" ),
"michel@klaralvdalens-datakonsult.se" );
about->addAuthor( "Steffen Hansen", I18N_NOOP( "LDAP Lookup " ),
"hansen@kde.org" );
return about;
#endif //KAB_EMBEDDED
QString version;
#include <../version>
QMessageBox::about( this, "About KAddressbook/Pi",
"KAddressbook/Platform-independent\n"
"(KA/Pi) " +version + " - " +
#ifdef DESKTOP_VERSION
"Desktop Edition\n"
#else
"PDA-Edition\n"
"for: Zaurus 5500 / 7x0 / 8x0\n"
#endif
"(c) 2004 Ulf Schenk\n"
"(c) 2004 Lutz Rogowski\n"
"(c) 1997-2003, The KDE PIM Team\n"
"Tobias Koenig Current maintainer\ntokoe@kde.org\n"
"Don Sanders Original author\n"
"Cornelius Schumacher Co-maintainer\nschumacher@kde.org\n"
"Mike Pilone GUI and framework redesign\nmpilone@slac.com\n"
"Greg Stern DCOP interface\n"
"Mark Westcot Contact pinning\n"
"Michel Boyer de la Giroday LDAP Lookup\n" "michel@klaralvdalens-datakonsult.se\n"
"Steffen Hansen LDAP Lookup\nhansen@kde.org\n"
#ifdef _WIN32_
"(c) 2004 Lutz Rogowski Import from OL\nrogowski@kde.org\n"
#endif
);
}
void KABCore::setContactSelected( const QString &uid )
{
KABC::Addressee addr = mAddressBook->findByUid( uid );
if ( !mDetails->isHidden() )
mDetails->setAddressee( addr );
if ( !addr.isEmpty() ) {
emit contactSelected( addr.formattedName() );
KABC::Picture pic = addr.photo();
if ( pic.isIntern() ) {
//US emit contactSelected( pic.data() );
//US instead use:
QPixmap px;
if (pic.data().isNull() != true)
{
px.convertFromImage(pic.data());
}
emit contactSelected( px );
}
}
mExtensionManager->setSelectionChanged();
// update the actions
bool selected = !uid.isEmpty();
if ( mReadWrite ) {
mActionCut->setEnabled( selected );
mActionPaste->setEnabled( selected );
}
mActionCopy->setEnabled( selected );
mActionDelete->setEnabled( selected );
mActionEditAddressee->setEnabled( selected );
mActionMail->setEnabled( selected );
mActionMailVCard->setEnabled( selected );
//if (mActionBeam)
//mActionBeam->setEnabled( selected );
if (mActionBeamVCard)
mActionBeamVCard->setEnabled( selected );
mActionExport2phone->setEnabled( selected );
mActionWhoAmI->setEnabled( selected );
mActionCategories->setEnabled( selected );
}
void KABCore::sendMail()
{
sendMail( mViewManager->selectedEmails().join( ", " ) );
}
void KABCore::sendMail( const QString& emaillist )
{
// the parameter has the form "name1 <abc@aol.com>,name2 <abc@aol.com>;... "
if (emaillist.contains(",") > 0)
ExternalAppHandler::instance()->mailToMultipleContacts( emaillist, QString::null );
else
ExternalAppHandler::instance()->mailToOneContact( emaillist );
}
void KABCore::mailVCard()
{
QStringList uids = mViewManager->selectedUids();
if ( !uids.isEmpty() )
mailVCard( uids );
}
void KABCore::mailVCard( const QStringList& uids )
{
QStringList urls;
// QString tmpdir = locateLocal("tmp", KGlobal::getAppName());
QString dirName = "/tmp/" + KApplication::randomString( 8 );
QDir().mkdir( dirName, true );
for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) {
KABC::Addressee a = mAddressBook->findByUid( *it );
if ( a.isEmpty() )
continue;
QString name = a.givenName() + "_" + a.familyName() + ".vcf";
QString fileName = dirName + "/" + name;
QFile outFile(fileName);
if ( outFile.open(IO_WriteOnly) ) { // file opened successfully
KABC::VCardConverter converter;
QString vcard;
converter.addresseeToVCard( a, vcard );
QTextStream t( &outFile ); // use a text stream
t.setEncoding( QTextStream::UnicodeUTF8 );
t << vcard;
outFile.close();
urls.append( fileName );
}
}
bool result = ExternalAppHandler::instance()->mailToMultipleContacts( QString::null, urls.join(", ") );
/*US
kapp->invokeMailer( QString::null, QString::null, QString::null,
QString::null, // subject
QString::null, // body
QString::null,
urls ); // attachments
*/
}
/**
Beams the "WhoAmI contact.
*/
void KABCore::beamMySelf()
{
KABC::Addressee a = KABC::StdAddressBook::self()->whoAmI();
if (!a.isEmpty())
{
QStringList uids;
uids << a.uid();
beamVCard(uids);
} else {
KMessageBox::information( this, i18n( "Your personal contact is\nnot set! Please select it\nand set it with menu:\nSettings - Set Who Am I\n" ) );
}
}
void KABCore::export2phone()
{
KAex2phonePrefs ex2phone;
ex2phone.mPhoneConnection->setText( KPimGlobalPrefs::instance()->mEx2PhoneConnection );
ex2phone.mPhoneDevice->setText( KPimGlobalPrefs::instance()->mEx2PhoneDevice );
ex2phone.mPhoneModel->setText( KPimGlobalPrefs::instance()->mEx2PhoneModel );
if ( !ex2phone.exec() ) {
return;
}
KPimGlobalPrefs::instance()->mEx2PhoneConnection = ex2phone.mPhoneConnection->text();
KPimGlobalPrefs::instance()->mEx2PhoneDevice = ex2phone.mPhoneDevice->text();
KPimGlobalPrefs::instance()->mEx2PhoneModel = ex2phone.mPhoneModel->text();
PhoneAccess::writeConfig( KPimGlobalPrefs::instance()->mEx2PhoneDevice,
KPimGlobalPrefs::instance()->mEx2PhoneConnection,
KPimGlobalPrefs::instance()->mEx2PhoneModel );
QStringList uids = mViewManager->selectedUids();
if ( uids.isEmpty() )
return;
#ifdef _WIN32_
- QString fileName = locateLocal("tmp", "tempfile.vcf");
+ QString fileName = locateLocal("tmp", "phonefile.vcf");
#else
- QString fileName = "/tmp/kdepimtemp.vcf";
+ QString fileName = "/tmp/phonefile.vcf";
#endif
- KABC::VCardConverter converter;
- QString description;
- QString datastream;
- for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) {
- KABC::Addressee a = mAddressBook->findByUid( *it );
-
- if ( a.isEmpty() )
- continue;
- a.simplifyEmails();
- a.simplifyPhoneNumbers();
- a.simplifyPhoneNumberTypes();
- a.simplifyAddresses();
-
- if (description.isEmpty())
- description = a.formattedName();
- QString vcard;
- QString vcardnew;
- converter.addresseeToVCard( a, vcard );
- int start = 0;
- int next;
- while ( (next = vcard.find("TYPE=", start) )>= 0 ) {
- int semi = vcard.find(";", next);
- int dopp = vcard.find(":", next);
- int sep;
- if ( semi < dopp && semi >= 0 )
- sep = semi ;
- else
- sep = dopp;
- vcardnew +=vcard.mid( start, next - start);
- vcardnew +=vcard.mid( next+5,sep -next -5 ).upper();
- start = sep;
- }
- vcardnew += vcard.mid( start,vcard.length() );
- vcard = "";
- start = 0;
- while ( (next = vcardnew.find("ADR", start) )>= 0 ) {
- int sep = vcardnew.find(":", next);
- vcard +=vcardnew.mid( start, next - start+3);
- start = sep;
- }
- vcard += vcardnew.mid( start,vcardnew.length() );
- vcard.replace ( QRegExp(";;;") , "" );
- vcard.replace ( QRegExp(";;") , "" );
- datastream += vcard;
-
- }
- QFile outFile(fileName);
- if ( outFile.open(IO_WriteOnly) ) {
- datastream.replace ( QRegExp("VERSION:3.0") , "VERSION:2.1" );
- QTextStream t( &outFile ); // use a text stream
- t.setEncoding( QTextStream::UnicodeUTF8 );
- t <<datastream;
- outFile.close();
- if ( PhoneAccess::writeToPhone( fileName ) )
- qDebug("Export okay ");
- else
- qDebug("Error export contacts ");
-
- } else {
- qDebug("Error open temp file ");
+ if ( ! mAddressBook->export2PhoneFormat( uids ,fileName ) )
return;
- }
-
+
+ if ( PhoneAccess::writeToPhone( fileName ) )
+ qDebug("Export okay ");
+ else
+ qDebug("Error export contacts ");
+
#if 0
setCaption( i18n("Writing to phone..."));
if ( PhoneFormat::writeToPhone( cal ) )
setCaption( i18n("Export to phone successful!"));
else
setCaption( i18n("Error exporting to phone!"));
#endif
}
void KABCore::beamVCard()
{
QStringList uids = mViewManager->selectedUids();
if ( !uids.isEmpty() )
beamVCard( uids );
}
void KABCore::beamVCard(const QStringList& uids)
{
/*US
QString beamFilename;
Opie::OPimContact c;
if ( actionPersonal->isOn() ) {
beamFilename = addressbookPersonalVCardName();
if ( !QFile::exists( beamFilename ) )
return; // can't beam a non-existent file
Opie::OPimContactAccessBackend* vcard_backend = new Opie::OPimContactAccessBackend_VCard( QString::null,
beamFilename );
Opie::OPimContactAccess* access = new Opie::OPimContactAccess ( "addressbook", QString::null , vcard_backend, true );
Opie::OPimContactAccess::List allList = access->allRecords();
Opie::OPimContactAccess::List::Iterator it = allList.begin(); // Just take first
c = *it;
delete access;
} else {
unlink( beamfile ); // delete if exists
mkdir("/tmp/obex/", 0755);
c = m_abView -> currentEntry();
Opie::OPimContactAccessBackend* vcard_backend = new Opie::OPimContactAccessBackend_VCard( QString::null,
beamfile );
Opie::OPimContactAccess* access = new Opie::OPimContactAccess ( "addressbook", QString::null , vcard_backend, true );
access->add( c );
access->save();
delete access;
beamFilename = beamfile;
}
owarn << "Beaming: " << beamFilename << oendl;
*/
#if 0
QString tmpdir = locateLocal("tmp", KGlobal::getAppName());
QString dirName = tmpdir + "/" + KApplication::randomString( 8 );
QString name = "contact.vcf";
QString fileName = dirName + "/" + name;
#endif
// LR: we should use the /tmp dir, because: /tmp = RAM, (HOME)/kdepim = flash memory
//
QString fileName = "/tmp/kapibeamfile.vcf";
//QDir().mkdir( dirName, true );
KABC::VCardConverter converter;
QString description;
QString datastream;
for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) {
KABC::Addressee a = mAddressBook->findByUid( *it );
if ( a.isEmpty() )
continue;
if (description.isEmpty())
description = a.formattedName();
QString vcard;
converter.addresseeToVCard( a, vcard );
int start = 0;
int next;
while ( (next = vcard.find("TYPE=", start) )>= 0 ) {
int semi = vcard.find(";", next);
int dopp = vcard.find(":", next);
int sep;
if ( semi < dopp && semi >= 0 )
sep = semi ;
else
sep = dopp;
datastream +=vcard.mid( start, next - start);
datastream +=vcard.mid( next+5,sep -next -5 ).upper();
start = sep;
}
datastream += vcard.mid( start,vcard.length() );
}
#ifndef DESKTOP_VERSION
QFile outFile(fileName);
if ( outFile.open(IO_WriteOnly) ) {
datastream.replace ( QRegExp("VERSION:3.0") , "VERSION:2.1" );
QTextStream t( &outFile ); // use a text stream
t.setEncoding( QTextStream::UnicodeUTF8 );
t <<datastream;
outFile.close();
Ir *ir = new Ir( this );
connect( ir, SIGNAL( done(Ir*) ), this, SLOT( beamDone(Ir*) ) );
ir->send( fileName, description, "text/x-vCard" );
} else {
qDebug("Error open temp beam file ");
return;
}
#endif
}
void KABCore::beamDone( Ir *ir )
{
#ifndef DESKTOP_VERSION
delete ir;
#endif
}
void KABCore::browse( const QString& url )
{
#ifndef KAB_EMBEDDED
kapp->invokeBrowser( url );
#else //KAB_EMBEDDED
qDebug("KABCore::browse must be fixed");
#endif //KAB_EMBEDDED
}
void KABCore::selectAllContacts()
{
mViewManager->setSelected( QString::null, true );
}
void KABCore::deleteContacts()
{
QStringList uidList = mViewManager->selectedUids();
deleteContacts( uidList );
}
void KABCore::deleteContacts( const QStringList &uids )
{
if ( uids.count() > 0 ) {
PwDeleteCommand *command = new PwDeleteCommand( mAddressBook, uids );
UndoStack::instance()->push( command );
RedoStack::instance()->clear();
// now if we deleted anything, refresh
setContactSelected( QString::null );
setModified( true );
}
}
void KABCore::copyContacts()
{
KABC::Addressee::List addrList = mViewManager->selectedAddressees();
QString clipText = AddresseeUtil::addresseesToClipboard( addrList );
kdDebug(5720) << "KABCore::copyContacts: " << clipText << endl;
QClipboard *cb = QApplication::clipboard();
cb->setText( clipText );
}
void KABCore::cutContacts()
{
QStringList uidList = mViewManager->selectedUids();
//US if ( uidList.size() > 0 ) {
if ( uidList.count() > 0 ) {
PwCutCommand *command = new PwCutCommand( mAddressBook, uidList );
UndoStack::instance()->push( command );
RedoStack::instance()->clear();
setModified( true );
}
}
void KABCore::pasteContacts()
{
QClipboard *cb = QApplication::clipboard();
KABC::Addressee::List list = AddresseeUtil::clipboardToAddressees( cb->text() );
pasteContacts( list );
}
void KABCore::pasteContacts( KABC::Addressee::List &list )
{
KABC::Resource *resource = requestResource( this );
KABC::Addressee::List::Iterator it;
for ( it = list.begin(); it != list.end(); ++it )
(*it).setResource( resource );
PwPasteCommand *command = new PwPasteCommand( this, list );
UndoStack::instance()->push( command );
RedoStack::instance()->clear();
setModified( true );
}
void KABCore::setWhoAmI()
{
KABC::Addressee::List addrList = mViewManager->selectedAddressees();
if ( addrList.count() > 1 ) {
KMessageBox::sorry( this, i18n( "Please select only one contact." ) );
return;
}
QString text( i18n( "<qt>Do you really want to use <b>%1</b> as your new personal contact?</qt>" ) );
if ( KMessageBox::questionYesNo( this, text.arg( addrList[ 0 ].assembledName() ) ) == KMessageBox::Yes )
static_cast<KABC::StdAddressBook*>( KABC::StdAddressBook::self() )->setWhoAmI( addrList[ 0 ] );
}
void KABCore::setCategories()
{
KPIM::CategorySelectDialog dlg( KABPrefs::instance(), this, "", true );
if ( !dlg.exec() )
return;
bool merge = false;
QString msg = i18n( "Merge with existing categories?" );
if ( KMessageBox::questionYesNo( this, msg ) == KMessageBox::Yes )
merge = true;
QStringList categories = dlg.selectedCategories();
QStringList uids = mViewManager->selectedUids();
QStringList::Iterator it;
for ( it = uids.begin(); it != uids.end(); ++it ) {
KABC::Addressee addr = mAddressBook->findByUid( *it );
if ( !addr.isEmpty() ) {
if ( !merge )
addr.setCategories( categories );
else {
QStringList addrCategories = addr.categories();
QStringList::Iterator catIt;
for ( catIt = categories.begin(); catIt != categories.end(); ++catIt ) {
if ( !addrCategories.contains( *catIt ) )
addrCategories.append( *catIt );
}
addr.setCategories( addrCategories );
}
mAddressBook->insertAddressee( addr );
}
}
if ( uids.count() > 0 )
setModified( true );
}
void KABCore::setSearchFields( const KABC::Field::List &fields )
{
mIncSearchWidget->setFields( fields );
}
void KABCore::incrementalSearch( const QString& text )
{
mViewManager->doSearch( text, mIncSearchWidget->currentField() );
}
void KABCore::setModified()
{
setModified( true );
}
void KABCore::setModifiedWOrefresh()
{
// qDebug("KABCore::setModifiedWOrefresh() ");
mModified = true;
mActionSave->setEnabled( mModified );
#ifdef DESKTOP_VERSION
mDetails->refreshView();
#endif
}
void KABCore::setModified( bool modified )
{
mModified = modified;
mActionSave->setEnabled( mModified );
if ( modified )
mJumpButtonBar->recreateButtons();
mViewManager->refreshView();
mDetails->refreshView();
}
bool KABCore::modified() const
{
return mModified;
}
void KABCore::contactModified( const KABC::Addressee &addr )
{
Command *command = 0;
QString uid;
// check if it exists already
KABC::Addressee origAddr = mAddressBook->findByUid( addr.uid() );
if ( origAddr.isEmpty() )
command = new PwNewCommand( mAddressBook, addr );
else {
command = new PwEditCommand( mAddressBook, origAddr, addr );
uid = addr.uid();
}
UndoStack::instance()->push( command );
RedoStack::instance()->clear();
setModified( true );
}
void KABCore::newContact()
{
QPtrList<KABC::Resource> kabcResources = mAddressBook->resources();
QPtrList<KRES::Resource> kresResources;
QPtrListIterator<KABC::Resource> it( kabcResources );
KABC::Resource *resource;
while ( ( resource = it.current() ) != 0 ) {
++it;
if ( !resource->readOnly() ) {
KRES::Resource *res = static_cast<KRES::Resource*>( resource );
if ( res )
kresResources.append( res );
}
}
KRES::Resource *res = KRES::SelectDialog::getResource( kresResources, this );
resource = static_cast<KABC::Resource*>( res );
if ( resource ) {
KABC::Addressee addr;
addr.setResource( resource );
mEditorDialog->setAddressee( addr );
KApplication::execDialog ( mEditorDialog );
} else
return;
// mEditorDict.insert( dialog->addressee().uid(), dialog );
}
void KABCore::addEmail( QString aStr )
{
#ifndef KAB_EMBEDDED
QString fullName, email;
KABC::Addressee::parseEmailAddress( aStr, fullName, email );
// Try to lookup the addressee matching the email address
bool found = false;
QStringList emailList;
KABC::AddressBook::Iterator it;
for ( it = mAddressBook->begin(); !found && (it != mAddressBook->end()); ++it ) {
emailList = (*it).emails();
if ( emailList.contains( email ) > 0 ) {
found = true;
(*it).setNameFromString( fullName );
editContact( (*it).uid() );
}
}
if ( !found ) {
KABC::Addressee addr;
addr.setNameFromString( fullName );
addr.insertEmail( email, true );
mAddressBook->insertAddressee( addr );
mViewManager->refreshView( addr.uid() );
editContact( addr.uid() );
}
#else //KAB_EMBEDDED
qDebug("KABCore::addEmail finsih method");
#endif //KAB_EMBEDDED
}
void KABCore::importVCard( const KURL &url, bool showPreview )
{
mXXPortManager->importVCard( url, showPreview );
}
void KABCore::importFromOL()
{
#ifdef _WIN32_
KAImportOLdialog* idgl = new KAImportOLdialog( i18n("Import Contacts from OL"), mAddressBook, this );
idgl->exec();
KABC::Addressee::List list = idgl->getAddressList();
if ( list.count() > 0 ) {
KABC::Addressee::List listNew;
KABC::Addressee::List listExisting;
KABC::Addressee::List::Iterator it;
KABC::AddressBook::Iterator iter;
for ( it = list.begin(); it != list.end(); ++it ) {
if ( mAddressBook->findByUid((*it).uid() ).isEmpty())
listNew.append( (*it) );
else
listExisting.append( (*it) );
}
if ( listExisting.count() > 0 )
KMessageBox::information( this, i18n("%1 contacts not added to addressbook\nbecause they were already in the addressbook!").arg( listExisting.count() ));
if ( listNew.count() > 0 ) {
pasteWithNewUid = false;
pasteContacts( listNew );
pasteWithNewUid = true;
}
}
delete idgl;
#endif
}
void KABCore::importVCard( const QString &vCard, bool showPreview )
{
mXXPortManager->importVCard( vCard, showPreview );
}
//US added a second method without defaultparameter
void KABCore::editContact2() {
editContact( QString::null );
}
void KABCore::editContact( const QString &uid )
{
if ( mExtensionManager->isQuickEditVisible() )
return;
// First, locate the contact entry
QString localUID = uid;
if ( localUID.isNull() ) {
QStringList uidList = mViewManager->selectedUids();
if ( uidList.count() > 0 )
localUID = *( uidList.at( 0 ) );
}
KABC::Addressee addr = mAddressBook->findByUid( localUID );
if ( !addr.isEmpty() ) {
mEditorDialog->setAddressee( addr );
KApplication::execDialog ( mEditorDialog );
}
}
/**
Shows or edits the detail view for the given uid. If the uid is QString::null,
the method will try to find a selected addressee in the view.
*/
void KABCore::executeContact( const QString &uid /*US = QString::null*/ )
{
if ( mMultipleViewsAtOnce )
{
editContact( uid );
}
else
{
setDetailsVisible( true );
mActionDetails->setChecked(true);
}
}
void KABCore::save()
{
if (syncManager->blockSave())
return;
if ( !mModified )
return;
syncManager->setBlockSave(true);
QString text = i18n( "There was an error while attempting to save\n the "
"address book. Please check that some \nother application is "
"not using it. " );
statusMessage(i18n("Saving addressbook ... "));
#ifndef KAB_EMBEDDED
KABC::StdAddressBook *b = dynamic_cast<KABC::StdAddressBook*>( mAddressBook );
if ( !b || !b->save() ) {
KMessageBox::error( this, text, i18n( "Unable to Save" ) );
}
#else //KAB_EMBEDDED
KABC::StdAddressBook *b = (KABC::StdAddressBook*)( mAddressBook );
if ( !b || !b->save() ) {
QMessageBox::critical( this, i18n( "Unable to Save" ), text, i18n("Ok"));
}
#endif //KAB_EMBEDDED
statusMessage(i18n("Addressbook saved!"));
setModified( false );
syncManager->setBlockSave(false);
}
void KABCore::statusMessage(QString mess , int time )
{
//topLevelWidget()->setCaption( mess );
// pending setting timer to revome message
}
void KABCore::undo()
{
UndoStack::instance()->undo();
// Refresh the view
mViewManager->refreshView();
}
void KABCore::redo()
{
RedoStack::instance()->redo();
// Refresh the view
mViewManager->refreshView();
}
void KABCore::setJumpButtonBarVisible( bool visible )
{
if (mMultipleViewsAtOnce)
{
if ( visible )
mJumpButtonBar->show();
else
mJumpButtonBar->hide();
}
else
{
// show the jumpbar only if "the details are hidden" == "viewmanager are shown"
if (mViewManager->isVisible())
{
if ( visible )
mJumpButtonBar->show();
else
mJumpButtonBar->hide();
}
else
{
mJumpButtonBar->hide();
}
}
}
void KABCore::setDetailsToState()
{
setDetailsVisible( mActionDetails->isChecked() );
}
void KABCore::setDetailsVisible( bool visible )
{
if (visible && mDetails->isHidden())
{
KABC::Addressee::List addrList = mViewManager->selectedAddressees();
if ( addrList.count() > 0 )
mDetails->setAddressee( addrList[ 0 ] );
}
// mMultipleViewsAtOnce=false: mDetails is always visible. But we switch between
// the listview and the detailview. We do that by changing the splitbar size.
if (mMultipleViewsAtOnce)
{
if ( visible )
mDetails->show();
else
mDetails->hide();
}
else
{
if ( visible ) {
mViewManager->hide();
mDetails->show();
}
else {
mViewManager->show();
mDetails->hide();
}
setJumpButtonBarVisible( !visible );
}
}
void KABCore::extensionChanged( int id )
{
//change the details view only for non desktop systems
#ifndef DESKTOP_VERSION
if (id == 0)
{
//the user disabled the extension.
if (mMultipleViewsAtOnce)
{ // enable detailsview again
setDetailsVisible( true );
mActionDetails->setChecked( true );
}
else
{ //go back to the listview
setDetailsVisible( false );
mActionDetails->setChecked( false );
mActionDetails->setEnabled(true);
}
}
else
{
//the user enabled the extension.
setDetailsVisible( false );
mActionDetails->setChecked( false );
if (!mMultipleViewsAtOnce)
{
mActionDetails->setEnabled(false);
}
mExtensionManager->setSelectionChanged();
}
#endif// DESKTOP_VERSION
}
void KABCore::extensionModified( const KABC::Addressee::List &list )
{
if ( list.count() != 0 ) {
KABC::Addressee::List::ConstIterator it;
for ( it = list.begin(); it != list.end(); ++it )
mAddressBook->insertAddressee( *it );
if ( list.count() > 1 )
setModified();
else
setModifiedWOrefresh();
}
if ( list.count() == 0 )
mViewManager->refreshView();
else
mViewManager->refreshView( list[ 0 ].uid() );
}
QString KABCore::getNameByPhone( const QString &phone )
{
#ifndef KAB_EMBEDDED
QRegExp r( "[/*/-/ ]" );
QString localPhone( phone );
bool found = false;
QString ownerName = "";
KABC::AddressBook::Iterator iter;
KABC::PhoneNumber::List::Iterator phoneIter;
KABC::PhoneNumber::List phoneList;
for ( iter = mAddressBook->begin(); !found && ( iter != mAddressBook->end() ); ++iter ) {
phoneList = (*iter).phoneNumbers();
for ( phoneIter = phoneList.begin(); !found && ( phoneIter != phoneList.end() );
++phoneIter) {
// Get rid of separator chars so just the numbers are compared.
if ( (*phoneIter).number().replace( r, "" ) == localPhone.replace( r, "" ) ) {
ownerName = (*iter).formattedName();
found = true;
}
}
}
return ownerName;
#else //KAB_EMBEDDED
qDebug("KABCore::getNameByPhone finsih method");
return "";
#endif //KAB_EMBEDDED
}
void KABCore::openConfigDialog()
{
KCMultiDialog* ConfigureDialog = new KCMultiDialog( "PIM", this ,"kabconfigdialog", true );
KCMKabConfig* kabcfg = new KCMKabConfig( ConfigureDialog->getNewVBoxPage(i18n( "Addressbook")) , "KCMKabConfig" );
ConfigureDialog->addModule(kabcfg );
KCMKdePimConfig* kdelibcfg = new KCMKdePimConfig( ConfigureDialog->getNewVBoxPage(i18n( "Global")) , "KCMKdeLibConfig" );
ConfigureDialog->addModule(kdelibcfg );
connect( ConfigureDialog, SIGNAL( applyClicked() ),
this, SLOT( configurationChanged() ) );
connect( ConfigureDialog, SIGNAL( okClicked() ),
this, SLOT( configurationChanged() ) );
saveSettings();
#ifndef DESKTOP_VERSION
ConfigureDialog->showMaximized();
#endif
if ( ConfigureDialog->exec() )
KMessageBox::information( this, i18n("Some changes are only\neffective after a restart!\n") );
delete ConfigureDialog;
}
void KABCore::openLDAPDialog()
{
#ifndef KAB_EMBEDDED
if ( !mLdapSearchDialog ) {
mLdapSearchDialog = new LDAPSearchDialog( mAddressBook, this );
connect( mLdapSearchDialog, SIGNAL( addresseesAdded() ), mViewManager,
SLOT( refreshView() ) );
connect( mLdapSearchDialog, SIGNAL( addresseesAdded() ), this,
SLOT( setModified() ) );
} else
mLdapSearchDialog->restoreSettings();
if ( mLdapSearchDialog->isOK() )
mLdapSearchDialog->exec();
#else //KAB_EMBEDDED
qDebug("KABCore::openLDAPDialog() finsih method");
#endif //KAB_EMBEDDED
}
void KABCore::print()
{
#ifndef KAB_EMBEDDED
KPrinter printer;
if ( !printer.setup( this ) )
return;
KABPrinting::PrintingWizard wizard( &printer, mAddressBook,
mViewManager->selectedUids(), this );
wizard.exec();
#else //KAB_EMBEDDED
qDebug("KABCore::print() finsih method");
#endif //KAB_EMBEDDED
}
void KABCore::addGUIClient( KXMLGUIClient *client )
{
if ( mGUIClient )
mGUIClient->insertChildClient( client );
else
KMessageBox::error( this, "no KXMLGUICLient");
}
void KABCore::configurationChanged()
{
mExtensionManager->reconfigure();
}
void KABCore::addressBookChanged()
{
/*US
QDictIterator<AddresseeEditorDialog> it( mEditorDict );
while ( it.current() ) {
if ( it.current()->dirty() ) {
QString text = i18n( "Data has been changed externally. Unsaved "
"changes will be lost." );
KMessageBox::information( this, text );
}
it.current()->setAddressee( mAddressBook->findByUid( it.currentKey() ) );
++it;
}
*/
if (mEditorDialog)
{
if (mEditorDialog->dirty())
{
QString text = i18n( "Data has been changed externally. Unsaved "
"changes will be lost." );
KMessageBox::information( this, text );
}
QString currentuid = mEditorDialog->addressee().uid();
mEditorDialog->setAddressee( mAddressBook->findByUid( currentuid ) );
}
mViewManager->refreshView();
// mDetails->refreshView();
}
AddresseeEditorDialog *KABCore::createAddresseeEditorDialog( QWidget *parent,
const char *name )
{
if ( mEditorDialog == 0 ) {
mEditorDialog = new AddresseeEditorDialog( this, parent,
name ? name : "editorDialog" );
connect( mEditorDialog, SIGNAL( contactModified( const KABC::Addressee& ) ),
SLOT( contactModified( const KABC::Addressee& ) ) );
//connect( mEditorDialog, SIGNAL( editorDestroyed( const QString& ) ),
// SLOT( slotEditorDestroyed( const QString& ) ) ;
}
return mEditorDialog;
}
void KABCore::slotEditorDestroyed( const QString &uid )
{
//mEditorDict.remove( uid );
}
void KABCore::initGUI()
{
#ifndef KAB_EMBEDDED
QHBoxLayout *topLayout = new QHBoxLayout( this );
topLayout->setSpacing( KDialogBase::spacingHint() );
mExtensionBarSplitter = new QSplitter( this );
mExtensionBarSplitter->setOrientation( Qt::Vertical );
mDetailsSplitter = new QSplitter( mExtensionBarSplitter );
QVBox *viewSpace = new QVBox( mDetailsSplitter );
mIncSearchWidget = new IncSearchWidget( viewSpace );
connect( mIncSearchWidget, SIGNAL( doSearch( const QString& ) ),
SLOT( incrementalSearch( const QString& ) ) );
mViewManager = new ViewManager( this, viewSpace );
viewSpace->setStretchFactor( mViewManager, 1 );
mDetails = new ViewContainer( mDetailsSplitter );
mJumpButtonBar = new JumpButtonBar( this, this );
mExtensionManager = new ExtensionManager( this, mExtensionBarSplitter );
topLayout->addWidget( mExtensionBarSplitter );
topLayout->setStretchFactor( mExtensionBarSplitter, 100 );
topLayout->addWidget( mJumpButtonBar );
topLayout->setStretchFactor( mJumpButtonBar, 1 );
mXXPortManager = new XXPortManager( this, this );
#else //KAB_EMBEDDED
//US initialize viewMenu before settingup viewmanager.
// Viewmanager needs this menu to plugin submenues.
viewMenu = new QPopupMenu( this );
settingsMenu = new QPopupMenu( this );
//filterMenu = new QPopupMenu( this );
ImportMenu = new QPopupMenu( this );
ExportMenu = new QPopupMenu( this );
syncMenu = new QPopupMenu( this );
changeMenu= new QPopupMenu( this );
//US since we have no splitter for the embedded system, setup
// a layout with two frames. One left and one right.
QBoxLayout *topLayout;
// = new QHBoxLayout( this );
// QBoxLayout *topLayout = (QBoxLayout*)layout();
// QWidget *mainBox = new QWidget( this );
// QBoxLayout * mainBoxLayout = new QHBoxLayout(mainBox);
#ifdef DESKTOP_VERSION
topLayout = new QHBoxLayout( this );
mMiniSplitter = new KDGanttMinimizeSplitter( Qt::Horizontal, this);
mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Right );
topLayout->addWidget(mMiniSplitter );
mExtensionBarSplitter = new KDGanttMinimizeSplitter( Qt::Vertical,mMiniSplitter );
mExtensionBarSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Down );
mViewManager = new ViewManager( this, mExtensionBarSplitter );
mDetails = new ViewContainer( mMiniSplitter );
mExtensionManager = new ExtensionManager( this, mExtensionBarSplitter );
#else
if ( QApplication::desktop()->width() > 480 ) {
topLayout = new QHBoxLayout( this );
mMiniSplitter = new KDGanttMinimizeSplitter( Qt::Horizontal, this);
mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Right );
} else {
topLayout = new QHBoxLayout( this );
mMiniSplitter = new KDGanttMinimizeSplitter( Qt::Vertical, this);
mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Down );
}
topLayout->addWidget(mMiniSplitter );
mViewManager = new ViewManager( this, mMiniSplitter );
mDetails = new ViewContainer( mMiniSplitter );
mExtensionManager = new ExtensionManager( this, mMiniSplitter );
#endif
//eh->hide();
// topLayout->addWidget(mExtensionManager );
/*US
#ifndef KAB_NOSPLITTER
QHBoxLayout *topLayout = new QHBoxLayout( this );
//US topLayout->setSpacing( KDialogBase::spacingHint() );
topLayout->setSpacing( 10 );
mDetailsSplitter = new QSplitter( this );
QVBox *viewSpace = new QVBox( mDetailsSplitter );
mViewManager = new ViewManager( this, viewSpace );
viewSpace->setStretchFactor( mViewManager, 1 );
mDetails = new ViewContainer( mDetailsSplitter );
topLayout->addWidget( mDetailsSplitter );
topLayout->setStretchFactor( mDetailsSplitter, 100 );
#else //KAB_NOSPLITTER
QHBoxLayout *topLayout = new QHBoxLayout( this );
//US topLayout->setSpacing( KDialogBase::spacingHint() );
topLayout->setSpacing( 10 );
// mDetailsSplitter = new QSplitter( this );
QVBox *viewSpace = new QVBox( this );
mViewManager = new ViewManager( this, viewSpace );
viewSpace->setStretchFactor( mViewManager, 1 );
mDetails = new ViewContainer( this );
topLayout->addWidget( viewSpace );
// topLayout->setStretchFactor( mDetailsSplitter, 100 );
topLayout->addWidget( mDetails );
#endif //KAB_NOSPLITTER
*/
syncManager = new KSyncManager((QWidget*)this, (KSyncInterface*)this, KSyncManager::KAPI, KABPrefs::instance(), syncMenu);
syncManager->setBlockSave(false);
connect(syncManager , SIGNAL( request_file() ), this, SLOT( syncFileRequest() ) );
connect(syncManager , SIGNAL( getFile( bool )), this, SLOT(getFile( bool ) ) );
syncManager->setDefaultFileName( sentSyncFile());
//connect(syncManager , SIGNAL( ), this, SLOT( ) );
#endif //KAB_EMBEDDED
initActions();
#ifdef KAB_EMBEDDED
addActionsManually();
//US make sure the export and import menues are initialized before creating the xxPortManager.
mXXPortManager = new XXPortManager( this, this );
// LR mIncSearchWidget = new IncSearchWidget( mMainWindow->getIconToolBar() );
//mMainWindow->toolBar()->insertWidget(-1, 4, mIncSearchWidget);
// mActionQuit->plug ( mMainWindow->toolBar());
//mIncSearchWidget = new IncSearchWidget( mMainWindow->toolBar() );
//mMainWindow->toolBar()->insertWidget(-1, 0, mIncSearchWidget);
// mIncSearchWidget->hide();
connect( mIncSearchWidget, SIGNAL( doSearch( const QString& ) ),
SLOT( incrementalSearch( const QString& ) ) );
mJumpButtonBar = new JumpButtonBar( this, this );
topLayout->addWidget( mJumpButtonBar );
//US topLayout->setStretchFactor( mJumpButtonBar, 10 );
// mMainWindow->getIconToolBar()->raise();
#endif //KAB_EMBEDDED
}
void KABCore::initActions()
{
//US qDebug("KABCore::initActions(): mIsPart %i", mIsPart);
#ifndef KAB_EMBEDDED
connect( QApplication::clipboard(), SIGNAL( dataChanged() ),
SLOT( clipboardDataChanged() ) );
#endif //KAB_EMBEDDED
// file menu
if ( mIsPart ) {
mActionMail = new KAction( i18n( "&Mail" ), "mail_generic", 0, this,
SLOT( sendMail() ), actionCollection(),
"kaddressbook_mail" );
mActionPrint = new KAction( i18n( "&Print" ), "fileprint", CTRL + Key_P, this,
SLOT( print() ), actionCollection(), "kaddressbook_print" );
} else {
mActionMail = KStdAction::mail( this, SLOT( sendMail() ), actionCollection() );
mActionPrint = KStdAction::print( this, SLOT( print() ), actionCollection() );
}
mActionSave = new KAction( i18n( "&Save" ), "filesave", CTRL+Key_S, this,
SLOT( save() ), actionCollection(), "file_sync" );
mActionNewContact = new KAction( i18n( "&New Contact..." ), "filenew", CTRL+Key_N, this,
SLOT( newContact() ), actionCollection(), "file_new_contact" );
mActionMailVCard = new KAction(i18n("Mail &vCard..."), "mail_post_to", 0,
this, SLOT( mailVCard() ),
actionCollection(), "file_mail_vcard");
mActionExport2phone = new KAction( i18n( "Selected to phone" ), "ex2phone", 0, this,
SLOT( export2phone() ), actionCollection(),
"kaddressbook_ex2phone" );
mActionBeamVCard = 0;
mActionBeam = 0;
#ifndef DESKTOP_VERSION
if ( Ir::supported() ) {
mActionBeamVCard = new KAction( i18n( "Beam selected v&Card(s)" ), "beam", 0, this,
SLOT( beamVCard() ), actionCollection(),
"kaddressbook_beam_vcard" );
mActionBeam = new KAction( i18n( "&Beam personal vCard" ), "beam", 0, this,
SLOT( beamMySelf() ), actionCollection(),
"kaddressbook_beam_myself" );
}
#endif
mActionEditAddressee = new KAction( i18n( "&Edit Contact..." ), "edit", 0,
this, SLOT( editContact2() ),
actionCollection(), "file_properties" );
#ifdef KAB_EMBEDDED
// mActionQuit = KStdAction::quit( mMainWindow, SLOT( exit() ), actionCollection() );
mActionQuit = new KAction( i18n( "&Exit" ), "exit", 0,
mMainWindow, SLOT( exit() ),
actionCollection(), "quit" );
#endif //KAB_EMBEDDED
// edit menu
if ( mIsPart ) {
mActionCopy = new KAction( i18n( "&Copy" ), "editcopy", CTRL + Key_C, this,
SLOT( copyContacts() ), actionCollection(),
"kaddressbook_copy" );
mActionCut = new KAction( i18n( "Cu&t" ), "editcut", CTRL + Key_X, this,
SLOT( cutContacts() ), actionCollection(),
"kaddressbook_cut" );
mActionPaste = new KAction( i18n( "&Paste" ), "editpaste", CTRL + Key_V, this,
SLOT( pasteContacts() ), actionCollection(),
"kaddressbook_paste" );
mActionSelectAll = new KAction( i18n( "Select &All" ), CTRL + Key_A, this,
SLOT( selectAllContacts() ), actionCollection(),
"kaddressbook_select_all" );
mActionUndo = new KAction( i18n( "&Undo" ), "undo", CTRL + Key_Z, this,
SLOT( undo() ), actionCollection(),
"kaddressbook_undo" );
mActionRedo = new KAction( i18n( "Re&do" ), "redo", CTRL + SHIFT + Key_Z,
this, SLOT( redo() ), actionCollection(),
"kaddressbook_redo" );
} else {
mActionCopy = KStdAction::copy( this, SLOT( copyContacts() ), actionCollection() );
mActionCut = KStdAction::cut( this, SLOT( cutContacts() ), actionCollection() );
mActionPaste = KStdAction::paste( this, SLOT( pasteContacts() ), actionCollection() );
mActionSelectAll = KStdAction::selectAll( this, SLOT( selectAllContacts() ), actionCollection() );
mActionUndo = KStdAction::undo( this, SLOT( undo() ), actionCollection() );
mActionRedo = KStdAction::redo( this, SLOT( redo() ), actionCollection() );
}
mActionDelete = new KAction( i18n( "&Delete Contact" ), "editdelete",
Key_Delete, this, SLOT( deleteContacts() ),
actionCollection(), "edit_delete" );
mActionUndo->setEnabled( false );
mActionRedo->setEnabled( false );
// settings menu
#ifdef KAB_EMBEDDED
//US special menuentry to configure the addressbook resources. On KDE
// you do that through the control center !!!
mActionConfigResources = new KAction( i18n( "Configure &Resources..." ), "configure_resources", 0, this,
SLOT( configureResources() ), actionCollection(),
"kaddressbook_configure_resources" );
#endif //KAB_EMBEDDED
if ( mIsPart ) {
mActionConfigKAddressbook = new KAction( i18n( "&Configure KAddressBook..." ), "configure", 0, this,
SLOT( openConfigDialog() ), actionCollection(),
"kaddressbook_configure" );
mActionConfigShortcuts = new KAction( i18n( "Configure S&hortcuts..." ), "configure_shortcuts", 0,
this, SLOT( configureKeyBindings() ), actionCollection(),
"kaddressbook_configure_shortcuts" );
#ifdef KAB_EMBEDDED
mActionConfigureToolbars = KStdAction::configureToolbars( this, SLOT( mMainWindow->configureToolbars() ), actionCollection() );
mActionConfigureToolbars->setEnabled( false );
#endif //KAB_EMBEDDED
} else {
mActionConfigKAddressbook = KStdAction::preferences( this, SLOT( openConfigDialog() ), actionCollection() );
mActionKeyBindings = KStdAction::keyBindings( this, SLOT( configureKeyBindings() ), actionCollection() );
}
mActionJumpBar = new KToggleAction( i18n( "Show Jump Bar" ), 0, 0,
actionCollection(), "options_show_jump_bar" );
connect( mActionJumpBar, SIGNAL( toggled( bool ) ), SLOT( setJumpButtonBarVisible( bool ) ) );
mActionDetails = new KToggleAction( i18n( "Show Details" ), "listview", 0,
actionCollection(), "options_show_details" );
connect( mActionDetails, SIGNAL( toggled( bool ) ), SLOT( setDetailsVisible( bool ) ) );
// misc
// only enable LDAP lookup if we can handle the protocol
#ifndef KAB_EMBEDDED
if ( KProtocolInfo::isKnownProtocol( KURL( "ldap://localhost" ) ) ) {
new KAction( i18n( "&Lookup Addresses in Directory" ), "find", 0,
this, SLOT( openLDAPDialog() ), actionCollection(),
"ldap_lookup" );
}
#else //KAB_EMBEDDED
//qDebug("KABCore::initActions() LDAP has to be implemented");
#endif //KAB_EMBEDDED
mActionWhoAmI = new KAction( i18n( "Set Who Am I" ), "personal", 0, this,
SLOT( setWhoAmI() ), actionCollection(),
"set_personal" );
mActionCategories = new KAction( i18n( "Set Categories" ), 0, this,
SLOT( setCategories() ), actionCollection(),
"edit_set_categories" );
mActionRemoveVoice = new KAction( i18n( "Remove \"voice\"..." ), 0, this,
SLOT( removeVoice() ), actionCollection(),
"remove_voice" );
mActionImportOL = new KAction( i18n( "Import from Outlook..." ), 0, this,
SLOT( importFromOL() ), actionCollection(),
"import_OL" );
#ifdef KAB_EMBEDDED
mActionLicence = new KAction( i18n( "Licence" ), 0,
this, SLOT( showLicence() ), actionCollection(),
"licence_about_data" );
mActionFaq = new KAction( i18n( "Faq" ), 0,
this, SLOT( faq() ), actionCollection(),
"faq_about_data" );
mActionAboutKAddressbook = new KAction( i18n( "&About KAddressBook" ), "kaddressbook2", 0,
this, SLOT( createAboutData() ), actionCollection(),
"kaddressbook_about_data" );
#endif //KAB_EMBEDDED
clipboardDataChanged();
connect( UndoStack::instance(), SIGNAL( changed() ), SLOT( updateActionMenu() ) );
connect( RedoStack::instance(), SIGNAL( changed() ), SLOT( updateActionMenu() ) );
}
//US we need this function, to plug all actions into the correct menues.
// KDE uses a XML format to plug the actions, but we work her without this overhead.
void KABCore::addActionsManually()
{
//US qDebug("KABCore::initActions(): mIsPart %i", mIsPart);
#ifdef KAB_EMBEDDED
QPopupMenu *fileMenu = new QPopupMenu( this );
QPopupMenu *editMenu = new QPopupMenu( this );
QPopupMenu *helpMenu = new QPopupMenu( this );
KToolBar* tb = mMainWindow->toolBar();
#ifdef DESKTOP_VERSION
QMenuBar* mb = mMainWindow->menuBar();
//US setup menubar.
//Disable the following block if you do not want to have a menubar.
mb->insertItem( "&File", fileMenu );
mb->insertItem( "&Edit", editMenu );
mb->insertItem( "&View", viewMenu );
mb->insertItem( "&Settings", settingsMenu );
mb->insertItem( i18n("Synchronize"), syncMenu );
mb->insertItem( "&Change selected", changeMenu );
mb->insertItem( "&Help", helpMenu );
mIncSearchWidget = new IncSearchWidget( tb );
// tb->insertWidget(-1, 0, mIncSearchWidget);
#else
//US setup toolbar
QPEMenuBar *menuBarTB = new QPEMenuBar( tb );
QPopupMenu *popupBarTB = new QPopupMenu( this );
menuBarTB->insertItem( "ME", popupBarTB);
tb->insertWidget(-1, 0, menuBarTB);
mIncSearchWidget = new IncSearchWidget( tb );
tb->enableMoving(false);
popupBarTB->insertItem( "&File", fileMenu );
popupBarTB->insertItem( "&Edit", editMenu );
popupBarTB->insertItem( "&View", viewMenu );
popupBarTB->insertItem( "&Settings", settingsMenu );
popupBarTB->insertItem( i18n("Synchronize"), syncMenu );
mViewManager->getFilterAction()->plug ( popupBarTB);
popupBarTB->insertItem( "&Change selected", changeMenu );
popupBarTB->insertItem( "&Help", helpMenu );
if (QApplication::desktop()->width() > 320 ) {
// mViewManager->getFilterAction()->plug ( tb);
}
#endif
// mActionQuit->plug ( mMainWindow->toolBar());
//US Now connect the actions with the menue entries.
mActionPrint->plug( fileMenu );
mActionMail->plug( fileMenu );
fileMenu->insertSeparator();
mActionNewContact->plug( fileMenu );
mActionNewContact->plug( tb );
mActionEditAddressee->plug( fileMenu );
if ((KGlobal::getDesktopSize() > KGlobal::Small ) ||
(!KABPrefs::instance()->mMultipleViewsAtOnce ))
mActionEditAddressee->plug( tb );
fileMenu->insertSeparator();
mActionSave->plug( fileMenu );
fileMenu->insertItem( "&Import", ImportMenu );
fileMenu->insertItem( "&Export", ExportMenu );
fileMenu->insertSeparator();
mActionMailVCard->plug( fileMenu );
#ifndef DESKTOP_VERSION
if ( Ir::supported() ) mActionBeamVCard->plug( fileMenu );
if ( Ir::supported() ) mActionBeam->plug(fileMenu );
#endif
fileMenu->insertSeparator();
mActionQuit->plug( fileMenu );
#ifdef _WIN32_
mActionImportOL->plug( ImportMenu );
#endif
// edit menu
mActionUndo->plug( editMenu );
mActionRedo->plug( editMenu );
editMenu->insertSeparator();
mActionCut->plug( editMenu );
mActionCopy->plug( editMenu );
mActionPaste->plug( editMenu );
mActionDelete->plug( editMenu );
editMenu->insertSeparator();
mActionSelectAll->plug( editMenu );
mActionRemoveVoice->plug( changeMenu );
// settings menu
//US special menuentry to configure the addressbook resources. On KDE
// you do that through the control center !!!
mActionConfigResources->plug( settingsMenu );
settingsMenu->insertSeparator();
mActionConfigKAddressbook->plug( settingsMenu );
if ( mIsPart ) {
mActionConfigShortcuts->plug( settingsMenu );
mActionConfigureToolbars->plug( settingsMenu );
} else {
mActionKeyBindings->plug( settingsMenu );
}
settingsMenu->insertSeparator();
mActionJumpBar->plug( settingsMenu );
mActionDetails->plug( settingsMenu );
if (!KABPrefs::instance()->mMultipleViewsAtOnce || KGlobal::getDesktopSize() == KGlobal::Desktop )
mActionDetails->plug( tb );
settingsMenu->insertSeparator();
mActionWhoAmI->plug( settingsMenu );
mActionCategories->plug( settingsMenu );
mActionLicence->plug( helpMenu );
mActionFaq->plug( helpMenu );
mActionAboutKAddressbook->plug( helpMenu );
if (KGlobal::getDesktopSize() > KGlobal::Small ) {
mActionSave->plug( tb );
mViewManager->getFilterAction()->plug ( tb);
if (KGlobal::getDesktopSize() == KGlobal::Desktop ) {
mActionUndo->plug( tb );
mActionDelete->plug( tb );
mActionRedo->plug( tb );
}
}
//mActionQuit->plug ( tb );
// tb->insertWidget(-1, 0, mIncSearchWidget, 6);
//US link the searchwidget first to this.
// The real linkage to the toolbar happens later.
//US mIncSearchWidget->reparent(tb, 0, QPoint(50,0), TRUE);
//US tb->insertItem( mIncSearchWidget );
/*US
mIncSearchWidget = new IncSearchWidget( tb );
connect( mIncSearchWidget, SIGNAL( doSearch( const QString& ) ),
SLOT( incrementalSearch( const QString& ) ) );
mJumpButtonBar = new JumpButtonBar( this, this );
//US topLayout->addWidget( mJumpButtonBar );
this->layout()->add( mJumpButtonBar );
*/
#endif //KAB_EMBEDDED
mActionExport2phone->plug( ExportMenu );
connect ( syncMenu, SIGNAL( activated ( int ) ), syncManager, SLOT (slotSyncMenu( int ) ) );
syncManager->fillSyncMenu();
}
void KABCore::showLicence()
{
KApplication::showLicence();
}
void KABCore::removeVoice()
{
if ( KMessageBox::questionYesNo( this, i18n("After importing, phone numbers\nmay have two or more types.\n(E.g. work+voice)\nThese numbers are shown as \"other\".\nClick Yes to remove the voice type\nfrom numbers with more than one type.\n\nRemove voice type?") ) == KMessageBox::No )
return;
KABC::Addressee::List list = mViewManager->selectedAddressees();
KABC::Addressee::List::Iterator it;
for ( it = list.begin(); it != list.end(); ++it ) {
if ( (*it).removeVoice() )
contactModified((*it) );
}
}
void KABCore::clipboardDataChanged()
{
if ( mReadWrite )
mActionPaste->setEnabled( !QApplication::clipboard()->text().isEmpty() );
}
void KABCore::updateActionMenu()
{
UndoStack *undo = UndoStack::instance();
RedoStack *redo = RedoStack::instance();
if ( undo->isEmpty() )
mActionUndo->setText( i18n( "Undo" ) );
else
mActionUndo->setText( i18n( "Undo %1" ).arg( undo->top()->name() ) );
mActionUndo->setEnabled( !undo->isEmpty() );
if ( !redo->top() )
mActionRedo->setText( i18n( "Redo" ) );
else
mActionRedo->setText( i18n( "Redo %1" ).arg( redo->top()->name() ) );
mActionRedo->setEnabled( !redo->isEmpty() );
}
void KABCore::configureKeyBindings()
{
#ifndef KAB_EMBEDDED
KKeyDialog::configure( actionCollection(), true );
#else //KAB_EMBEDDED
qDebug("KABCore::configureKeyBindings() not implemented");
#endif //KAB_EMBEDDED
}
#ifdef KAB_EMBEDDED
void KABCore::configureResources()
{
KRES::KCMKResources dlg( this, "" , 0 );
if ( !dlg.exec() )
return;
KMessageBox::information( this, i18n("Please restart to get the \nchanged resources (re)loaded!\n") );
}
#endif //KAB_EMBEDDED
/* this method will be called through the QCop interface from Ko/Pi to select addresses
* for the attendees list of an event.
*/
void KABCore::requestForNameEmailUidList(const QString& sourceChannel, const QString& uid)
{
QStringList nameList;
QStringList emailList;
QStringList uidList;
KABC::Addressee::List list = KABC::AddresseeDialog::getAddressees(this);
uint i=0;
for (i=0; i < list.count(); i++)
{
nameList.append(list[i].realName());
emailList.append(list[i].preferredEmail());
uidList.append(list[i].uid());
}
bool res = ExternalAppHandler::instance()->returnNameEmailUidListFromKAPI(sourceChannel, uid, nameList, emailList, uidList);
}
/* this method will be called through the QCop interface from Ko/Pi to select birthdays
* to put them into the calendar.
*/
void KABCore::requestForBirthdayList(const QString& sourceChannel, const QString& uid)
{
// qDebug("KABCore::requestForBirthdayList");
QStringList birthdayList;
QStringList anniversaryList;
QStringList realNameList;
QStringList preferredEmailList;
QStringList assembledNameList;
QStringList uidList;
KABC::AddressBook::Iterator it;
int count = 0;
for( it = mAddressBook->begin(); it != mAddressBook->end(); ++it ) {
++count;
}
QProgressBar bar(count,0 );
int w = 300;
if ( QApplication::desktop()->width() < 320 )
w = 220;
int h = bar.sizeHint().height() ;
int dw = QApplication::desktop()->width();
int dh = QApplication::desktop()->height();
bar.setGeometry( (dw-w)/2, (dh - h )/2 ,w,h );
bar.show();
bar.setCaption (i18n("collecting birthdays - close to abort!") );
qApp->processEvents();
QDate bday;
QString anni;
QString formattedbday;
for( it = mAddressBook->begin(); it != mAddressBook->end(); ++it )
{
if ( ! bar.isVisible() )
return;
bar.setProgress( count++ );
qApp->processEvents();
bday = (*it).birthday().date();
anni = (*it).custom("KADDRESSBOOK", "X-Anniversary" );
if ( bday.isValid() || !anni.isEmpty())
{
if (bday.isValid())
formattedbday = KGlobal::locale()->formatDate(bday, true, KLocale::ISODate);
else
formattedbday = "NOTVALID";
if (anni.isEmpty())
anni = "INVALID";
birthdayList.append(formattedbday);
anniversaryList.append(anni); //should be ISODate
realNameList.append((*it).realName());
preferredEmailList.append((*it).preferredEmail());
assembledNameList.append((*it).assembledName());
uidList.append((*it).uid());
qDebug("found birthday in KA/Pi: %s,%s,%s,%s: %s, %s", (*it).realName().latin1(), (*it).preferredEmail().latin1(), (*it).assembledName().latin1(), (*it).uid().latin1(), formattedbday.latin1(), anni.latin1() );
}
}
bool res = ExternalAppHandler::instance()->returnBirthdayListFromKAPI(sourceChannel, uid, birthdayList, anniversaryList, realNameList, preferredEmailList, assembledNameList, uidList);
}
/* this method will be called through the QCop interface from other apps to show details of a contact.
*/
void KABCore::requestForDetails(const QString& sourceChannel, const QString& sessionuid, const QString& name, const QString& email, const QString& uid)
{
qDebug("KABCore::requestForDetails %s %s %s %s %s", sourceChannel.latin1(), sessionuid.latin1(), name.latin1(), email.latin1(), uid.latin1());
QString foundUid = QString::null;
if ( ! uid.isEmpty() ) {
Addressee adrr = mAddressBook->findByUid( uid );
if ( !adrr.isEmpty() ) {
foundUid = uid;
}
if ( email == "sendbacklist" ) {
//qDebug("ssssssssssssssssssssssend ");
QStringList nameList;
QStringList emailList;
QStringList uidList;
nameList.append(adrr.realName());
emailList = adrr.emails();
uidList.append( adrr.preferredEmail());
bool res = ExternalAppHandler::instance()->returnNameEmailUidListFromKAPI("QPE/Application/ompi", uid, nameList, emailList, uidList);
return;
}
}
if ( email == "sendbacklist" )
return;
if (foundUid.isEmpty())
{
//find the uid of the person first
Addressee::List namelist;
Addressee::List emaillist;
if (!name.isEmpty())
namelist = mAddressBook->findByName( name );
if (!email.isEmpty())
emaillist = mAddressBook->findByEmail( email );
qDebug("count %d %d ", namelist.count(),emaillist.count() );
//check if we have a match in Namelist and Emaillist
if ((namelist.count() == 0) && (emaillist.count() > 0)) {
foundUid = emaillist[0].uid();
}
else if ((namelist.count() > 0) && (emaillist.count() == 0))
foundUid = namelist[0].uid();
else
{
for (int i = 0; i < namelist.count(); i++)
{
for (int j = 0; j < emaillist.count(); j++)
{
if (namelist[i] == emaillist[j])
{
foundUid = namelist[i].uid();
}
}
}
}
}
else
{
foundUid = uid;
}
if (!foundUid.isEmpty())
{
// raise Ka/Pi if it is in the background
#ifndef DESKTOP_VERSION
#ifndef KORG_NODCOP
//QCopEnvelope e("QPE/Application/kapi", "raise()");
#endif
#endif
mMainWindow->showMaximized();
mMainWindow-> raise();
mViewManager->setSelected( "", false);
mViewManager->refreshView( "" );
mViewManager->setSelected( foundUid, true );
mViewManager->refreshView( foundUid );
if ( !mMultipleViewsAtOnce )
{
setDetailsVisible( true );
mActionDetails->setChecked(true);
}
}
}
void KABCore::faq()
{
KApplication::showFile( "KA/Pi FAQ", "kdepim/kaddressbook/kapiFAQ.txt" );
}
#include <libkcal/syncdefines.h>
KABC::Addressee KABCore::getLastSyncAddressee()
{
Addressee lse;
QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice();
//qDebug("CurrentSyncDevice %s ",mCurrentSyncDevice .latin1() );
lse = mAddressBook->findByUid( "last-syncAddressee-"+mCurrentSyncDevice );
if (lse.isEmpty()) {
qDebug("Creating new last-syncAddressee ");
lse.setUid( "last-syncAddressee-"+mCurrentSyncDevice );
QString sum = "";
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL )
sum = "E: ";
lse.setFamilyName("!"+sum+mCurrentSyncDevice + i18n(" - sync event"));
lse.setRevision( mLastAddressbookSync );
lse.setCategories( i18n("SyncEvent") );
mAddressBook->insertAddressee( lse );
}
return lse;
}
int KABCore::takeAddressee( KABC::Addressee* local, KABC::Addressee* remote, int mode , bool full )
{
//void setZaurusId(int id);
// int zaurusId() const;
// void setZaurusUid(int id);
// int zaurusUid() const;
// void setZaurusStat(int id);
// int zaurusStat() const;
// 0 equal
// 1 take local
// 2 take remote
// 3 cancel
QDateTime lastSync = mLastAddressbookSync;
QDateTime localMod = local->revision();
QDateTime remoteMod = remote->revision();
QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice();
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
bool remCh, locCh;
remCh = ( remote->getCsum(mCurrentSyncDevice) != local->getCsum(mCurrentSyncDevice) );
//qDebug("loc %s rem %s", local->getCsum(mCurrentSyncDevice).latin1(), remote->getCsum(mCurrentSyncDevice).latin1() );
locCh = ( localMod > mLastAddressbookSync );
if ( !remCh && ! locCh ) {
//qDebug("both not changed ");
lastSync = localMod.addDays(1);
if ( mode <= SYNC_PREF_ASK )
return 0;
} else {
if ( locCh ) {
//qDebug("loc changed %s %s", localMod.toString().latin1(), mLastAddressbookSync.toString().latin1());
lastSync = localMod.addDays( -1 );
if ( !remCh )
remoteMod =( lastSync.addDays( -1 ) );
} else {
//qDebug(" not loc changed ");
lastSync = localMod.addDays( 1 );
if ( remCh )
remoteMod =( lastSync.addDays( 1 ) );
}
}
full = true;
if ( mode < SYNC_PREF_ASK )
mode = SYNC_PREF_ASK;
} else {
if ( localMod == remoteMod )
return 0;
}
// qDebug(" %d %d conflict on %s %s ", mode, full, local->summary().latin1(), remote->summary().latin1() );
//qDebug("%s %d %s %d", local->lastModified().toString().latin1() , localMod, remote->lastModified().toString().latin1(), remoteMod);
//qDebug("%d %d %d %d ", local->lastModified().time().second(), local->lastModified().time().msec(), remote->lastModified().time().second(), remote->lastModified().time().msec() );
//full = true; //debug only
if ( full ) {
bool equ = ( (*local) == (*remote) );
if ( equ ) {
//qDebug("equal ");
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
local->setCsum( mCurrentSyncDevice, remote->getCsum(mCurrentSyncDevice) );
}
if ( mode < SYNC_PREF_FORCE_LOCAL )
return 0;
}//else //debug only
//qDebug("not equal %s %s ", local->summary().latin1(), remote->summary().latin1());
}
int result;
bool localIsNew;
//qDebug("%s -- %s mLastCalendarSync %s lastsync %s --- local %s remote %s ",local->summary().latin1(), remote->summary().latin1(),mLastCalendarSync.toString().latin1() ,lastSync.toString().latin1() , local->lastModified().toString().latin1() , remote->lastModified().toString().latin1() );
if ( full && mode < SYNC_PREF_NEWEST )
mode = SYNC_PREF_ASK;
switch( mode ) {
case SYNC_PREF_LOCAL:
if ( lastSync > remoteMod )
return 1;
if ( lastSync > localMod )
return 2;
return 1;
break;
case SYNC_PREF_REMOTE:
if ( lastSync > remoteMod )
return 1;
if ( lastSync > localMod )
return 2;
return 2;
break;
case SYNC_PREF_NEWEST:
if ( localMod > remoteMod )
return 1;
else
return 2;
break;
case SYNC_PREF_ASK:
//qDebug("lsy %s --- lo %s --- re %s ", lastSync.toString().latin1(), localMod.toString().latin1(), remoteMod.toString().latin1() );
if ( lastSync > remoteMod )
return 1;
if ( lastSync > localMod )
return 2;
localIsNew = localMod >= remoteMod;
//qDebug("conflict! ************************************** ");
{
KPIM::AddresseeChooser acd ( *local,*remote, localIsNew , this );
result = acd.executeD(localIsNew);
return result;
}
break;
case SYNC_PREF_FORCE_LOCAL:
return 1;
break;
case SYNC_PREF_FORCE_REMOTE:
return 2;
break;
default:
// SYNC_PREF_TAKE_BOTH not implemented
break;
}
return 0;
}
bool KABCore::synchronizeAddressbooks( KABC::AddressBook* local, KABC::AddressBook* remote,int mode)
{
bool syncOK = true;
int addedAddressee = 0;
int addedAddresseeR = 0;
int deletedAddresseeR = 0;
int deletedAddresseeL = 0;
int changedLocal = 0;
int changedRemote = 0;
QString mCurrentSyncName = syncManager->getCurrentSyncName();
QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice();
//QPtrList<Addressee> el = local->rawAddressees();
Addressee addresseeR;
QString uid;
int take;
Addressee addresseeL;
Addressee addresseeRSync;
Addressee addresseeLSync;
// KABC::Addressee::List addresseeRSyncSharp = remote->getExternLastSyncAddressees();
//KABC::Addressee::List addresseeLSyncSharp = local->getExternLastSyncAddressees();
bool fullDateRange = false;
local->resetTempSyncStat();
mLastAddressbookSync = QDateTime::currentDateTime();
QDateTime modifiedCalendar = mLastAddressbookSync;;
addresseeLSync = getLastSyncAddressee();
qDebug("Last Sync %s ", addresseeLSync.revision().toString().latin1());
addresseeR = remote->findByUid("last-syncAddressee-"+mCurrentSyncName );
if ( !addresseeR.isEmpty() ) {
addresseeRSync = addresseeR;
remote->removeAddressee(addresseeR );
} else {
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
addresseeRSync = addresseeLSync ;
} else {
qDebug("FULLDATE 1");
fullDateRange = true;
Addressee newAdd;
addresseeRSync = newAdd;
addresseeRSync.setFamilyName(mCurrentSyncName + i18n(" - sync addressee"));
addresseeRSync.setUid("last-syncAddressee-"+mCurrentSyncName );
addresseeRSync.setRevision( mLastAddressbookSync );
addresseeRSync.setCategories( i18n("SyncAddressee") );
}
}
if ( addresseeLSync.revision() == mLastAddressbookSync ) {
qDebug("FULLDATE 2");
fullDateRange = true;
}
if ( ! fullDateRange ) {
if ( addresseeLSync.revision() != addresseeRSync.revision() ) {
// qDebug("set fulldate to true %s %s" ,addresseeLSync->dtStart().toString().latin1(), addresseeRSync->dtStart().toString().latin1() );
//qDebug("%d %d %d %d ", addresseeLSync->dtStart().time().second(), addresseeLSync->dtStart().time().msec() , addresseeRSync->dtStart().time().second(), addresseeRSync->dtStart().time().msec());
fullDateRange = true;
qDebug("FULLDATE 3 %s %s", addresseeLSync.revision().toString().latin1() , addresseeRSync.revision().toString().latin1() );
}
}
// fullDateRange = true; // debug only!
if ( fullDateRange )
mLastAddressbookSync = QDateTime::currentDateTime().addDays( -100*365);
else
mLastAddressbookSync = addresseeLSync.revision();
// for resyncing if own file has changed
// PENDING fixme later when implemented
#if 0
if ( mCurrentSyncDevice == "deleteaftersync" ) {
mLastAddressbookSync = loadedFileVersion;
qDebug("setting mLastAddressbookSync ");
}
#endif
//qDebug("*************************** ");
// qDebug("mLastAddressbookSync %s ",mLastAddressbookSync.toString().latin1() );
QStringList er = remote->uidList();
Addressee inR ;//= er.first();
Addressee inL;
syncManager->showProgressBar(0, i18n("Syncing - close to abort!"), er.count());
int modulo = (er.count()/10)+1;
int incCounter = 0;
while ( incCounter < er.count()) {
if (syncManager->isProgressBarCanceled())
return false;
if ( incCounter % modulo == 0 )
syncManager->showProgressBar(incCounter);
uid = er[ incCounter ];
bool skipIncidence = false;
if ( uid.left(19) == QString("last-syncAddressee-") )
skipIncidence = true;
QString idS,OidS;
qApp->processEvents();
if ( !skipIncidence ) {
inL = local->findByUid( uid );
inR = remote->findByUid( uid );
//inL.setResource( 0 );
//inR.setResource( 0 );
if ( !inL.isEmpty() ) { // maybe conflict - same uid in both calendars
if ( take = takeAddressee( &inL, &inR, mode, fullDateRange ) ) {
//qDebug("take %d %s ", take, inL.summary().latin1());
if ( take == 3 )
return false;
if ( take == 1 ) {// take local
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
inL.setCsum( mCurrentSyncDevice, inR.getCsum(mCurrentSyncDevice) );
inL.setID( mCurrentSyncDevice, inR.getID(mCurrentSyncDevice) );
local->insertAddressee( inL, false );
idS = inR.externalUID();
OidS = inR.originalExternalUID();
}
else
idS = inR.IDStr();
remote->removeAddressee( inR );
inR = inL;
inR.setTempSyncStat( SYNC_TEMPSTATE_INITIAL );
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
inR.setOriginalExternalUID( OidS );
inR.setExternalUID( idS );
} else {
inR.setIDStr( idS );
}
inR.setResource( 0 );
remote->insertAddressee( inR , false);
++changedRemote;
} else { // take == 2 take remote
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
if ( inR.revision().date().year() < 2004 )
inR.setRevision( modifiedCalendar );
}
idS = inL.IDStr();
local->removeAddressee( inL );
inL = inR;
inL.setIDStr( idS );
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
inL.setCsum( mCurrentSyncDevice, inR.getCsum(mCurrentSyncDevice) );
inL.setID( mCurrentSyncDevice, inR.getID(mCurrentSyncDevice) );
}
inL.setResource( 0 );
local->insertAddressee( inL , false );
++changedLocal;
}
}
} else { // no conflict
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
QString des = addresseeLSync.note();
if ( des.find( inR.getID(mCurrentSyncDevice) +"," ) >= 0 && mode != 5) { // delete it
inR.setTempSyncStat( SYNC_TEMPSTATE_DELETE );
remote->insertAddressee( inR, false );
++deletedAddresseeR;
} else {
inR.setRevision( modifiedCalendar );
remote->insertAddressee( inR, false );
inL = inR;
inL.setResource( 0 );
local->insertAddressee( inL , false);
++addedAddressee;
}
} else {
if ( inR.revision() > mLastAddressbookSync || mode == 5 ) {
inR.setRevision( modifiedCalendar );
remote->insertAddressee( inR, false );
inR.setResource( 0 );
local->insertAddressee( inR, false );
++addedAddressee;
} else {
// pending checkExternSyncAddressee(addresseeRSyncSharp, inR);
remote->removeAddressee( inR );
++deletedAddresseeR;
}
}
}
}
++incCounter;
}
er.clear();
QStringList el = local->uidList();
modulo = (el.count()/10)+1;
syncManager->showProgressBar(0, i18n("Add / remove addressees"), el.count());
incCounter = 0;
while ( incCounter < el.count()) {
qApp->processEvents();
if (syncManager->isProgressBarCanceled())
return false;
if ( incCounter % modulo == 0 )
syncManager->showProgressBar(incCounter);
uid = el[ incCounter ];
bool skipIncidence = false;
if ( uid.left(19) == QString("last-syncAddressee-") )
skipIncidence = true;
if ( !skipIncidence ) {
inL = local->findByUid( uid );
inR = remote->findByUid( uid );
if ( inR.isEmpty() ) {
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
if ( !inL.getID(mCurrentSyncDevice).isEmpty() && mode != 4 ) {
// pending checkExternSyncAddressee(addresseeLSyncSharp, inL);
local->removeAddressee( inL );
++deletedAddresseeL;
} else {
if ( ! syncManager->mWriteBackExistingOnly ) {
inL.removeID(mCurrentSyncDevice );
++addedAddresseeR;
inL.setRevision( modifiedCalendar );
local->insertAddressee( inL, false );
inR = inL;
inR.setTempSyncStat( SYNC_TEMPSTATE_ADDED_EXTERNAL );
inR.setResource( 0 );
remote->insertAddressee( inR, false );
}
}
} else {
if ( inL.revision() < mLastAddressbookSync && mode != 4 ) {
// pending checkExternSyncAddressee(addresseeLSyncSharp, inL);
local->removeAddressee( inL );
++deletedAddresseeL;
} else {
if ( ! syncManager->mWriteBackExistingOnly ) {
++addedAddresseeR;
inL.setRevision( modifiedCalendar );
local->insertAddressee( inL, false );
inR = inL;
inR.setResource( 0 );
remote->insertAddressee( inR, false );
}
}
}
}
}
++incCounter;
}
el.clear();
syncManager->hideProgressBar();
mLastAddressbookSync = QDateTime::currentDateTime().addSecs( 1 );
// get rid of micro seconds
QTime t = mLastAddressbookSync.time();
mLastAddressbookSync.setTime( QTime (t.hour (), t.minute (), t.second () ) );
addresseeLSync.setRevision( mLastAddressbookSync );
addresseeRSync.setRevision( mLastAddressbookSync );
addresseeRSync.setRole( i18n("!Remote from: ")+mCurrentSyncName ) ;
addresseeLSync.setRole(i18n("!Local from: ") + mCurrentSyncName );
addresseeRSync.setGivenName( i18n("!DO NOT EDIT!") ) ;
addresseeLSync.setGivenName(i18n("!DO NOT EDIT!") );
addresseeRSync.setOrganization( "!"+mLastAddressbookSync.toString() ) ;
addresseeLSync.setOrganization("!"+ mLastAddressbookSync.toString() );
addresseeRSync.setNote( "" ) ;
addresseeLSync.setNote( "" );
if ( mGlobalSyncMode == SYNC_MODE_NORMAL)
remote->insertAddressee( addresseeRSync, false );
local->insertAddressee( addresseeLSync, false );
QString mes;
mes .sprintf( i18n("Synchronization summary:\n\n %d items added to local\n %d items added to remote\n %d items updated on local\n %d items updated on remote\n %d items deleted on local\n %d items deleted on remote\n"),addedAddressee, addedAddresseeR, changedLocal, changedRemote, deletedAddresseeL, deletedAddresseeR );
if ( syncManager->mShowSyncSummary ) {
KMessageBox::information(this, mes, i18n("KA/Pi Synchronization") );
}
qDebug( mes );
return syncOK;
}
//this is a overwritten callbackmethods from the syncinterface
bool KABCore::sync(KSyncManager* manager, QString filename, int mode)
{
//pending prepare addresseeview for output
//pending detect, if remote file has REV field. if not switch to external sync
mGlobalSyncMode = SYNC_MODE_NORMAL;
QString mCurrentSyncDevice = manager->getCurrentSyncDevice();
AddressBook abLocal(filename,"syncContact");
bool syncOK = false;
if ( abLocal.load() ) {
qDebug("AB loaded %s,sync mode %d",filename.latin1(), mode );
bool external = false;
bool isXML = false;
if ( filename.right(4) == ".xml") {
mGlobalSyncMode = SYNC_MODE_EXTERNAL;
isXML = true;
abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice );
} else {
Addressee lse = mAddressBook->findByUid( "last-syncAddressee-"+mCurrentSyncDevice );
if ( ! lse.isEmpty() ) {
if ( lse.familyName().left(4) == "!E: " )
external = true;
} else {
bool found = false;
AddressBook::Iterator it;
for ( it = abLocal.begin(); it != abLocal.end(); ++it ) {
if ( (*it).revision().date().year() > 2003 ) {
found = true;
break;
}
}
external = ! found;
}
if ( external ) {
qDebug("Setting vcf mode to external ");
mGlobalSyncMode = SYNC_MODE_EXTERNAL;
AddressBook::Iterator it;
for ( it = abLocal.begin(); it != abLocal.end(); ++it ) {
(*it).setID( mCurrentSyncDevice, (*it).uid() );
(*it).computeCsum( mCurrentSyncDevice );
}
}
}
//AddressBook::Iterator it;
//QStringList vcards;
//for ( it = abLocal.begin(); it != abLocal.end(); ++it ) {
// qDebug("Name %s ", (*it).familyName().latin1());
//}
syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, mode );
if ( syncOK ) {
if ( syncManager->mWriteBackFile )
{
if ( external )
abLocal.removeSyncAddressees( !isXML);
qDebug("Saving remote AB ");
if ( ! abLocal.saveAB())
qDebug("Error writing back AB to file ");
if ( isXML ) {
// afterwrite processing
abLocal.postExternSync( mAddressBook,mCurrentSyncDevice );
}
}
}
setModified();
}
if ( syncOK )
mViewManager->refreshView();
return syncOK;
}
//this is a overwritten callbackmethods from the syncinterface
bool KABCore::syncExternal(KSyncManager* manager, QString resource)
{
if ( resource == "phone" )
return syncPhone();
QString mCurrentSyncDevice = manager->getCurrentSyncDevice();
AddressBook abLocal( resource,"syncContact");
bool syncOK = false;
if ( abLocal.load() ) {
qDebug("AB sharp loaded ,sync device %s",mCurrentSyncDevice.latin1());
mGlobalSyncMode = SYNC_MODE_EXTERNAL;
abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice );
syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, syncManager->mSyncAlgoPrefs );
if ( syncOK ) {
if ( syncManager->mWriteBackFile ) {
+ abLocal.removeSyncAddressees( false );
abLocal.saveAB();
abLocal.postExternSync( mAddressBook,mCurrentSyncDevice );
}
}
setModified();
}
if ( syncOK )
mViewManager->refreshView();
return syncOK;
}
void KABCore::message( QString m )
{
topLevelWidget()->setCaption( m );
QTimer::singleShot( 15000, this , SLOT ( setCaptionBack()));
}
bool KABCore::syncPhone()
{
QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice();
QString fileName;
#ifdef _WIN32_
fileName = locateLocal("tmp", "phonefile.vcf");
#else
fileName = "/tmp/phonefile.vcf";
#endif
if ( !PhoneAccess::readFromPhone( fileName) ) {
message(i18n("Phone access failed!"));
return false;
}
AddressBook abLocal( fileName,"syncContact");
bool syncOK = false;
- if ( abLocal.load() ) {
+ {
+ abLocal.importFromFile( fileName );
qDebug("AB phone loaded ,sync device %s",mCurrentSyncDevice.latin1());
mGlobalSyncMode = SYNC_MODE_EXTERNAL;
abLocal.preparePhoneSync( mCurrentSyncDevice, true );
abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice );
syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, syncManager->mSyncAlgoPrefs );
if ( syncOK ) {
if ( syncManager->mWriteBackFile ) {
+ abLocal.removeSyncAddressees( true );
abLocal.saveABphone( fileName );
- abLocal.preparePhoneSync( mCurrentSyncDevice, false );
- abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice );
+ abLocal.findNewExtIds( fileName, mCurrentSyncDevice );
+ //abLocal.preparePhoneSync( mCurrentSyncDevice, false );
abLocal.postExternSync( mAddressBook,mCurrentSyncDevice );
}
}
setModified();
}
if ( syncOK )
mViewManager->refreshView();
return syncOK;
}
void KABCore::getFile( bool success )
{
if ( ! success ) {
message( i18n("Error receiving file. Nothing changed!") );
return;
}
mAddressBook->importFromFile( sentSyncFile() , false, true );
message( i18n("Pi-Sync successful!") );
mViewManager->refreshView();
}
void KABCore::syncFileRequest()
{
mAddressBook->export2File( sentSyncFile() );
}
QString KABCore::sentSyncFile()
{
#ifdef _WIN32_
return locateLocal( "tmp", "copysyncab.vcf" );
#else
return QString( "/tmp/copysyncab.vcf" );
#endif
}
void KABCore::setCaptionBack()
{
topLevelWidget()->setCaption( i18n("KAddressbook/Pi") );
}
diff --git a/libkdepim/ksyncprefsdialog.cpp b/libkdepim/ksyncprefsdialog.cpp
index 84cc448..cf8f996 100644
--- a/libkdepim/ksyncprefsdialog.cpp
+++ b/libkdepim/ksyncprefsdialog.cpp
@@ -1,731 +1,732 @@
/*
This file is part of KOrganizer.
Copyright (c) 2004 Lutz Rogowski <rogowski@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlayout.h>
#include <qlabel.h>
#include <qgroupbox.h>
#include <qbuttongroup.h>
#include <qlineedit.h>
#include <qfont.h>
#include <qslider.h>
#include <qfile.h>
#include <qdir.h>
#include <qtextstream.h>
#include <qcombobox.h>
#include <qvbox.h>
#include <qhbox.h>
#include <qspinbox.h>
#include <qdatetime.h>
#include <qcheckbox.h>
#include <qradiobutton.h>
#include <qpushbutton.h>
#include <qstrlist.h>
#include <qapplication.h>
#include <qlayout.h>
#include <qscrollview.h>
#include <kcolorbutton.h>
#include <kdebug.h>
#include <klocale.h>
#include <kglobal.h>
#include <kfontdialog.h>
#include <kmessagebox.h>
#include <kcolordialog.h>
#include <kiconloader.h>
#include <kemailsettings.h>
#include <kstandarddirs.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
//#include <kurlrequester.h>
#include <klineedit.h>
#include "ksyncprofile.h"
//#include "koprefs.h"
#include "ksyncprefsdialog.h"
//#include "koglobals.h"
KSyncPrefsDialog::KSyncPrefsDialog(QWidget *parent, char *name, bool modal) :
KDialog(parent,name,true)
{
setCaption( i18n("Synchronization Preferences"));
mSyncProfiles.setAutoDelete( true );
setupSyncAlgTab();
}
KSyncPrefsDialog::~KSyncPrefsDialog()
{
}
void KSyncPrefsDialog::setupSyncAlgTab()
{
QLabel * lab;
//QFrame *page = addPage(i18n("Sync Prefs"),0,0);
QVBox * mainbox = new QVBox( this );
QScrollView* sv = new QScrollView( mainbox );
QHBoxLayout * lay = new QHBoxLayout( this );
lay->addWidget( mainbox );
QHBox * b_box = new QHBox( mainbox );
QPushButton* button = new QPushButton( i18n("Ok"), b_box );
connect ( button, SIGNAL( clicked()), this, SLOT (slotOK() ) );
button = new QPushButton( i18n("Cancel"), b_box );
connect ( button, SIGNAL( clicked()), this, SLOT (reject() ) );
//QBoxLayout * sl = new QVBoxLayout(this );
//sl->addWidget ( sv );
sv->setResizePolicy ( QScrollView::AutoOneFit );
QFrame *topFrame = new QFrame ( sv );
sv->addChild( topFrame );
mSetupSyncAlgTab = topFrame;
QGridLayout *topLayout = new QGridLayout(topFrame,6,2);
topLayout->setSpacing(spacingHint());
topLayout->setMargin(marginHint());
//lab = new QLabel(i18n("Sync settings not yet implemented. DO NOT USE!"), topFrame);
int iii = 0;
//topLayout->addMultiCellWidget(lab , iii,iii,0,1);
//++iii;
mMyMachineName = new QLineEdit(topFrame);
lab = new QLabel(mMyMachineName, i18n("Local device name:"), topFrame);
topLayout->addWidget(lab ,iii,0);
topLayout->addWidget(mMyMachineName,iii,1);
++iii;
QHBox* buttonbox = new QHBox( topFrame);
topLayout->addMultiCellWidget(buttonbox, iii,iii,0,1);
++iii;
button = new QPushButton( i18n("New profile"), buttonbox );
connect ( button, SIGNAL( clicked()), this, SLOT (newProfile() ) );
button = new QPushButton( i18n("Clone profile"), buttonbox );
connect ( button, SIGNAL( clicked()), this, SLOT ( cloneProfile() ) );
button = new QPushButton( i18n("Delete profile"), buttonbox );
connect ( button, SIGNAL( clicked()), this, SLOT (deleteProfile() ) );
mProfileBox = new QComboBox(topFrame);
mProfileBox->setEditable ( true );
mProfileBox->setInsertionPolicy(QComboBox::NoInsertion);
connect ( mProfileBox, SIGNAL(activated ( int ) ), this, SLOT (profileChanged( int ) ) );
connect ( mProfileBox, SIGNAL( textChanged ( const QString & ) ), this, SLOT (textChanged( const QString & ) ) );
lab = new QLabel(mProfileBox, i18n("Profile:"), topFrame);
topLayout->addWidget(lab ,iii,0);
topLayout->addWidget(mProfileBox, iii,1);
++iii;
QHBox *iims = new QHBox( topFrame );
new QLabel( i18n("Include in multiple "), iims );
mIncludeInRing = new QCheckBox( i18n("calendar "), iims );
mIncludeInRingAB = new QCheckBox( i18n("addressbook "), iims );
mIncludeInRingPWM = new QCheckBox( i18n("pwmanager"), iims );
new QLabel( i18n(" sync"), iims );
topLayout->addMultiCellWidget(iims, iii,iii,0,1);
++iii;
mAskForPreferences = new QCheckBox( i18n("Ask for preferences before sync"), topFrame );
topLayout->addMultiCellWidget(mAskForPreferences, iii,iii,0,1);
++iii;
QButtonGroup* gr = new QButtonGroup ( 1, Qt::Horizontal, i18n("Sync preferences"), topFrame);
topLayout->addMultiCellWidget(gr, iii,iii,0,1);
++iii;
loc = new QRadioButton ( i18n("Take local entry on conflict"), gr );
rem = new QRadioButton ( i18n("Take remote entry on conflict"), gr );
newest = new QRadioButton ( i18n("Take newest entry on conflict"), gr );
ask = new QRadioButton ( i18n("Ask for every entry on conflict"), gr );
f_loc= new QRadioButton ( i18n("Force: Take local entry always"), gr );
f_rem = new QRadioButton ( i18n("Force: Take remote entry always"), gr );
// both = new QRadioButton ( i18n("Take both on conflict"), gr );
mShowSummaryAfterSync = new QCheckBox( i18n("Show summary after sync"), topFrame );
topLayout->addMultiCellWidget(mShowSummaryAfterSync, iii,iii,0,1);
++iii;
mWriteBackFile = new QCheckBox( i18n("Write back synced data"), topFrame );
topLayout->addMultiCellWidget(mWriteBackFile, iii,iii,0,1);
++iii;
mWriteBackExisting= new QCheckBox( i18n("-- Write back (on remote) existing entries only"), topFrame );
topLayout->addMultiCellWidget(mWriteBackExisting, iii,iii,0,1);
++iii;
mWriteBackFuture= new QCheckBox( i18n("-- Write back (calendar) entries in future only"), topFrame );
topLayout->addMultiCellWidget(mWriteBackFuture, iii,iii,0,1);
++iii;
topLayout->addMultiCellWidget(new QLabel( i18n("---- Max. weeks in future: ") , topFrame ), iii,iii,0,0);
mWriteBackFutureWeeks= new QSpinBox(1,104, 1, topFrame);
topLayout->addMultiCellWidget(mWriteBackFutureWeeks, iii,iii,1,1);
++iii;
proGr = new QButtonGroup ( 1, Qt::Horizontal, i18n("Profile kind"), topFrame);
gr = proGr;
topLayout->addMultiCellWidget(gr, iii,iii,0,1);
++iii;
mIsLocal = new QRadioButton ( i18n("Local file"), gr );
mIsPi = new QRadioButton ( i18n("Pi-Sync ( direct Kx/Pi to Kx/Pi sync )"), gr );
connect (mIsPi, SIGNAL( toggled(bool)), this, SLOT (kindChanged(bool) ) );
mIsNotLocal = new QRadioButton ( i18n("Remote file (w down/upload command)"), gr );
connect (mIsLocal, SIGNAL( toggled(bool)), this, SLOT (kindChanged(bool) ) );
mIsPhone = new QRadioButton ( i18n("Mobile device (cell phone)"), gr );
connect (mIsPhone, SIGNAL( toggled(bool)), this, SLOT (kindChanged(bool) ) );
phoneWidget = new QVBox( topFrame);
topLayout->addMultiCellWidget(phoneWidget, iii,iii,0,1);
++iii;
- mWriteContactToSIM= new QCheckBox( i18n("Sync contacts with phone SIM card (If not, sync with phone memory)"), phoneWidget );
+ mWriteContactToSIM = 0;//new QCheckBox( i18n("Sync contacts with phone SIM card (If not, sync with phone memory)"), phoneWidget );
QHBox* temphb = new QHBox( phoneWidget );
new QLabel( i18n("I/O device: "), temphb );
mPhoneDevice = new QLineEdit( temphb);
button = new QPushButton( i18n("Help..."), temphb );
connect ( button, SIGNAL( clicked()), this, SLOT ( helpDevice() ) );
temphb = new QHBox( phoneWidget );
new QLabel( i18n("Connection: "), temphb );
mPhoneConnection = new QLineEdit( temphb);
button = new QPushButton( i18n("Help..."), temphb );
connect ( button, SIGNAL( clicked()), this, SLOT ( helpConnection() ) );
temphb = new QHBox( phoneWidget );
new QLabel( i18n("Model(opt.): "), temphb );
mPhoneModel = new QLineEdit( temphb);
button = new QPushButton( i18n("Help..."), temphb );
connect ( button, SIGNAL( clicked()), this, SLOT ( helpModel() ) );
// *** local
localFileWidget = new QVBox( topFrame);
topLayout->addMultiCellWidget(localFileWidget, iii,iii,0,1);
++iii;
temphb = new QHBox( localFileWidget );
lab = new QLabel( i18n("Local file Cal:"), temphb );
lab = new QLabel( i18n("Local file ABook:"), temphb );
lab = new QLabel( i18n("Local file PWMgr:"), temphb );
temphb = new QHBox( localFileWidget );
button = new QPushButton( i18n("Choose..."), temphb );
connect ( button, SIGNAL( clicked()), this, SLOT ( chooseFile() ) );
button = new QPushButton( i18n("Choose..."), temphb );
connect ( button, SIGNAL( clicked()), this, SLOT ( chooseFileAB() ) );
button = new QPushButton( i18n("Choose..."), temphb );
connect ( button, SIGNAL( clicked()), this, SLOT ( chooseFilePWM() ) );
temphb = new QHBox( localFileWidget );
mRemoteFile = new QLineEdit( temphb);
mRemoteFileAB = new QLineEdit( temphb);
mRemoteFilePWM = new QLineEdit( temphb);
// *** remote
remoteFileWidget = new QVBox( topFrame);
topLayout->addMultiCellWidget(remoteFileWidget, iii,iii,0,1);
++iii;
temphb = new QHBox( remoteFileWidget );
new QLabel( i18n("Calendar:"), temphb);
new QLabel( i18n("AddressBook:"), temphb);
new QLabel( i18n("PWManager:"), temphb);
lab = new QLabel( i18n("Pre sync (download) command:"), remoteFileWidget);
temphb = new QHBox( remoteFileWidget );
mRemotePrecommand = new QLineEdit(temphb);
mRemotePrecommandAB = new QLineEdit(temphb);
mRemotePrecommandPWM = new QLineEdit(temphb);
lab = new QLabel( i18n("Local temp file:"), remoteFileWidget);
temphb = new QHBox( remoteFileWidget );
mLocalTempFile = new QLineEdit(temphb);
mLocalTempFileAB = new QLineEdit(temphb);
mLocalTempFilePWM = new QLineEdit(temphb);
lab = new QLabel( i18n("Post sync (upload) command:"), remoteFileWidget);
temphb = new QHBox( remoteFileWidget );
mRemotePostcommand = new QLineEdit(temphb );
mRemotePostcommandAB = new QLineEdit(temphb );
mRemotePostcommandPWM = new QLineEdit(temphb );
lab = new QLabel( i18n("Fill in default values for:"), remoteFileWidget);
temphb = new QHBox( remoteFileWidget );
button = new QPushButton( i18n("ssh/scp"), temphb );
connect ( button, SIGNAL( clicked()), this, SLOT (fillSSH() ) );
button = new QPushButton( i18n("ftp"), temphb );
connect ( button, SIGNAL( clicked()), this, SLOT (fillFTP() ) );
lab = new QLabel( i18n("Hint: Use $PWD$ for placeholder of password!"), remoteFileWidget);
// *** pi-sync
piWidget = new QVBox( topFrame);
topLayout->addMultiCellWidget(piWidget, iii,iii,0,1);
++iii;
temphb = new QHBox( piWidget );
new QLabel( i18n("Calendar:"), temphb);
new QLabel( i18n("AddressBook:"), temphb);
new QLabel( i18n("PWManager:"), temphb);
lab = new QLabel( i18n("Password for remote access: (could be the same for each)"), piWidget);
temphb = new QHBox( piWidget );
mRemotePw = new QLineEdit(temphb);
mRemotePwAB = new QLineEdit(temphb);
mRemotePwPWM = new QLineEdit(temphb);
lab = new QLabel( i18n("Remote IP address: (could be the same for each)"), piWidget);
temphb = new QHBox( piWidget );
mRemoteIP = new QLineEdit(temphb);
mRemoteIPAB = new QLineEdit(temphb);
mRemoteIPPWM = new QLineEdit(temphb);
lab = new QLabel( i18n("Remote port number: (should be different for each)"), piWidget);
temphb = new QHBox( piWidget );
mRemotePort = new QLineEdit(temphb);
mRemotePortAB = new QLineEdit(temphb);
mRemotePortPWM = new QLineEdit(temphb);
}
void KSyncPrefsDialog::slotOK()
{
if ( mMyMachineName->text() == "undefined" ) {
KMessageBox::error(this,i18n("Local device name undefined!\nPlease define device name!"),i18n("KO/Pi config error"));
return;
}
int i;
for (i = 0; i < mSyncProfileNames.count(); ++ i) {
if ( mSyncProfileNames.contains( mSyncProfileNames[i]) > 1 ) {
KMessageBox::error(this,i18n("Multiple profiles with same name!\nPlease use unique profile names!"),i18n("KO/Pi config error"));
return;
}
}
usrWriteConfig();
QDialog::accept();
}
void KSyncPrefsDialog::accept()
{
slotOK();
}
void KSyncPrefsDialog::chooseFile()
{
QString fn = QDir::homeDirPath();
fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename(*.ics/*.vcs)"), this );
if ( fn == "" )
return;
mRemoteFile->setText( fn );
}
void KSyncPrefsDialog::chooseFileAB()
{
QString fn = QDir::homeDirPath();
fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename(*.vcf)"), this );
if ( fn == "" )
return;
mRemoteFileAB->setText( fn );
}
void KSyncPrefsDialog::chooseFilePWM()
{
QString fn = QDir::homeDirPath();
fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename(*.pwm)"), this );
if ( fn == "" )
return;
mRemoteFilePWM->setText( fn );
}
void KSyncPrefsDialog::textChanged( const QString & s )
{
if ( mProfileBox->count() == 0 )
return;
if ( currentSelection < 3 ) {
//KMessageBox::error(this,i18n("This profil name\ncannot be edited!\n"),i18n("KO/Pi config error"));
mProfileBox->blockSignals( true );
mProfileBox->setCurrentItem(mProfileBox-> currentItem ());
mProfileBox->blockSignals( false );
return;
}
//qDebug("cur i %d ",mProfileBox-> currentItem () );
mProfileBox->changeItem ( s, mProfileBox-> currentItem () ) ;
KSyncProfile* prof = mSyncProfiles.at(mProfileBox-> currentItem ()) ;
prof->setName( s );
mSyncProfileNames[mProfileBox-> currentItem ()] = s;
}
void KSyncPrefsDialog::profileChanged( int item )
{
//qDebug("KSyncPrefsDialog::profileChanged before %d, count %d ", item, mProfileBox->count() );
KSyncProfile* prof;
saveProfile();
currentSelection = item;
prof = mSyncProfiles.at(item) ;
mRemotePw->setText(prof->getRemotePw());
mRemoteIP->setText(prof->getRemoteIP());
mRemotePort->setText(prof->getRemotePort());
mRemotePwAB->setText(prof->getRemotePwAB());
mRemoteIPAB->setText(prof->getRemoteIPAB());
mRemotePortAB->setText(prof->getRemotePortAB());
mRemotePwPWM->setText(prof->getRemotePwPWM());
mRemoteIPPWM->setText(prof->getRemoteIPPWM());
mRemotePortPWM->setText(prof->getRemotePortPWM());
mRemotePrecommand->setText(prof->getPreSyncCommand());
mRemotePostcommand->setText(prof->getPostSyncCommand());
mLocalTempFile->setText(prof->getLocalTempFile());
mRemoteFile->setText(prof->getRemoteFileName()) ;
mRemotePrecommandAB->setText(prof->getPreSyncCommandAB());
mRemotePostcommandAB->setText(prof->getPostSyncCommandAB());
mLocalTempFileAB->setText(prof->getLocalTempFileAB());
mRemoteFileAB->setText(prof->getRemoteFileNameAB()) ;
mRemotePrecommandPWM->setText(prof->getPreSyncCommandPWM());
mRemotePostcommandPWM->setText(prof->getPostSyncCommandPWM());
mLocalTempFilePWM->setText(prof->getLocalTempFilePWM());
mRemoteFilePWM->setText(prof->getRemoteFileNamePWM()) ;
- mWriteContactToSIM->setChecked( prof->getWriteContactToSIM());
+ if ( mWriteContactToSIM )
+ mWriteContactToSIM->setChecked( prof->getWriteContactToSIM());
mPhoneDevice->setText(prof->getPhoneDevice());
mPhoneConnection->setText(prof->getPhoneConnection());
mPhoneModel->setText(prof->getPhoneModel());
mShowSummaryAfterSync->setChecked( prof->getShowSummaryAfterSync());
mAskForPreferences->setChecked( prof->getAskForPreferences());
mWriteBackExisting->setChecked( prof->getWriteBackExisting() );
mWriteBackFile->setChecked( prof->getWriteBackFile());
mIncludeInRing->setChecked( prof->getIncludeInRingSync() );
mIncludeInRingAB->setChecked( prof->getIncludeInRingSyncAB() );
mIncludeInRingPWM->setChecked( prof->getIncludeInRingSyncPWM() );
mWriteBackFuture->setChecked( prof->getWriteBackFuture());
mWriteBackFutureWeeks->setValue( prof->getWriteBackFutureWeeks() );
switch ( prof->getSyncPrefs() ) {
case 0:
loc->setChecked( true);
break;
case 1:
rem->setChecked( true );
break;
case 2:
newest->setChecked( true);
break;
case 3:
ask->setChecked( true);
break;
case 4:
f_loc->setChecked( true);
break;
case 5:
f_rem->setChecked( true);
break;
case 6:
//both->setChecked( true);
break;
default:
break;
}
mIsLocal->setChecked(prof->getIsLocalFileSync()) ;
mIsPhone->setChecked(prof->getIsPhoneSync()) ;
mIsPi->setChecked(prof->getIsPiSync()) ;
mIsNotLocal->setChecked(!prof->getIsLocalFileSync() && !prof->getIsPhoneSync() &&!prof->getIsPiSync() );
proGr->setEnabled( item > 2 );
if ( item < 3 ) {
localFileWidget->hide();
remoteFileWidget->hide();
phoneWidget->hide();
piWidget->hide();
} else
kindChanged( prof->getIsLocalFileSync() );
}
void KSyncPrefsDialog::fillSSH()
{
mRemotePrecommand->setText("scp zaurus@192.168.0.65:/home/zaurus/kdepim/apps/korganizer/mycalendar.ics /tmp/mycalendar.ics" );
mLocalTempFile->setText("/tmp/mycalendar.ics" );
mRemotePostcommand->setText("scp /tmp/mycalendar.ics zaurus@192.168.0.65:/home/zaurus/kdepim/apps/korganizer/mycalendar.ics" );
mRemotePrecommandAB->setText("scp zaurus@192.168.0.65:/home/zaurus/kdepim/apps/kabc/std.vcf /tmp/std.vcf" );
mLocalTempFileAB->setText("/tmp/std.vcf" );
mRemotePostcommandAB->setText("scp /tmp/std.vcf zaurus@192.168.0.65:/home/zaurus/kdepim/apps/kabc/std.vcf" );
mRemotePrecommandPWM->setText("scp zaurus@192.168.0.65:/home/zaurus/kdepim/apps/pwmanager/passwords.pwm /tmp/passwords.pwm" );
mLocalTempFilePWM->setText("/tmp/passwords.pwm" );
mRemotePostcommandPWM->setText("scp /tmp/passwords.pwm zaurus@192.168.0.65:/home/zaurus/kdepim/apps/pwmanager/pwmanager.pwm" );
}
void KSyncPrefsDialog::fillFTP()
{
mRemotePrecommand->setText("cd /tmp;ftp ftp://zaurus:a@192.168.0.65/kdepim/apps/korganizer/mycalendar.ics" );
mLocalTempFile->setText("/tmp/mycalendar.ics" );
mRemotePostcommand->setText("ftp -u ftp://zaurus:a@192.168.0.65/kdepim/apps/korganizer/mycalendar.ics /tmp/mycalendar.ics" );
mRemotePrecommandAB->setText("cd /tmp;ftp ftp://zaurus:a@192.168.0.65/kdepim/apps/kabc/std.vcf" );
mLocalTempFileAB->setText("/tmp/std.vcf" );
mRemotePostcommandAB->setText("ftp -u ftp://zaurus:a@192.168.0.65/kdepim/apps/kabc/std.vcf /tmp/std.vcf" );
mRemotePrecommandPWM->setText("cd /tmp;ftp ftp://zaurus:a@192.168.0.65/kdepim/apps/pwmanager/passwords.pwm" );
mLocalTempFilePWM->setText("/tmp/passwords.pwm" );
mRemotePostcommandPWM->setText("ftp -u ftp://zaurus:a@192.168.0.65/kdepim/apps/pwmanager/passwords.pwm /tmp/passwords.pwm" );
}
void KSyncPrefsDialog::kindChanged( bool b )
{
if ( mIsLocal->isChecked () )
localFileWidget->show();
else
localFileWidget->hide();
if ( mIsNotLocal->isChecked () )
remoteFileWidget->show();
else
remoteFileWidget->hide();
if ( mIsPhone->isChecked () ) {
phoneWidget->show();
}
else {
phoneWidget->hide();
}
if ( mIsPi->isChecked () ) {
piWidget->show();
}
else {
piWidget->hide();
}
}
void KSyncPrefsDialog::deleteProfile()
{
//qDebug("KSyncPrefsDialog::deleteProfile() ");
if ( currentSelection >= 0 ) {
if ( currentSelection < 3 ) {
KMessageBox::error(this,i18n("This profil cannot be deleted!\n"),i18n("KO/Pi config error"));
return;
}
KSyncProfile* temp = mSyncProfiles.at(currentSelection);
mSyncProfiles.remove( temp );
mSyncProfileNames.remove( mSyncProfileNames.at( currentSelection ));
insertProfiles();
}
}
void KSyncPrefsDialog::saveProfile()
{
KSyncProfile* prof;
if ( currentSelection >= 0 ) {
prof = mSyncProfiles.at(currentSelection) ;
prof->setRemotePw( mRemotePw->text());
prof->setRemoteIP( mRemoteIP->text());
prof->setRemotePort( mRemotePort->text());
prof->setRemotePwAB( mRemotePwAB->text());
prof->setRemoteIPAB( mRemoteIPAB->text());
prof->setRemotePortAB( mRemotePortAB->text());
prof->setRemotePwPWM( mRemotePwPWM->text());
prof->setRemoteIPPWM( mRemoteIPPWM->text());
prof->setRemotePortPWM( mRemotePortPWM->text());
prof->setPreSyncCommand( mRemotePrecommand->text());
prof->setPostSyncCommand( mRemotePostcommand->text() );
prof->setLocalTempFile( mLocalTempFile->text());
prof->setRemoteFileName( mRemoteFile->text() );
prof->setPreSyncCommandAB( mRemotePrecommandAB->text());
prof->setPostSyncCommandAB( mRemotePostcommandAB->text() );
prof->setLocalTempFileAB( mLocalTempFileAB->text());
prof->setRemoteFileNameAB( mRemoteFileAB->text() );
prof->setPreSyncCommandPWM( mRemotePrecommandPWM->text());
prof->setPostSyncCommandPWM( mRemotePostcommandPWM->text() );
prof->setLocalTempFilePWM( mLocalTempFilePWM->text());
prof->setRemoteFileNamePWM( mRemoteFilePWM->text() );
prof->setShowSummaryAfterSync( mShowSummaryAfterSync->isChecked() );
prof->setAskForPreferences( mAskForPreferences->isChecked());
prof->setWriteBackExisting(mWriteBackExisting->isChecked() );
prof->setWriteBackFile( mWriteBackFile->isChecked());
prof->setIncludeInRingSync( mIncludeInRing->isChecked() );
prof->setIncludeInRingSyncAB( mIncludeInRingAB->isChecked() );
prof->setIncludeInRingSyncPWM( mIncludeInRingPWM->isChecked() );
int syncprefs = rem->isChecked()*1+newest->isChecked()*2+ ask->isChecked()*3+ f_loc->isChecked()*4+ f_rem->isChecked()*5 ;//+ both->isChecked()*6 ;
prof->setSyncPrefs( syncprefs);
prof->setIsLocalFileSync( mIsLocal->isChecked() );
prof->setIsPhoneSync( mIsPhone->isChecked() );
prof->setIsPiSync( mIsPi->isChecked() );
prof->setWriteBackFuture(mWriteBackFuture->isChecked());
prof->setWriteBackFutureWeeks(mWriteBackFutureWeeks->value());
-
- prof->setWriteContactToSIM(mWriteContactToSIM->isChecked());
+ if ( mWriteContactToSIM )
+ prof->setWriteContactToSIM(mWriteContactToSIM->isChecked());
prof->setPhoneDevice( mPhoneDevice->text() );
prof->setPhoneConnection( mPhoneConnection->text() );
prof->setPhoneModel( mPhoneModel->text() );
}
}
void KSyncPrefsDialog::insertProfiles()
{
int curItem = mProfileBox->currentItem();
mProfileBox->blockSignals( true );
mProfileBox->clear();
mProfileBox->insertStringList (mSyncProfileNames );
int item = mSyncProfileNames.count() -1;
if ( curItem >= 0 && mSyncProfileNames.count() > 0 && curItem < mSyncProfileNames.count() )
mProfileBox->setCurrentItem( curItem );
else if ( item >= 0 ) {
mProfileBox->setCurrentItem( item );
}
currentSelection = -1;
if ( mSyncProfileNames.count() > 0 ) {
//qDebug(" profileChanged( mProfileBox->currentItem() ");
profileChanged( mProfileBox->currentItem() );
currentSelection = mProfileBox->currentItem();
}
mProfileBox->blockSignals( false );
}
void KSyncPrefsDialog::addProfile ( KSyncProfile* temp )
{
saveProfile();
mSyncProfiles.append( temp );
mSyncProfileNames << temp->getName();
insertProfiles();
int last = mProfileBox->count() -1;
mProfileBox->blockSignals( true );
mProfileBox->setCurrentItem( last );
mProfileBox->blockSignals( false );
profileChanged(last);
}
void KSyncPrefsDialog::newProfile()
{
addProfile ( new KSyncProfile () );
}
void KSyncPrefsDialog::cloneProfile()
{
if ( currentSelection >= 0 )
addProfile (mSyncProfiles.at(currentSelection)->clone()) ;
else
newProfile();
}
void KSyncPrefsDialog::setLocalMachineName ( const QString& name )
{
mMyMachineName->setText( name );
}
QString KSyncPrefsDialog::getLocalMachineName ( )
{
return mMyMachineName->text();
}
QStringList KSyncPrefsDialog::getSyncProfileNames()
{
return mSyncProfileNames;
}
void KSyncPrefsDialog::usrReadConfig()
{
//KConfig *config = KOGlobals::config();
KConfig config ( locateLocal( "config","ksyncprofilesrc" ) );
config.setGroup("General");
mSyncProfileNames =config.readListEntry("SyncProfileNames");
mMyMachineName->setText(config.readEntry("LocalMachineName","undefined"));
int i;
KSyncProfile* temp ;
mSyncProfiles.clear();
for ( i = 0; i < mSyncProfileNames.count();++i ) {
temp = new KSyncProfile ();
temp->setName( mSyncProfileNames[i] );
temp->readConfig( &config );
mSyncProfiles.append( temp );
}
insertProfiles();
//mMyMachineName->setText(KOPrefs::instance()->mLocalMachineName );
}
void KSyncPrefsDialog::usrWriteConfig()
{
saveProfile();
if ( currentSelection >= 0 )
profileChanged(currentSelection);
//KConfig *config = KOGlobals::config();
KConfig config ( locateLocal( "config","ksyncprofilesrc" ) );
KSyncProfile* prof = mSyncProfiles.first();
QStringList externalSyncProfileNames;
externalSyncProfileNames.append("Sharp_DTM");;
while ( prof ) {
prof->writeConfig(&config);
if ( prof->getIsPhoneSync( ) )
externalSyncProfileNames.append(prof->getName( ) );
prof = mSyncProfiles.next();
}
//KOPrefs::instance()->mSyncProfileNames = mSyncProfileNames;
//KOPrefs::instance()->mLocalMachineName = mMyMachineName->text();
config.setGroup("General");
config.writeEntry("SyncProfileNames",mSyncProfileNames);
config.writeEntry("ExternSyncProfiles",externalSyncProfileNames);
config.writeEntry("LocalMachineName",mMyMachineName->text());
config.sync();
}
void KSyncPrefsDialog::helpDevice()
{
QString hint = i18n("Insert device where\nphone is connected. E.g.:\n");
#ifdef _WIN32_
hint += "Leave empty for Irda.\n"
"com1:\n(first serial port)\n"
"usb not supported\n"
"???\n(bluetooth device address)\n";
#else
hint += "/dev/ircomm\n(Irda)\n"
"/dev/ttyS0\n(first serial port)\n"
"/dev/ttyUSB0\n(first device usb port)\n"
"???\n(bluetooth device address)\n";
#endif
KMessageBox::information(this,hint,i18n("KDE-Pim sync config"));
}
void KSyncPrefsDialog::helpModel()
{
- QString hint = i18n("Leave empty or\ninsert name of phone model:\n");
+ QString hint = i18n("Recommended: Leave empty!\n(Such that model can\nbe auto detected)\nOr insert name of model:\n");
hint += "E.g. for Nokia 6310i:\n6310i\nAlso possible:\nobex\nfor Obex connection";
KMessageBox::information(this,hint,i18n("KDE-Pim sync config"));
}
void KSyncPrefsDialog::helpConnection()
{
QString hint = i18n("Insert kind of connection,e.g.:\n");
hint += "irda | Nokia FBUS over infrared\n"
"irdaat | AT commands infrared\n(for Siemens/Sony-Erricsson)\n"
"irdaobex | set also model as obex\n"
"fbus | Nokia FBUS2 serial\n";
KMessageBox::information(this,hint,i18n("KDE-Pim sync config"));
}