branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<file_sep><h4>C/C➕➕ Repository</h4> This repository contains a few projects which were coded in C/C++. <h4>Projects:</h4> <p> <ul> <li>Functions</li> </ul> <img src= "https://github.com/thaycn/CPP/blob/main/Functions/Functions.gif" width="70%"/> <file_sep>/**************************************** Programa: Funções em C Objetivo: Apresentar 11 funções Data da criação: 23/05/21 Autor: <NAME> *****************************************/ #include <stdio.h> #include <locale.h> #include <stdlib.h> #include <math.h> #include <time.h> //1 float funcao1positivo(float valor); //2 float funcao2null(float valor); //3 float funcao3delta(float a, float b, float c); float funcao3equacao(float a, float b, float c, float raiz1, float raiz2); float funcao3null_equacao(float valor); float funcao3positivo_equacao(float valor); //4, 5, 6, 7 float funcao4maior2(float valor, float valor2); float funcao5menor2(float valor, float valor2); float funcao6maior3(float valor, float valor2, float valor3); float funcao7menor3(float valor, float valor2, float valor3); //8 int Dado(); //9 void funcao9_probabilidade(); //10 float funcao10_temperatura_celsius(float celsius, float farenheit); float funcao10_temperatura_farenheit(float celsius, float farenheit); //11 float funcao11_media1(float nota1, float nota2, float nota3); float funcao11_media2(float nota1, float nota2, float nota3); float funcao11_maior(float valor, float valor2, float valor3); float funcao11_menor(float valor, float valor2, float valor3); int main() { //VARIÁVEIS int opcao, dado, menu; float valor, valor2, valor3; float a, b, c, delta, raiz1, raiz2, resultado; float nota1, nota2, nota3, media, media2, maiorNota, menorNota; float celsius, farenheit, resultado2; //bool quit_menu = false; //APRESENTAÇÃO printf("Aluna: <NAME>\n\n"); //MENU setlocale(LC_ALL, "Portuguese"); system ("cls"); printf("****** Menu *******\n"); printf(" 1 - Exercício 1 - É positivo?\n"); printf(" 2 - Exercício 2 - É null?\n"); printf(" 3 - Exercício 3 - Delta e Equação\n"); printf(" 4 - Exercício 4 - Qual é o maior? (2 números)\n"); printf(" 5 - Exercício 5 - Qual é o menor? (2 números)\n"); printf(" 6 - Exercício 6 - Qual é o maior (3 números)\n"); printf(" 7 - Exercício 7 - Qual é o menor? (3 números)\n"); printf(" 8 - Exercício 8 - Sorteio do Dado\n"); printf(" 9 - Exercício 9 - Probabilidade do Dado\n"); printf(" 10 - Exercício 10 - Converter a temperatura de Celsius para Farenheit ou Farenheit para Celsius\n"); printf(" 11 - Exercício 11 - Média das notas\n\n"); printf("Digite a opção desejada => "); scanf("%d", &opcao); system("cls"); switch(opcao) { case 1: /*************************************** Função: Positivo ou negativo? Objetivo: descobre se um número é positivo ou negativo retornará 1 caso positivo retornará 0 caso negativo ****************************************/ printf("Você escolheu Exercício 1 - É positivo?\n"); do { printf("\nDigite um número: "); fflush(stdin); scanf("%d", &valor); resultado = funcao1positivo(valor); //printf("O número que você digitou é: ", resultado); printf("\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); case 2: /*************************************** Função: É null? Objetivo: Descobre se um número é null ****************************************/ printf("Você escolheu Exercício 2 - É null?\n"); do { printf("\nDigite um número: "); fflush(stdin); scanf("%f", &valor); resultado = funcao2null(valor); printf("\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); case 3: /*************************************** Função: Delta e Equação de segundo grau Objetivo: Receber três valores que são coeficientes de uma equação de segundo grau e retornar o valor de Delta. E calcular as raízes de uma equação. ****************************************/ fflush(stdin); printf("Você escolheu Exercício 3\n"); do { printf("\n****** Menu *******\n"); printf("1 - Cálculo do Delta\n"); printf("2 - Cálculo da Equação\n"); printf("\nAgora escolha a opção desejada: "); fflush(stdin); scanf("%d", &opcao); switch(opcao) { case 1: printf("\nVocê escolheu Delta"); printf("\nDigite o valor de a: "); fflush(stdin); scanf("%f", &a); printf("Digite o valor de b: "); fflush(stdin); scanf("%f", &b); printf("Digite o valor de c: "); fflush(stdin); scanf("%f", &c); resultado = funcao3delta(a, b, c); printf("\nO valor de delta é %.2f", resultado); break; case 2: printf("\nVocê escolheu Equação"); printf("\nDigite o valor de a: "); fflush(stdin); scanf("%f", &a); fflush(stdin); printf("Digite o valor de b: "); fflush(stdin); scanf("%f", &b); printf("Digite o valor de c: "); fflush(stdin); scanf("%f", &c); resultado = funcao3equacao(a, b, c, raiz1, raiz2); break; default: printf("\nOpção inválida, por favor tente novamente.\n\n"); return main(); } printf("\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); case 4: /*************************************** Função: Maior valor Objetivo: receber 2 números e retorna maior valor. ****************************************/ printf("Você escolheu Exercício 4 - Qual é o maior (2 números)?\n"); do { printf("Digite o primeiro número: "); fflush(stdin); scanf("%f", &valor); printf("Digite o segundo número: "); fflush(stdin); scanf("%f", &valor2); resultado = funcao4maior2(valor, valor2); printf("O maior número é %1.f.", resultado); printf("\n\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); case 5: /*************************************** Função: Menor valor Objetivo: Receber 2 números e retorna menor valor. ****************************************/ printf("Você escolheu Exercício 5 - Qual é o menor?\n"); do { printf("Digite o primeiro número: "); fflush(stdin); scanf("%f", &valor); printf("Digite o segundo número: "); fflush(stdin); scanf("%f", &valor2); resultado = funcao5menor2(valor, valor2); printf("O menor número é %1.f.", resultado); printf("\n\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); case 6: /*************************************** Função: Maior valor Objetivo: Receber 3 números e retornar maior valor. ****************************************/ printf("Você escolheu Exercício 6 - Qual é o maior (3 números)\n"); do { printf("Digite o primeiro número: "); fflush(stdin); scanf("%f", &valor); printf("Digite o segundo número: "); fflush(stdin); scanf("%f", &valor2); printf("Digite o terceiro número: "); fflush(stdin); scanf("%f", &valor3); resultado = funcao6maior3(valor, valor2, valor3); printf("O maior número é %1.f.", resultado); printf("\n\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); case 7: /*************************************** Função: Menor valor Objetivo: Receber 3 números e retornar menor valor. ****************************************/ printf("Você escolheu Exercício 7 - Qual é o menor? (3 números)\n"); do { printf("Digite o primeiro número: "); fflush(stdin); scanf("%f", &valor); printf("Digite o segundo número: "); fflush(stdin); scanf("%f", &valor2); printf("Digite o terceiro número: "); fflush(stdin); scanf("%f", &valor3); resultado = funcao7menor3(valor, valor2, valor3); printf("O menor número é %1.f.", resultado); printf("\n\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); case 8: /*************************************** Função: Dado Objetivo: e retorna, através de sorteio, um número de 1 até 6. ****************************************/ fflush(stdin); printf("Você escolheu Exercício 8 - Sorteio\n"); do { //resultado = funcao8dado(dado); //funcao8dado(); fflush(stdin); printf("O número sorteado é: %d", Dado()); fflush(stdin); printf("\n\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); case 9: /*************************************** Função: Probabilidade Objetivo: Calcular o lance de um dado 1 milhão de vezes. E contar quantas vezes cada número saiu. E mostrar em porcentagem. ****************************************/ printf("Você escolheu Exercício 9\n"); do { funcao9_probabilidade(); printf("\n\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); case 10: /*************************************** Função: Temperatura Objetivo: Calcular a conversão entre as temperaturas Celsius e Farenheit. ****************************************/ printf("Você escolheu o Exercício 10\n"); printf("Primeiramente entre com os valores da temperatura em Celsius e Farenheit e depois escolha a opção desejada: \n\n"); printf("Celsius: "); scanf("%f", &celsius); printf("Farenheit: "); scanf("%f", &farenheit); printf("\n****** Menu *******\n"); printf("1 - Entrada com Celsius\n"); printf("2 - Entrada com Farenheit\n"); printf("\nAgora escolha a opção desejada: "); fflush(stdin); scanf("%d", &opcao); switch(opcao) { case 1: resultado = funcao10_temperatura_celsius(celsius, farenheit); printf("\nO valor da temperatura em Celsius é: %.2f", resultado); break; case 2: resultado2 = funcao10_temperatura_farenheit(celsius, farenheit); printf("\nO valor da temperatura em Farenheit é: %.2f", resultado2); break; default: printf("Opção inválida, por favor tente novamente.\n\n"); return main(); } break; case 11: /*************************************** Função: Média de notas Objetivo: Calcular a média da nota de 3 provas, levando em consideração apenas as 2 notas mais altas. ****************************************/ printf("Você escolheu Exercício 11 - Média das notas\n"); do { printf("Digite a nota da primeira prova: "); fflush(stdin); scanf("%f", &nota1); printf("Digite a nota da segunda prova: "); fflush(stdin); scanf("%f", &nota2); printf("Digite a nota da terceira prova: "); fflush(stdin); scanf("%f", &nota3); media = funcao11_media1(nota1, nota2, nota3); media2 = funcao11_media2(nota1, nota2, nota3); menorNota = funcao11_menor(nota1, nota2, nota3); maiorNota = funcao11_maior(nota1, nota2, nota3); printf("A media das provas é: %.2f \n", media); printf("A menor nota é: %.2f \n", menorNota); printf("A maior nota é: %.2f \n", maiorNota); printf("A media das das provas com as duas maiores notas é: %.2f \n", media2); printf("\n\nDigite (1) para tentar outra vez ou (2) para retornar ao menu principal: "); scanf("%d", &menu); }while(menu == 1); return main(); } } // CÁLCULOS DAS FUNÇÕES float funcao1positivo(float valor) { if (valor >= 0) { printf("O número que você digitou é positivo.\n"); return 1; } else { printf("O número que você digitou não é positivo.\n"); return 0; } } float funcao2null(float valor) { if(valor == 0) { printf("O número que você digitou é nulo.\n"); return 1; } else { printf("O número que você digitou não é nulo.\n"); return 0; } } float funcao3positivo_equacao(float valor) { if (valor >= 0) { return 1; } else { return 0; } } float funcao3null_equacao(float valor) { if(valor == 0) { return 1; } else { return 0; } } float funcao3delta(float a, float b, float c) { return ((b * b) - (4 * a * c)); return a, b, c; } float funcao3equacao(float a, float b, float c, float raiz1, float raiz2){ if (funcao3null_equacao(a)) { printf("'a' deve ser diferente de zero."); } else { if (funcao3positivo_equacao(funcao3delta(a, b, c)) || funcao3null_equacao(funcao3delta(a, b, c))) { raiz1 = ((-1) * b + sqrt(funcao3delta(a, b, c))) / (2 * a); raiz2 = ((-1) * b - sqrt(funcao3delta(a, b, c))) / (2 * a); printf("Raiz 1: %.2f\nRaiz 2: %.2f", raiz1, raiz2); return raiz1, raiz2; } else { raiz1 = ((-1) * b / (2 * a) + sqrt((-1) * funcao3delta(a, b, c)) / (2 * a)); raiz2 = ((-1) * b / (2 * a) + sqrt((-1) * funcao3delta(a, b, c)) / (2 * a)); printf("Raiz 1: %.2f\nRaiz 2: %.2f", raiz1, raiz2); return raiz1, raiz2; } } } float funcao4maior2(float valor, float valor2) { if (valor >= valor2) { return valor; } else { return valor2; } } float funcao5menor2(float valor, float valor2) { if (valor <= valor2) { return valor; } else { return valor2; } } float funcao6maior3(float valor, float valor2, float valor3) { if (funcao4maior2(valor, valor2) >= valor3) { return (funcao4maior2(valor, valor2)); } else { return valor3; } } float funcao7menor3(float valor, float valor2, float valor3) { if (funcao5menor2(valor, valor2) <= valor3) { return (funcao5menor2(valor, valor2)); } else { return valor3; } } int Dado() { //return (1 + rand() % 6); return 1 + ( rand() % 6 ); } void funcao9_probabilidade() { int n1 = 0, n2 = 0, n3 = 0, n4 = 0, n5 = 0, n6 = 0, contador; for (contador = 0 ; contador < 1000000 ; contador++) switch( Dado() ) { case 1: n1++; break; case 2: n2++; break; case 3: n3++; break; case 4: n4++; break; case 5: n5++; break; case 6: n6++; } printf("O numero 1 foi sorteado: %d vezes -> %.2f%%\n", n1, (n1 / 1000000.0) * 100); printf("O numero 2 foi sorteado: %d vezes -> %.2f%%\n", n2, (n2 / 1000000.0) * 100); printf("O numero 3 foi sorteado: %d vezes -> %.2f%%\n", n3, (n3 / 1000000.0) * 100); printf("O numero 4 foi sorteado: %d vezes -> %.2f%%\n", n4, (n4 / 1000000.0) * 100); printf("O numero 5 foi sorteado: %d vezes -> %.2f%%\n", n5, (n5 / 1000000.0) * 100); printf("O numero 6 foi sorteado: %d vezes -> %.2f%%\n", n6, (n6 / 1000000.0) * 100); printf("\nTotal: %d -> %.2f\n", n1 + n2 + n3 + n4 + n5 + n6, (n1 / 1000000.0)* 100 + (n2 / 1000000.0) * 100 + (n3 / 1000000.0) * 100 + (n4 / 1000000.0) * 100 + (n5 / 1000000.0) * 100 + (n6 / 1000000.0) * 100); } float funcao10_temperatura_celsius(float celsius, float farenheit) { //return celsius = (5 * (farenheit - 32) / 9); return farenheit = ((1.8 * celsius) + 32); } float funcao10_temperatura_farenheit(float celsius, float farenheit) { //return farenheit = (9 * (celsius / 5) + 32); return farenheit = ((farenheit - 32)/1.8); } float funcao11_media1(float nota1, float nota2, float nota3) { return ((nota1 + nota2 + nota3) / 3); } float funcao11_media2(float nota1, float nota2, float nota3) { float resultado = 0; if (nota1 >= nota2) { if (nota2 >= nota3) { resultado = (nota1 + nota2) / 2; return resultado; } else { resultado = (nota1 + nota3) / 2; return resultado; } } else { if (nota3 >= nota1) { resultado = (nota2 + nota3) / 2; return resultado; } } } float funcao11_maior(float nota1, float nota2, float nota3) { if (nota1 >= nota2 & nota1 >= nota3) { return nota1; } if (nota2 >= nota1 & nota2 >= nota3) { return nota2; } else { return nota3; } } float funcao11_menor(float nota1, float nota2, float nota3) { if (nota1 <= nota2 & nota1 <= nota3) { return nota1; } if (nota2 <= nota1 & nota2 <= nota3) { return nota2; } else { return nota3; } }
977961f6d3e22158dd2d088af5690f8ebab8c1ac
[ "Markdown", "C" ]
2
Markdown
thaycn/CPP
39f28011dbb3fdeaeb7dd35b3886c58005a1daa2
6f1ab9371d1247ce47336e09faec9ff7e3d52c1d
refs/heads/master
<repo_name>Joannie/udacity-lab2<file_sep>/designs.js // Select color input // Select size input // When size is submitted by the user, call makeGrid() function makeGrid() { let height = document.getElementById('inputHeight').value; let width = document.getElementById('inputWidth').value; let tableArea = document.getElementById('pixelCanvas'); //reset the table tableArea.innerHTML = ""; //Make the grid for(let i = 0; i < height; i++){ var row = document.createElement('tr'); for (let j = 0; j < width; j++){ var cell = document.createElement('td'); row.appendChild(cell); } tableArea.appendChild(row); } tableArea.addEventListener('click', function(evt){ evt.target.style.backgroundColor = document.getElementById('colorPicker').value; }); return false; };
1ccc1dde12f2f75bdd610957e5257de9a9b5242c
[ "JavaScript" ]
1
JavaScript
Joannie/udacity-lab2
aa576cded73758ec4d6db78c77cfebe5ed3e014b
c15f818f78fe994c6ac86917fa1f8083e9d0851e
refs/heads/master
<file_sep>tags = { }<file_sep>import re import time import clr from System import Convert from System import Text playerside = None sideflip = None cstack = { } versioncheck = None def clearCache(group, x = 0, y = 0): if confirm("Reset the Autoscript Tag cache?"): global savedtags savedtags = { } notify("{} reset the global tag cache.".format(me)) if confirm("Reset the Attachment Dictionary?"): setGlobalVariable('cattach', "{ }") notify("{} reset the global attachment dictionary.".format(me)) def shuffle(group, x = 0, y = 0): global versioncheck if versioncheck == None: (url, code) = webRead('http://octgn.gamersjudgement.com/OCTGN/game.txt') if code == 200: if url == gameVersion: whisper("Your game definition is up-to-date") else: notify("{}'s game definition is out-of-date!".format(me)) if confirm("There is a new game definition available! Your version {}. Current version {}.\nClicking yes will open your browser to the location of the most recent version.".format(gameVersion, url)): openUrl('http://octgn.gamersjudgement.com/viewtopic.php?f=8&t=195') else: whisper("Newest game definition version is unavailable at the moment") versioncheck = True for card in group: if card.isFaceUp: card.isFaceUp = False group.shuffle() autoscripts = True def disable(card, x = 0, y = 0): mute() global autoscripts if autoscripts == False: autoscripts = True notify("{} enables autoscripts".format(me)) else: autoscripts = False notify("{} disables autoscripts".format(me)) savedtags = { } def getTags(card, key): mute() global savedtags if re.search(r"//", card.name) and card.Type != None and not re.search(r"Instant", card.Type) and not re.search(r"Sorcery", card.Type): if card.isAlternateImage == True: cardname = (card.name)[(card.name).find("/")+3:] else: cardname = (card.name)[:(card.name).find("/")-1] else: cardname = card.name encodedcardname = Convert.ToBase64String(Text.Encoding.UTF8.GetBytes(cardname)) if not cardname in savedtags: (fulltag, code) = webRead('http://octgn.gamersjudgement.com/tags.php?id={}'.format(encodedcardname)) if code != 200: whisper('tag database is currently unavailable.') fulltag = tags[cardname] tagdict = { } classpieces = fulltag.split('; ') for classes in classpieces: if classes != "": actionlist = classes.split('.') actiondict = { } for actionpieces in actionlist[1:]: actionname = actionpieces[:actionpieces.find("[")] actionparam = actionpieces[actionpieces.find("[")+1:actionpieces.find("]")] if actionname == 'token': if not 'autotoken' in tagdict: tagdict['autotoken'] = [ ] tokenname = actionparam[:actionparam.find(",")] if not tokenname in tagdict['autotoken']: tagdict['autotoken'].append(tokenname) if actionname == 'marker': if not 'automarker' in tagdict: tagdict['automarker'] = [ ] markername = actionparam[:actionparam.find(",")] if not markername in tagdict['automarker']: tagdict['automarker'].append(markername) if not actionname in actiondict: actiondict[actionname] = [ ] actiondict[actionname].append(actionparam) tagdict[actionlist[0]] = actiondict savedtags[cardname] = tagdict if key == 'allactivate': st = savedtags[cardname] if 'initactivate1' in st: text11 = st['initactivate1'] else: text11 = '' if 'activate1' in st: text12 = st['activate1'] else: text12 = '' if 'initactivate2' in st: text21 = st['initactivate2'] else: text21 = '' if 'activate2' in st: text22 = st['activate2'] else: text22 = '' if 'initactivate3' in st: text31 = st['initactivate3'] else: text31 = '' if 'activate3' in st: text32 = st['activate3'] else: text32 = '' if 'initactivate4' in st: text41 = st['initactivate4'] else: text41 = '' if 'activate4' in st: text42 = st['activate4'] else: text42 = '' if 'initactivate5' in st: text51 = st['initactivate5'] else: text51 = '' if 'activate5' in st: text52 = st['activate5'] else: text52 = '' return "1) {}\n --> {}\n2) {}\n --> {}\n3) {}\n --> {}\n4) {}\n --> {}\n5) {}\n --> {}".format(text11, text12, text21, text22, text31, text32, text41, text42, text51, text52) if key in savedtags[cardname]: return savedtags[cardname][key] else: return "" def submitTags(card, x = 0, y = 0): if re.search(r"//", card.name) and card.Type != None and not re.search(r"Instant", card.Type) and not re.search(r"Sorcery", card.Type): if card.isAlternateImage == True: cardname = (card.name)[(card.name).find("/")+3:] else: cardname = (card.name)[:(card.name).find("/")-1] else: cardname = card.name encodedcardname = Convert.ToBase64String(Text.Encoding.UTF8.GetBytes(cardname)) (url, code) = webRead('http://octgn.gamersjudgement.com/tags.php?id={}'.format(encodedcardname)) if code == 200: if url != "": if not confirm("Submit an edit?\n{}".format(url)): return() openUrl('http://octgn.gamersjudgement.com/submit.php?id={}'.format(encodedcardname)) else: whisper("cannot connect to online database.") def transform(card, x = 0, y = 0): mute() if re.search(r"//", card.name) and card.Type != None and not re.search(r"Instant", card.Type) and not re.search(r"Sorcery", card.Type): if re.search(r'DFC', card.Rarity): notify("{} transforms {}.".format(me, card)) else: notify("{} flips {}.".format(me, card)) card.switchImage else: if card.isFaceUp == True: notify("{} morphs {} face down.".format(me, card)) card.isFaceUp = False else: card.isFaceUp = True notify("{} morphs {} face up.".format(me, card)) ################################## #Card Functions -- Autoscripted ################################## def trigAbility(card, tagclass, pile): mute() markerdict = { } text = "" inittag = getTags(card, 'init{}'.format(tagclass)) ####aura attachment#### if tagclass == 'cast' and card.Subtype != None and re.search(r'Aura', card.Subtype): target = (card for card in table if card.targetedBy) targetcount = sum(1 for card in table if card.targetedBy) if targetcount == 1: for targetcard in target: while getGlobalVariable('cattach') == 'CHECKOUT': whisper("Global card attachment dictionary is currently in use, please wait.") return CRASH cattach = eval(getGlobalVariable('cattach')) setGlobalVariable('cattach', 'CHECKOUT') cattach[card._id] = targetcard._id targetcard.target(False) setGlobalVariable('cattach', str(cattach)) text += ", targeting {}".format(targetcard) ####init tag checking#### if 'tapped' in inittag and card.orientation == Rot90: if not confirm("{} is already tapped!\nContinue?".format(card.name)): return "BREAK" if 'untapped' in inittag and card.orientation == Rot0: if not confirm("{} is already untapped!\nContinue?".format(card.name)): return "BREAK" if 'cost' in inittag: for costtag in inittag['cost']: (cost, type) = costtag.split(', ') if cost in scriptMarkers: marker = cost else: marker = 'cost' if type == "ask": if confirm("{}'s {}: Pay additional/alternate cost?".format(card.name, cost)): markerdict[marker] = 1 text += ", paying {} cost".format(cost.title()) elif type == "num": qty = askInteger("{}'s {}: Paying how many times?".format(card.name, cost), 0) if qty == None: qty = 0 if qty != 0: markerdict[marker] = qty text += ", paying {} {} times".format(cost.title(), qty) else: qty = cardcount(card, card, type) if qty != 0: markerdict[marker] = qty if 'marker' in inittag: for markertag in inittag['marker']: (markername, qty) = markertag.split(', ') count = card.markers[counters[markername]] if count + cardcount(card, card, qty) < 0: if not confirm("Not enough {} counters to remove!\nContinue?".format(markername)): return "BREAK" ####cast moves card to table#### if tagclass == 'cast': card.moveToTable(0,0) card.markers[scriptMarkers['cast']] = 1 for markers in markerdict: card.markers[scriptMarkers[markers]] += markerdict[markers] if card.Type != None and re.search(r'Land', card.Type): text += stackResolve(card, 'resolve') cardalign() return text ####cost modifier#### if 'cost' in markerdict: trigtype = "cost{}".format(tagclass) else: trigtype = tagclass ####create the triggered copy#### if trigtype == 'cycle' or getTags(card, trigtype) != '': stackcard = table.create(card.model, 0, 0, 1) if card.isAlternateImage == True: stackcard.switchImage if re.search(r'activate', tagclass): stackcard.markers[scriptMarkers['activate']] += int(tagclass[-1]) else: stackcard.markers[scriptMarkers[tagclass]] += 1 cstack[stackcard] = card for markers in markerdict: stackcard.markers[scriptMarkers[markers]] += markerdict[markers] else: stackcard = card ####autoscripts#### if 'life' in inittag: for tag in inittag['life']: text += autolife(card, stackcard, tag) if 'token' in inittag: for tag in inittag['token']: text += autotoken(card, stackcard, tag) if 'marker' in inittag: for tag in inittag['marker']: text += automarker(card, stackcard, tag) if 'smartmarker' in inittag: for tag in inittag['smartmarker']: text += autosmartmarker(card, tag) if 'highlight' in inittag: for tag in inittag['highlight']: text += autohighlight(card, tag) if 'tapped' in inittag: for tag in inittag['tapped']: text += autotapped(card, tag) if 'untapped' in inittag: for tag in inittag['untapped']: text += autountapped(card, tag) if 'transform' in inittag: for tag in inittag['transform']: text += autotransform(card, tag) if 'moveto' in inittag: for tag in inittag['moveto']: text += automoveto(card, tag) elif pile == "table": card.moveToTable(0,0) elif pile != '': cardowner = card.owner card.moveTo(cardowner.piles[pile]) stackcard.sendToFront() cardalign() return text def stackResolve(stackcard, type): mute() text = '' if stackcard in cstack: card = cstack[stackcard] else: card = stackcard cost = getTags(stackcard, 'cost{}'.format(type)) if scriptMarkers['cost'] in stackcard.markers and cost != '': resolvetag = cost else: resolvetag = getTags(stackcard, type) if 'persist' in resolvetag: for tag in resolvetag['persist']: text += autopersist(card, stackcard, tag) if 'undying' in resolvetag: for tag in resolvetag['undying']: text += autoundying(card, stackcard, tag) if 'life' in resolvetag: for tag in resolvetag['life']: text += autolife(card, stackcard, tag) if 'token' in resolvetag: for tag in resolvetag['token']: text += autotoken(card, stackcard, tag) if 'marker' in resolvetag: for tag in resolvetag['marker']: text += automarker(card, stackcard, tag) if 'smartmarker' in resolvetag: for tag in resolvetag['smartmarker']: text += autosmartmarker(card, tag) if 'highlight' in resolvetag: for tag in resolvetag['highlight']: text += autohighlight(card, tag) if 'tapped' in resolvetag: for tag in resolvetag['tapped']: text += autotapped(card, tag) if 'untapped' in resolvetag: for tag in resolvetag['untapped']: text += autountapped(card, tag) if 'transform' in resolvetag: for tag in resolvetag['transform']: text += autotransform(card, tag) if 'moveto' in resolvetag: for tag in resolvetag['moveto']: text += automoveto(card, tag) if stackcard in cstack: del cstack[stackcard] if type == 'miracle': if card in me.hand: casttext = trigAbility(card, 'cast', 'table') text += ", casting{}".format(casttext) else: text += ", countered" if type == 'resolve' and stackcard.Type != None and not re.search(r'Instant', stackcard.Type) and not re.search(r'Sorcery', stackcard.Type): if scriptMarkers['cost'] in stackcard.markers and getTags(stackcard, 'costetb') != '': newcard = table.create(stackcard.model, 0, 0, 1) newcard.markers[scriptMarkers['etb']] += 1 newcard.markers[scriptMarkers['cost']] += stackcard.markers[scriptMarkers['cost']] cstack[newcard] = stackcard elif not scriptMarkers['cost'] in stackcard.markers and getTags(stackcard, 'etb') != '': newcard = table.create(stackcard.model, 0, 0, 1) newcard.markers[scriptMarkers['etb']] += 1 cstack[newcard] = stackcard for marker in scriptMarkers: stackcard.markers[scriptMarkers[marker]] = 0 else: stackcard.moveTo(me.Graveyard) cardalign() return text ############################ #Modifiers ############################ def attach(card, x = 0, y = 0): if autoscripts == True: stackAttach(card) else: whisper("Autoscripts must be enabled to use this feature") def stackAttach(card): mute() align = True while getGlobalVariable('cattach') == 'CHECKOUT': whisper("Global card attachment dictionary is currently in use, please wait.") return CRASH cattach = eval(getGlobalVariable('cattach')) setGlobalVariable('cattach', 'CHECKOUT') target = (card for card in table if card.targetedBy) targetcount = sum(1 for card in table if card.targetedBy) if targetcount == 0: if card._id in dict([(v, k) for k, v in cattach.iteritems()]): card2 = [k for k, v in cattach.iteritems() if v == card._id] for card3 in card2: del cattach[card3] notify("{} unattaches {} from {}.".format(me, Card(card3), card)) elif card._id in cattach: card2 = cattach[card._id] del cattach[card._id] notify("{} unattaches {} from {}.".format(me, card, Card(card2))) else: align = False elif targetcount == 1: for targetcard in target: if card == targetcard: del cattach[card._id] notify("{} unattaches {} from {}.".format(me, card, targetcard)) else: cattach[card._id] = targetcard._id targetcard.target(False) notify("{} attaches {} to {}.".format(me, card, targetcard)) else: whisper("Incorrect targets, select only 1 target.") align = False setGlobalVariable('cattach', str(cattach)) if align == True: cardalign() def align(group, x = 0, y = 0): mute() if autoscripts == True: if cardalign() != "BREAK": notify("{} re-aligns his cards on the table".format(me)) def cardalign(): mute() global playerside global sideflip if sideflip == 0: return "BREAK" if Table.isTwoSided(): if playerside == None: if me.hasInvertedTable(): playerside = -1 else: playerside = 1 if sideflip == None: playersort = sorted(players, key=lambda player: player._id) playercount = [p for p in playersort if me.hasInvertedTable() == p.hasInvertedTable()] if len(playercount) > 2: whisper("Cannot align: Too many players on your side of the table.") sideflip = 0 return "BREAK" if playercount[0] == me: sideflip = 1 else: sideflip = -1 else: whisper("Cannot align: Two-sided table is required for card alignment.") sideflip = 0 return "BREAK" while getGlobalVariable('cattach') == 'CHECKOUT': whisper("Global card attachment dictionary is currently in use, please wait.") return "BREAK" cattach = eval(getGlobalVariable('cattach')) setGlobalVariable('cattach', 'CHECKOUT') not in table group1 = [cardid for cardid in cattach if Card(cattach[cardid]) not in table] for cardid in group1: if Card(cardid).Subtype != None and re.search(r'Aura', Card(cardid).Subtype) and Card(cardid).controller == me: Card(cardid).moveTo(me.Graveyard) notify("{}'s {} was destroyed".format(me, Card(cardid))) del cattach[cardid] group2 = [cardid for cardid in cattach if Card(cardid) not in table] for cardid in group2: del cattach[cardid] setGlobalVariable('cattach', str(cattach)) stackcount = 0 stackcards = (card for card in table if scriptMarkers['cast'] in card.markers or scriptMarkers['activate'] in card.markers or scriptMarkers['attack'] in card.markers or scriptMarkers['block'] in card.markers or scriptMarkers['destroy'] in card.markers or scriptMarkers['exile'] in card.markers or scriptMarkers['etb'] in card.markers or scriptMarkers['cost'] in card.markers or scriptMarkers['x'] in card.markers or scriptMarkers['cycle'] in card.markers or scriptMarkers['miracle'] in card.markers) for card in stackcards: if card.controller == me: card.moveToTable(0, 0 + 10 * stackcount) stackcount += 1 cardorder = [ ] carddict = { } landorder = [ ] landdict = { } tablecards = [card for card in table if card.controller == me and not scriptMarkers['cast'] in card.markers and not scriptMarkers['activate'] in card.markers and not scriptMarkers['attack'] in card.markers and not scriptMarkers['block'] in card.markers and not scriptMarkers['destroy'] in card.markers and not scriptMarkers['exile'] in card.markers and not scriptMarkers['etb'] in card.markers and not scriptMarkers['cost'] in card.markers and not scriptMarkers['x'] in card.markers and not scriptMarkers['cycle'] in card.markers and not scriptMarkers['miracle'] in card.markers and not counters['general'] in card.markers and not card._id in cattach] cardsort = sorted(tablecards, key=lambda card:(sortlist(card), card.name)) for card in cardsort: if re.search(r'Land', card.Type) or re.search(r'Planeswalker', card.Type) or re.search(r'Emblem', card.Type): vardict = landdict varorder = landorder yshift = 170 else: vardict = carddict varorder = cardorder yshift = 45 if len(card.markers) == 0 and not card._id in dict([(v, k) for k, v in cattach.iteritems()]): if not card.name in vardict or vardict[card.name] == 0: vardict[card.name] = 1 varorder.append(card.name) xpos = len(varorder) ypos = 1 elif vardict[card.name] >= 3: vardict[card.name] = 0 xpos = varorder.index(card.name) + 1 varorder[varorder.index(card.name)] = ['BLANK'] ypos = 4 else: vardict[card.name] += 1 xpos = varorder.index(card.name) + 1 ypos = vardict[card.name] else: varorder.append('BLANK') xpos = len(varorder) ypos = 4 card.moveToTable(sideflip * xpos * 80, playerside * yshift - 44 + playerside * 9 * ypos) cattachcount = { } attachcardsgroup = [card for card in table if card.controller == me and not scriptMarkers['cast'] in card.markers and not scriptMarkers['activate'] in card.markers and not scriptMarkers['attack'] in card.markers and not scriptMarkers['block'] in card.markers and not scriptMarkers['destroy'] in card.markers and not scriptMarkers['exile'] in card.markers and not scriptMarkers['etb'] in card.markers and not scriptMarkers['cost'] in card.markers and not scriptMarkers['x'] in card.markers and not scriptMarkers['cycle'] in card.markers and not scriptMarkers['miracle'] in card.markers and not counters['general'] in card.markers and card._id in cattach] attachcards= sorted(attachcardsgroup, key=lambda card: card.name) for card in attachcards: origc = cattach[card._id] (x, y) = Card(origc).position if playerside*y < 0: yyy = -1 else: yyy = 1 if not Card(origc) in cattachcount: cattachcount[Card(origc)] = 1 card.moveToTable(x, y - yyy*playerside*9) card.sendToBack() else: cattachcount[Card(origc)] += 1 card.moveToTable(x, y - yyy*playerside*cattachcount[Card(origc)]*9) card.sendToBack() def sortlist(card): if re.search(r"Land", card.Type): return "A" elif re.search(r"Planeswalker", card.Type): return "B" elif re.search(r"Emblem", card.Type): return "C" elif re.search(r"Creature", card.Type): return "D" elif re.search(r"Artifact", card.Type): return "E" elif re.search(r"Enchantment", card.Type): return "F" else: return "G" def cardcount(card, stackcard, search): multiplier = 1 if re.search(r'-', search): search = search.replace('-', '') multiplier = multiplier * (0 - 1) if re.search(r'\*', search): intval = int(search[:search.find("*")]) search = search[search.find("*")+1:] multiplier = multiplier * intval if search == "x": qty = stackcard.markers[scriptMarkers['x']] card.markers[scriptMarkers['x']] -= qty elif search == "cost": qty = stackcard.markers[scriptMarkers['cost']] card.markers[scriptMarkers['cost']] -= qty elif re.search(r'marker', search): marker = search[search.find("marker")+7:] addmarker = counters[marker] qty = card.markers[addmarker] elif search == "ask": qty = askInteger("What is X?", 0) if qty == None: qty = 0 else: qty = int(search) return qty * multiplier ############################ #Autoscript ############################ def autopersist(card, stackcard, persist): if card.group.name == "Graveyard": card.moveToTable(0,0) stackResolve(card, 'resolve') card.markers[counters['minusoneminusone']] += 1 return ", persisting" else: return "" def autoundying(card, stackcard, undying): if card.group.name == "Graveyard": card.moveToTable(0,0) stackResolve(card, 'resolve') card.markers[counters['plusoneplusone']] += 1 return ", undying" else: return "" def automoveto(card, pile): rnd(100,1000) cardowner = card.owner cards = card position = re.sub("[^0-9]", "", pile) if position != "": pos = int(position) cards.moveTo(cardowner.Library, pos) text = "{} from top of library".format(pos) if re.search(r'top', pile): cards.moveTo(cardowner.Library) text = "top of library" elif re.search(r'bottom', pile): cards.moveToBottom(cardowner.Library) text = "bottom of library" elif re.search(r'shuffle', pile): librarycount = len(cardowner.Library) n = rnd(0, librarycount) cards.moveTo(cardowner.Library, n) cardowner.Library.shuffle() text = "library and shuffled" elif re.search(r'exile', pile): if trigAbility(card, 'exile', 'Exiled Zone') != "BREAK": text = "exile" elif re.search(r'hand', pile): cards.moveTo(cardowner.hand) text = "hand" elif re.search(r'graveyard', pile): if trigAbility(card, 'destroy', 'Graveyard') != "BREAK": text = "graveyard" elif re.search(r'stack', pile): if trigAbility(card, 'cast', 'table') != "BREAK": text = "stack" elif re.search(r'table', pile): card.moveToTable(0,0) stackResolve(card, 'resolve') text = "table" return ", moving to {}".format(text) def autolife(card, stackcard, tag): qty = cardcount(card, stackcard, tag) me.Life += qty if qty >= 0: return ", {} life".format(qty) else: return ", {} life".format(qty) def autotransform(card, tag): if tag == "no": return "" if tag == "ask": if not confirm("Transform {}?".format(card.name)): return "" card.switchImage return ", transforming to {}".format(card) def autotoken(card, stackcard, tag): tag2 = tag.split(', ') name = tag2[0] qty = tag2[1] if len(tag2) > 2: modifiers = tag2[2:] else: modifiers = "" quantity = cardcount(card, stackcard, qty) if quantity == 1: quant = "" else: quant = "s" if quantity != 0: addtoken = tokenTypes[name] tokens = table.create(addtoken[1], 0, 0, quantity, persist = False) if quantity == 1: tokens = [tokens] for token in tokens: for modtag in modifiers: if modtag == 'attack': token.highlight = AttackColor elif modtag == 'tap': token.orientation = Rot90 elif re.search(r'marker', modtag): (marker, type, quant) = modtag.split('_') token.markers[counters[type]] += cardcount(token, stackcard, qty) tokentext = "{} {}/{} {} {}".format(quantity, token.Power, token.Toughness, token.Color, token.name) cardalign() return ", creating {} token{}".format(tokentext, quant) else: return "" def automarker(card, stackcard, tag): (markername, qty) = tag.split(', ') quantity = cardcount(card, stackcard, qty) originalquantity = quantity if quantity == 1: quant = "" else: quant = "s" addmarker = counters[markername] while markername == "plusoneplusone" and counters["minusoneminusone"] in card.markers and quantity > 0: card.markers[counters["minusoneminusone"]] -= 1 quantity -= 1 while markername == "minusoneminusone" and counters["plusoneplusone"] in card.markers and quantity > 0: card.markers[counters["plusoneplusone"]] -= 1 quantity -= 1 card.markers[addmarker] += quantity if originalquantity > 0: sign = "+" else: sign = "" return ", {}{} {}{}".format(sign, originalquantity, addmarker[0], quant) def autohighlight(card, color): if color == "nountap": if card.highlight == AttackColor: card.highlight = AttackDoesntUntapColor elif card.highlight == BlockColor: card.highlight = BlockDoesntUntapColor else: card.highlight = DoesntUntapColor text = "does not untap" elif color == "attack": if card.highlight == DoesntUntapColor: card.highlight = AttackDoesntUntapColor else: card.highlight = AttackColor text = "attacking" elif color == "block": if card.highlight == DoesntUntapColor: card.highlight = BlockDoesntUntapColor else: card.highlight = BlockColor text = "blocking" else: text = "" return ", {}".format(text) def autotapped(card, tapped): card.orientation = Rot90 return ", tapped" def autountapped(card, untapped): card.orientation = Rot0 return ", untapped" def autosmartmarker(card, marker): if marker in counters: setGlobalVariable("smartmarker", marker) notify("{} sets the Smart Counter to {}.".format(me, counters[marker][0])) return "" ############################ #Smart Token/Markers ############################ def autoCreateToken(card, x = 0, y = 0): mute() text = "" tokens = getTags(card, 'autotoken') if tokens != "": for token in tokens: addtoken = tokenTypes[token] tokencard = table.create(addtoken[1], x, y, 1, persist = False) x, y = table.offset(x, y) text += "{}/{} {} {}, ".format(tokencard.Power, tokencard.Toughness, tokencard.Color, tokencard.name) if autoscripts == True: cardalign() notify("{} creates {}.".format(me, text[0:-2])) def autoAddMarker(card, x = 0, y = 0): mute() text = "" markers = getTags(card, 'automarker') if markers != "": for marker in markers: addmarker = counters[marker] if marker == "minusoneminusone" and counters["plusoneplusone"] in card.markers: card.markers[counters["plusoneplusone"]] -= 1 elif marker == "plusoneplusone" and counters["minusoneminusone"] in card.markers: card.markers[counters["minusoneminusone"]] -= 1 else: card.markers[addmarker] += 1 text += "one {}, ".format(addmarker[0]) notify("{} adds {} to {}.".format(me, text[0:-2], card)) def smartMarker(card, x = 0, y = 0): mute() marker = getGlobalVariable("smartmarker") if marker == "": whisper("No counters available") return if marker == "minusoneminusone" and counters["plusoneplusone"] in card.markers: card.markers[counters["plusoneplusone"]] -= 1 notify("{} adds one -1/-1 counter to {}.".format(me, card)) elif marker == "plusoneplusone" and counters["minusoneminusone"] in card.markers: card.markers[counters["minusoneminusone"]] -= 1 notify("{} adds one -1/-1 counter to {}.".format(me, card)) else: addmarker = counters[marker] card.markers[addmarker] += 1 notify("{} adds one {} to {}.".format(me, addmarker[0], card))
136270f9c292c99ce8266154b9abf860b6688602
[ "Python" ]
2
Python
drilus/mtg-octgn
01522a7f33056a564ffc30c11c82c9a3892bd586
276864841ac3d6cf8388b0917c77f969273edd71
refs/heads/master
<repo_name>indywu/cc<file_sep>/cc.py #!/usr/bin/python # -*- coding: utf-8 -*- """USAGE: """ __version__ = 0.03 __author__ = "<NAME>" """ Naechste Schritte: in Webseite mit iframe einbinden """ def teilen(a, b): if a == 0: a = 1 ergebnis4 = (1.0*a)/b return ergebnis4 """ print("Hallo Welt") print("Bitte geben Sie die Gitterkonstanten ein") a = input("a=") b = input("b=") c = input("c=") print("Bitte geben Sie die Vervielfachung der Gitterkonstanten ein") d = input("a=a*") e = input("b=b*") f = input("c=c*") ergebnis = a * d ergebnis2 = b * e ergebnis3 = c * f print("a= {0:.4f} b= {1:.4f} b= {2:.4f}".format(ergebnis, ergebnis2, ergebnis3) ) print("Bitte geben Sie die Positionen der Atome ein.") print("Erstes Atom:") x1 = input("x=") y1 = input("y=") z1 = input("z=")""" print("{0:.4f}".format(teilen(0, 3)))
4f51bd6df7a915ff9256ddaf4f698b1f8ac028cc
[ "Python" ]
1
Python
indywu/cc
aca33815fcd40b32d820c2ed5b8ed9c0c7de950c
ca0ab8c03e446fd08cc9fe322e2acd0ccfd6f3e4
refs/heads/master
<repo_name>evanhackett/evanhackett.github.io<file_sep>/todo.txt fix star animation not being centered on mobile. fix line not wrapping on mobile.<file_sep>/index.js const socialIcons = [ { dom: document.getElementById("octocat"), description: "Github - see my code and open source activity" }, { dom: document.getElementById("blog"), description: "Blog - I write about all things software development" }, { dom: document.getElementById("twitter"), description: "twitter - I might tweet more if I had more followers!" }, { dom: document.getElementById("linkedin"), description: "LinkedIn - I heard you're supposed to have one of these..." }, ] function accelerate() { for (let i = 0; i < 80; i++) { setTimeout(() => speed += 0.5, 50 * i) } } function decelerate() { for (let i = 0; i < 80; i++) { setTimeout(() => speed -= 0.5, 50 * i) } } const workExperience = document.getElementById('work-exp') socialIcons.forEach(item => { // set up on hover handlers for link images. const linkDescription = document.getElementById("link-description") let intervalId; item.dom.onmouseover = () => { // On hover will cause text to appear that explains what the link is. linkDescription.innerHTML = item.description // It will also speed up the star animation. accelerate() // lastly it will fade out the work experience section text workExperience.classList.add('fade-out') workExperience.classList.remove('fade-in') } item.dom.onmouseout = () => { linkDescription.innerHTML = '' decelerate() workExperience.classList.remove('fade-out') workExperience.classList.add('fade-in') } }) <file_sep>/README.md This is my homepage. See it live at [evanhackett.com](https://evanhackett.com/)
4b135fa7f18f7b745a4ec355899fab29304cdee3
[ "JavaScript", "Text", "Markdown" ]
3
Text
evanhackett/evanhackett.github.io
20e2c11f70f200e81a583b871d889d66c6ae84f8
a8608d6f9f1d1eff3feafe4dd596a07de54c9899
refs/heads/master
<repo_name>Safal08/SIMS<file_sep>/app/src/main/java/com/example/naruto/sims/Login.java package com.example.naruto.sims; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class Login extends AppCompatActivity implements View.OnClickListener{ EditText email,password; Button btnlogin, btnregister; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); getSupportActionBar().setTitle("Login"); btnlogin=(Button) findViewById(R.id.btn_login); btnregister=(Button) findViewById(R.id.btn_register); btnregister.setOnClickListener(this); btnlogin.setOnClickListener(this); email = findViewById(R.id.email); password = findViewById(R.id.pwd); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_login : break; case R.id.btn_register: break; } } }
387c02870302896cd7da34cd82e992b069bedb9f
[ "Java" ]
1
Java
Safal08/SIMS
c97233b360d200cf2fb9ed2a5d130fd990c93270
15b6a7e8e00fb2f5ef2443437d53768b0a350b2e
refs/heads/master
<repo_name>Nick-Howlett/Lantgon-s-Ant<file_sep>/ant.py class Board: def __init__(self): self.board = [[False for i in range(11)] for j in range(11)] self.ant = Ant() def place_ant(self): self.board[self.ant.pos[0]][self.ant.pos[1]] = 'A' def take_turn(self): if self.board[self.ant.pos[0]][self.ant.pos[1]]: self.ant.turn(-1) else: self.ant.turn(1) self.board[self.ant.pos[0]][self.ant.pos[1]] = not self.board[self.ant.pos[0]][self.ant.pos[1]] self.ant.move() def print(self): for row in self.board: print("|".join(["B" if el else "W" for el in row])) class Ant: def __init__(self): self.pos = [5, 5] self.current_dir = 0 self.direcs = [[0, 1], [1, 0], [0, -1], [-1, 0]] def move(self): self.pos = [x + y for x, y in zip(self.pos, self.direcs[self.current_dir])] return self.pos def turn(self, turn): self.current_dir += turn self.current_dir %= 4 board = Board() for i in range(100): board.print() board.take_turn()
bd178006438bfbdc91df666e366a9ad981956024
[ "Python" ]
1
Python
Nick-Howlett/Lantgon-s-Ant
f6e561bff9ce7c21aea44e96dcc11baec533e09f
7ac32ff2db427adaa397cc4a974099e8ae95e52a
refs/heads/master
<file_sep><?php require_once "RequestResultBase.php"; require_once "AdBlock.php"; /** * This class represents the result of a GetAdvertisement query. * * @package prediggo4php * @subpackage types * * @author Stef */ class GetAdvertisementResult extends RequestResultBase { protected $pageId; protected $pageName; protected $blocks = array(); /** * Returns the page ID submitted in the request */ public function getPageId() { return $this->pageId; } public function setPageId( $pageId) { $this->pageId = $pageId; } /** * The page name as configured in the backoffice * @return */ public function getPageName() { return $this->pageName; } public function setPageName($pageName) { $this->pageName = $pageName; } /** * Returns the list of blocks in the page * @return array[AdBlock] */ public function getBlocks() { return $this->blocks; } /** * @param $block */ public function addBlock($block) { $this->blocks[] = $block; } /** * Retrieves a block object from the result based on its ID * * @param int $blockId the ID of the block * @return AdBlock The block with specified ID, null if not found */ public function blockById($blockId) { foreach ( $this->blocks as $block) { if( $block->getBlockId() == $blockId ) { return $block; } } return null; } /** * Returns a list of Ads for the given blockId, this is a null safe alternative to blockById(blockID).getAds() * @param $blockId The block id * @return array[AdResult] the list of ads, or an empty list if block ID is not found */ public function adsByBlock($blockId) { $requestedBlock = $this->blockById($blockId); if($requestedBlock === null) { return array(); } return $requestedBlock->getAds(); } } <file_sep><?php header("Pragma: no-cache"); header("Expires: 0"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Content-type: application/xml"); $PS_ROOT_DIR=$_POST['PS_ROOT_DIR']; $id_product_attribute=$_POST['id_product_attribute']; $id_product=$_POST['id_product']; $ean13=$_POST['ean13']; $retour=''; $id_to_refresh=''; $ligne=''; if ($id_product_attribute=='NULL' or $id_product_attribute=='0') { $ligne=$id_product.'-0'; } else { $ligne=$id_product.'-'.$id_product_attribute; } require($PS_ROOT_DIR.'/config/config.inc.php'); $query='select count(ean13) as nombre from ( select '._DB_PREFIX_.'product.id_product, if (ISNULL('._DB_PREFIX_.'product_attribute.id_product_attribute),0,'._DB_PREFIX_.'product_attribute.id_product_attribute) as id_product_attribute, if(ISNULL('._DB_PREFIX_.'product_attribute.id_product_attribute),'._DB_PREFIX_.'product.ean13,'._DB_PREFIX_.'product_attribute.ean13) as ean13 from '._DB_PREFIX_.'product LEFT OUTER JOIN '._DB_PREFIX_.'product_attribute ON ('._DB_PREFIX_.'product.id_product='._DB_PREFIX_.'product_attribute.id_product) ) tmp_ean13 where ean13=\''.$ean13.'\''; $result = Db::getInstance()->ExecuteS($query); foreach ($result as $row){ $nombre=$row['nombre']; } if ($nombre<>'0') { //echo 'duplicate'; echo 'erreur:3'.'|'.$ligne; } else { if(test_ean13($ean13)<>0){ $erreur=test_ean13($ean13); $retour='erreur:'.$erreur.'|'.$ligne; } else { if ($id_product_attribute=='NULL' or $id_product_attribute=='0'){ $sql='UPDATE '._DB_PREFIX_.'product SET ean13 = \''.$ean13.'\' WHERE '._DB_PREFIX_.'product.id_product ='.$id_product; } else { $sql='UPDATE '._DB_PREFIX_.'product_attribute SET ean13 = \''.$ean13.'\' WHERE '._DB_PREFIX_.'product_attribute.id_product_attribute ='.$id_product_attribute; $id_to_refresh=$id_product_attribute; } $result = Db::getInstance()->Execute($sql); $retour=$ean13.'|'.$ligne; } } $query_recup_ean13_before='select ean13 from ( select '._DB_PREFIX_.'product.id_product, if (ISNULL('._DB_PREFIX_.'product_attribute.id_product_attribute),0,'._DB_PREFIX_.'product_attribute.id_product_attribute) as id_product_attribute, if(ISNULL('._DB_PREFIX_.'product_attribute.id_product_attribute),'._DB_PREFIX_.'product.ean13,'._DB_PREFIX_.'product_attribute.ean13) as ean13 from '._DB_PREFIX_.'product LEFT OUTER JOIN '._DB_PREFIX_.'product_attribute ON ('._DB_PREFIX_.'product.id_product='._DB_PREFIX_.'product_attribute.id_product) ) tmp_ean13 where id_product_attribute='.$id_product_attribute.' and id_product='.$id_product; $result_ean13_before = Db::getInstance()->ExecuteS($query_recup_ean13_before); foreach ($result_ean13_before as $row_ean13_before){ $ean13_before=$row_ean13_before['ean13']; } echo $retour.'|'.$ean13_before; function test_ean13($ean13){ if(strlen($ean13)<>13) { //echo 'longueur='.strlen($ean13); return 1; //return 'pb_longueur'; } $bit_ctrl=calc_bit_ctrl(substr($ean13,0,-1)); //function de test a reprendre ici test si le bit de controle est ok if($ean13<>substr($ean13,0,-1).$bit_ctrl){ //echo 'pb_ctr'; return 2; //return 'pb_bit_control'; } //si ok return 0 return 0; } function calc_bit_ctrl($code_ean) { $ctrl_key=0; $len_ch= strlen($code_ean); $i=0; while($i<$len_ch) { $etape = $len_ch - $i; $tab[$i] = substr($code_ean, -$etape,1); $i++; } foreach ($tab as $key => $value){ if (($key+1)%2==0){ $ctrl_key=$ctrl_key+$value*3; } else { $ctrl_key=$ctrl_key+$value; } } $ctrl_key=$ctrl_key%10; //echo '<BR>'.$ctrl_key.'<BR>'; if ($ctrl_key==0) { return $ctrl_key; } else { return 10-$ctrl_key; } } ?><file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class PowaTagLogs extends ObjectModel { const IN_PROGRESS = 'in progress'; const SUCCESS = 'success'; const WARNING = 'warning'; const ERROR = 'error'; public $subject; public $status; public $message; public $date_add; public $date_upd; public static $definition = array( 'table' => 'powatag_logs', 'primary' => 'id_powatag_logs', 'multilang' => false, 'fields' => array( 'subject' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), 'status' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), 'message' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), 'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat'), 'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat'), ), ); public static function getIds() { $sql = 'SELECT `'.self::$definition['primary'].'` FROM '._DB_PREFIX_.self::$definition['table'].''; $objsIDs = Db::getInstance()->ExecuteS($sql); return $objsIDs; } public static function install() { // Create Category Table in Database $sql = array(); $sql[] = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.self::$definition['table'].'` ( `'.self::$definition['primary'].'` int(16) NOT NULL AUTO_INCREMENT, `subject` VARCHAR(255) NOT NULL, `status` VARCHAR(255) NOT NULL, `message` VARCHAR(255) NOT NULL, date_add DATETIME NOT NULL, date_upd DATETIME NOT NULL, UNIQUE(`'.self::$definition['primary'].'`), PRIMARY KEY ('.self::$definition['primary'].') ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8;'; foreach ($sql as $q) { Db::getInstance()->Execute($q); } } public static function uninstall() { // Create Category Table in Database $sql = array(); $sql[] = 'DROP TABLE IF EXISTS `'._DB_PREFIX_.self::$definition['table'].'`'; foreach ($sql as $q) { Db::getInstance()->Execute($q); } } public static function initLog($subject, $message, $api = false, $status = false) { if ($api && Configuration::get('POWATAG_API_LOG')) { $log = new self(); $log->subject = $subject; $log->message = $message; $log->status = $status; return $log->save(); } elseif (Configuration::get('POWATAG_REQUEST_LOG')) { $module = Module::getInstanceByName('powatag'); $handle = fopen($module->getLocalPath().'error.txt', 'a+'); fwrite($handle, '['.strftime('%Y-%m-%d %H:%M:%S').'] '.$subject.' : '.print_r($message, true)); fclose($handle); } } public static function initAPILog($subject, $status, $message) { return self::initLog($subject, $message, true, $status); } public static function initRequestLog($subject, $message) { return self::initLog($subject, $message); } } <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.inc.php'; //require_once '/home/jara/ejp/80-powa/15-presta/prestashop/config/config.inc.php'; require_once _PS_ROOT_DIR_.DIRECTORY_SEPARATOR.'init.php'; require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'PowaTagAPI.php'; class PowaTagAPIHandle { public static function init() { if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) { $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME']; } try { $request = null; if (array_key_exists('request', $_GET) && !empty($_GET['request'])) { $request = Tools::getValue('request'); } $api = new PowaTagAPI($request, $_SERVER['HTTP_ORIGIN']); $content = $api->processAPI(); } catch (Exception $e) { $content = Tools::jsonEncode(array( 'code' => '500101', 'errorMessage' => $e->getMessage(), )); } return $content; } } echo PowaTagAPIHandle::init(); <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionOfferDataManager', false)) return; class ProductAuctionOfferDataManager { /** * * @param ProductAuction $product_auction * @return ProductAuctionOffer[] */ public static function getCollectionByProductAuction(ProductAuction $product_auction, $product_auction_offer_status = null, $language_id = null) { $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); if (empty($product_auction_offer_status)) $product_auction_offer_status = array( ProductAuctionOffer::STATUS_VALID, ProductAuctionOffer::STATUS_WINNER ); $query = ' SELECT '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction_offer` pao LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE pao.id_product_auction = '.(int)$product_auction->id.' AND pao.status IN ('.implode(',', $product_auction_offer_status).') ORDER BY pao.customer_price DESC '; $result = Db::getInstance()->executeS($query); $product_auction_offer_collection = array(); if (!empty($result)) { $classes = array( 'ProductAuctionOffer', 'Customer' ); $result = CoreModuleTools::hydrateCollection($classes, $result, $language_id); foreach ($result['ProductAuctionOffer'] as $product_auction_offer) { $product_auction_offer->setProductAuction($product_auction); if (isset($result['Customer'][$product_auction_offer->id_customer])) $product_auction_offer->setCustomer($result['Customer'][$product_auction_offer->id_customer]); $product_auction_offer_collection[] = $product_auction_offer; } } return $product_auction_offer_collection; } /** * * @param Product $product * @return ProductAuction */ public static function getCollectionByProductAuctionsAndCustomer($product_auction_collection, $product_auction_offer_status = null, $customer_id, $language_id = null) { if (empty($product_auction_collection)) return array(); if (empty($product_auction_offer_status)) $product_auction_offer_status = array( ProductAuctionOffer::STATUS_VALID, ProductAuctionOffer::STATUS_WINNER ); $product_auction_ids = array(); foreach ($product_auction_collection as $product_auction) $product_auction_ids[] = (int)$product_auction->id; $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $query = ' SELECT '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction_offer` pao LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) JOIN ( SELECT id_product_auction, MAX(customer_price) as customer_price FROM `'._DB_PREFIX_.'product_auction_offer` WHERE id_product_auction IN ('.implode(',', $product_auction_ids).') AND id_customer = '.(int)$customer_id.' AND status IN ('.implode(',', $product_auction_offer_status).') GROUP BY id_product_auction ) cpao ON (pao.id_product_auction = cpao.id_product_auction AND pao.customer_price = cpao.customer_price) WHERE pao.id_product_auction IN ('.implode(',', $product_auction_ids).') AND pao.id_customer = '.(int)$customer_id.' AND pao.status IN ('.implode(',', $product_auction_offer_status).') '; $result = Db::getInstance()->executeS($query); $product_auction_offer_collection = array(); if (!empty($result)) { $classes = array( 'ProductAuctionOffer', 'Customer' ); $result = CoreModuleTools::hydrateCollection($classes, $result, $language_id); foreach ($result['ProductAuctionOffer'] as $product_auction_offer) { if (isset($result['Customer'][$product_auction_offer->id_customer])) $product_auction_offer->setCustomer($result['Customer'][$product_auction_offer->id_customer]); $product_auction_offer_collection[$product_auction_offer->id_product_auction] = $product_auction_offer; } } return $product_auction_offer_collection; } /** * * @param ProductAuction $product_auction */ public static function clearOffersForProductAuction(ProductAuction $product_auction) { return Db::getInstance()->execute(' DELETE FROM `'._DB_PREFIX_.ProductAuctionOffer::$definition['table'].'` WHERE `id_product_auction` = '.(int)$product_auction->id); } /** * * @param ProductAuction $product_auction * @return ProductAuctionOffer */ public static function getWinnerForProductAuction(ProductAuction $product_auction, $language_id = null, $shop_id = null) { $product_auction_offer = null; $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $query = ' SELECT '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction_offer` pao LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE pao.id_product_auction = '.(int)$product_auction->id.' AND pao.status IN ('.ProductAuctionOffer::STATUS_VALID.', '.ProductAuctionOffer::STATUS_WINNER.') ORDER BY pao.customer_price DESC, pao.date_add ASC LIMIT 1 '; $result = Db::getInstance()->executeS($query); if (!empty($result)) { $product_auction_offer = new ProductAuctionOffer(null, true, $language_id, $shop_id); CoreModuleTools::hydrateObject($product_auction_offer, $result, $language_id); $product_auction_offer->setProductAuction($product_auction); CoreModuleTools::hydrateObject($product_auction_offer->customer, $result, $language_id); } return $product_auction_offer; } /** * * @param ProductAuction $product_auction */ public static function retireWinnerForProductAuction($product_auction_id) { return Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.ProductAuctionOffer::$definition['table'].'` SET status = '.ProductAuctionOffer::STATUS_RETIRED.' WHERE `id_product_auction` = '.(int)$product_auction_id.' AND `status` = '.ProductAuctionOffer::STATUS_WINNER); } /** * * @param ProductAuction $product_auction * @return Customers[] */ public static function getParticipantsCustomersCollectionByProductAuction(ProductAuction $product_auction, $product_auction_offer_status = null, $language_id = null) { $customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); if (empty($product_auction_offer_status)) $product_auction_offer_status = array( ProductAuctionOffer::STATUS_VALID, ProductAuctionOffer::STATUS_WINNER ); $query = ' SELECT DISTINCT '.implode(', ', $customer_fields).' FROM `'._DB_PREFIX_.'customer` c INNER JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (c.id_customer = pao.id_customer) WHERE pao.id_product_auction = '.(int)$product_auction->id.' AND pao.status IN ('.implode(',', $product_auction_offer_status).') ORDER BY pao.customer_price DESC '; $result = Db::getInstance()->executeS($query); $customer_collection = array(); if (!empty($result)) { $classes = array( 'Customer' ); $result = CoreModuleTools::hydrateCollection($classes, $result, $language_id); foreach ($result['Customer'] as $customer) $customer_collection[] = $customer; } return $customer_collection; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsMyAuctionsController', false)) return; class AuctionsMyAuctionsController extends CoreModuleController { public $mybids_count; public $mypayment_count; public $myhistory_count; public $mywatching_count; public function setMedia() { parent::setMedia(); $this->addCSS($this->module->getPathUri().'css/myauctions.css', 'all'); $this->addJS($this->module->getPathUri().'js/myauctions.js'); } public function process() { parent::process(); if ($this->context->customer->isLogged()) { $show_my_bids = true; $show_my_payment = true; $show_my_history = true; $show_watching = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_WATCH_AUCTION); $customer_id = $this->context->customer->id; $shop_id = $this->context->shop->id; $this->mybids_count = $show_my_bids ? ProductAuctionDataManager::getCurrentAuctionsCountByCustomer($customer_id, $shop_id) : null; $this->mypayment_count = $show_my_payment ? ProductAuctionDataManager::getWonAuctionsCountByCustomer($customer_id, $shop_id) : null; $this->myhistory_count = $show_my_history ? ProductAuctionDataManager::getClosedAuctionsCountByCustomer($customer_id, $shop_id) : null; $this->mywatching_count = $show_watching ? ProductAuctionDataManager::getWatchingAuctionsCountByCustomer($customer_id, $shop_id) : null; $appearance_settings = $this->module->getSettings('AuctionsAppearanceSettings'); $this->context->smarty->assign(array( 'mybids_count' => $this->mybids_count, 'mypayment_count' => $this->mypayment_count, 'myhistory_count' => $this->myhistory_count, 'mywatching_count' => $this->mywatching_count, 'my_permissions' => array( 'show_mybids' => $show_my_bids, 'show_mypayment' => $show_my_payment, 'show_myhistory' => $show_my_history, 'show_mywatching' => $show_watching ), 'global_permissions' => array( 'show_current_price' => $appearance_settings->getValue(AuctionsAppearanceSettings::MYAUCTIONS_SHOW_PRICE), 'show_start_time' => $appearance_settings->getValue(AuctionsAppearanceSettings::MYAUCTIONS_SHOW_START_TIME), 'show_close_time' => $appearance_settings->getValue(AuctionsAppearanceSettings::MYAUCTIONS_SHOW_CLOSE_TIME), 'show_duration' => $appearance_settings->getValue(AuctionsAppearanceSettings::MYAUCTIONS_SHOW_DURATION), 'show_bids' => $appearance_settings->getValue(AuctionsAppearanceSettings::MYAUCTIONS_SHOW_BIDS), 'show_bids_list' => $appearance_settings->getValue(AuctionsAppearanceSettings::MYAUCTIONS_SHOW_BIDS_LIST), 'show_winner' => $appearance_settings->getValue(AuctionsAppearanceSettings::MYAUCTIONS_SHOW_WINNER), 'show_starting_price' => $appearance_settings->getValue(AuctionsAppearanceSettings::MYAUCTIONS_SHOW_STARTING_PRICE), 'show_countdown' => $appearance_settings->getValue(AuctionsAppearanceSettings::MYAUCTIONS_SHOW_COUNTDOWN) ), 'cartSize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('cart')), 'smallSize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('small')), 'mediumSize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('medium')), 'categorySize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('category')), 'thumbSceneSize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('m_scene')), 'homeSize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('home')), 'myauctions_labels' => array( 'my_bids' => $this->l('My bids', __CLASS__), 'my_won_items' => $this->l('My won items', __CLASS__), 'my_bids_history' => $this->l('My bids history', __CLASS__), 'watching_list' => $this->l('Watching list', __CLASS__), 'no_auctions' => $this->l('You don\'t have any auctions.', __CLASS__), 'back' => $this->l('Back to your account', __CLASS__), 'home' => $this->l('Home', __CLASS__), ), )); $this->context->smarty->assign(array( 'bids_url' => $this->context->link->getModuleLink('auctions', 'bids', array( 'token' => Tools::getToken(false) )) )); } else $this->errors[] = $this->l('You must be logged in to manage your auctions.', __CLASS__); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (!class_exists('CoreModuleColumnFormatter', false)) { class CoreModuleColumnFormatter { public static function formatTemplateFromDate($value, $row, $module) { if (!empty($row['from_fixed']) && $row['from_fixed'] != '0000-00-00 00:00:00') return Tools::displayDate($row['from_fixed'], null, true); if (!empty($row['from_offset'])) { $from_countdown = self::formatCountDown($row['from_offset'], $row, FormattedAuctionsDateTime::ZEROS_TRIM_LEFT, true); if ($row['from_offset'] > 0) return sprintf($module->l('Now + %s', __CLASS__), $from_countdown); return sprintf($module->l('Now - %s', __CLASS__), $from_countdown); } return '--'; } public static function formatTemplateToDate($value, $row, $module) { if (!empty($row['to_fixed']) && $row['to_fixed'] != '0000-00-00 00:00:00') return Tools::displayDate($row['to_fixed'], null, true); if (!empty($row['to_offset'])) { $to_countdown = self::formatCountDown($row['to_offset'], $row, FormattedAuctionsDateTime::ZEROS_TRIM_LEFT, true); if ($row['to_offset'] > 0) return sprintf($module->l('Start Date + %s', __CLASS__), $to_countdown); return sprintf($module->l('Start Date - %s', __CLASS__), $to_countdown); } return '--'; } public static function formatTemplateDuration($value, $row, $zeros = FormattedAuctionsDateTime::ZEROS_TRIM_BOTH) { if (!empty($row['from_fixed']) && $row['from_fixed'] != '0000-00-00 00:00:00') $date1 = strtotime($row['from_fixed']); else if (!empty($row['from_offset'])) $date1 = time() + $row['from_offset']; else $date1 = time(); if (!empty($row['to_fixed']) && $row['to_fixed'] != '0000-00-00 00:00:00') $date2 = strtotime($row['to_fixed']); else if (!empty($row['to_offset'])) $date2 = $date1 + $row['to_offset']; else return '--'; $date_time_formatter = new FormattedAuctionsDateTime(); $date_time_formatter->setStartTimestamp($date1); $date_time_formatter->setEndTimestamp($date2); $date_time_formatter->setBehaviour($zeros); return $date_time_formatter->format(); } public static function formatDuration($value, $row, $zeros = FormattedAuctionsDateTime::ZEROS_TRIM_BOTH) { return self::formatCountDown($value, $row, $zeros); } public static function formatCountDown($value, $row, $zeros = FormattedAuctionsDateTime::ZEROS_TRIM_LEFT, $absolute = false) { if (empty($value)) return '--'; $date_time_formatter = new FormattedAuctionsDateTime(); $date_time_formatter->setBehaviour($zeros); if ($value > 0) { $date_time_formatter->setStartTimestamp(time()); $date_time_formatter->setEndTimestamp(time() + (int)$value); return $date_time_formatter->format(); } else { $date_time_formatter->setStartTimestamp(time() + (int)$value); $date_time_formatter->setEndTimestamp(time()); if ($absolute) return $date_time_formatter->format(); return '-'.$date_time_formatter->format(); } } } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * @version Release: $Revision: 7776 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class PowatagTotAdminTabHelper { /** * Function to delete admin tabs from a menu with the module name * @param string $name name of the module to delete * @return void */ public static function deleteAdminTabs($name) { Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'tab_lang WHERE id_tab IN (SELECT id_tab FROM '._DB_PREFIX_.'tab WHERE module = "'.pSQL($name).'")'); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'tab WHERE module = "'.pSQL($name).'"'); } /** * Add admin tabs in the menu * @param Array $tabs * Array[ * Array[ * id_parent => 0 || void * className => Controller to link to * module => modulename to easily delete when uninstalling * name => name to display * position => position * ] * ] */ public static function addAdminTab($tab) { $id_parent = isset($tab['id_parent']) ? $tab['id_parent'] : self::getAdminTabIDByClassName($tab['classNameParent']); /* define data array for the tab */ $data = array( 'id_tab' => '', 'id_parent' => $id_parent, 'class_name' => $tab['className'], 'module' => $tab['module'], 'position' => $tab['position'], 'active' => 1 ); /* Insert the data to the tab table*/ $res = Db::getInstance()->insert('tab', $data); //Get last insert id from db which will be the new tab id $id_tab = Db::getInstance()->Insert_ID(); //Define tab multi language data foreach (Language::getLanguages(false) as $language) { $data_lang = array( 'id_tab' => $id_tab, 'id_lang' => $language['id_lang'], 'name' => $tab['name'], ); // Now insert the tab lang data $res = Db::getInstance()->insert('tab_lang', $data_lang); } return $id_tab; } /** * Get the Id of a tab by its class name * @param string $name classname to get the ID * @return int id_tab */ public static function getAdminTabIDByClassName($name) { return Db::getInstance()->getValue('SELECT id_tab FROM '._DB_PREFIX_.'tab WHERE class_name = "'.pSQL($name).'"'); } }<file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AdminAuctionsWinnersController', false)) return; class AdminAuctionsWinnersController extends ModuleAdminController { protected $product_identifier; protected $product_table; protected $product_class_name; public function __construct() { $this->bootstrap = true; $this->identifier = 'id_product_auction'; $this->table = 'product_auction'; $this->className = 'ProductAuction'; $this->product_identifier = 'id_product'; $this->product_table = 'product'; $this->product_class_name = 'Product'; $this->lang = false; $this->list_no_link = false; $this->allow_export = true; parent::__construct(); $this->imageType = 'jpg'; $this->_defaultOrderBy = $this->identifier; $auction_statuses = array(); $auction_statuses_icon = array(); $auction_statuses_icon[0] = 'icon-2x icon-question'; foreach (ProductAuction::getStatusList($this->module) as $id => $label) { if (in_array($id, array(ProductAuction::STATUS_FINISHED, ProductAuction::STATUS_CLOSED))) { $auction_statuses_icon[$id] = "icon-2x auction-status-icon-{$id}"; $auction_statuses[$id] = $label; } } $this->fields_list = array(); $this->fields_list['id_product_auction'] = array( 'title' => $this->l('ID'), 'width' => 10 ); $this->fields_list['image'] = array( 'title' => $this->l('Photo'), 'align' => 'center', 'image' => 'p', 'image_id' => 'id_product', 'width' => 70, 'orderby' => false, 'filter' => false, 'search' => false ); $this->fields_list['name'] = array( 'title' => $this->l('Product name'), 'filter_key' => 'pl!name' ); $this->fields_list['customer_name'] = array( 'title' => $this->l('Winner name'), 'filter_key' => 'customer_name', 'havingFilter' => true, ); $this->fields_list['email'] = array( 'title' => $this->l('Winner email'), 'filter_key' => 'c!email', ); $this->fields_list['initial_price'] = array( 'title' => $this->l('Starting price'), 'type' => 'price', 'filter_key' => 'a!initial_price' ); $this->fields_list['price'] = array( 'title' => $this->l('Final bid'), 'type' => 'price', 'filter_key' => 'sp!price' ); $this->fields_list['date_bid'] = array( 'title' => $this->l('Bid date'), 'type' => 'datetime', 'filter_key' => 'pao!date_bid' ); $this->fields_list['status'] = array( 'title' => $this->l('Payment status'), 'align' => 'center', 'type' => 'select', 'icon' => $auction_statuses_icon, 'list' => $auction_statuses, 'filter_key' => 'a!status' ); $id_lang = (int)$this->context->language->id; $this->_join = ' INNER JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.`id_product_auction_offer` = a.`id_product_auction_offer`) LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.`id_product` = a.`id_product`) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = pao.`id_customer`) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (sp.`id_specific_price` = a.`id_specific_price`) '; $id_lang = (int)$this->context->language->id; $id_shop = (int)$this->context->shop->id; if (Shop::isFeatureActive()) { $alias = 'sa'; $alias_image = 'image_shop'; if (Shop::getContext() == Shop::CONTEXT_SHOP) { $this->_join .= ' JOIN `'._DB_PREFIX_.'product_shop` sa ON (a.`id_product` = sa.`id_product` AND sa.id_shop = '.$id_shop.') LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.`id_product` = a.`id_product` AND pl.`id_lang` = '.$id_lang.' AND pl.id_shop = '.$id_shop.') LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON ('.$alias.'.`id_category_default` = cl.`id_category` AND pl.`id_lang` = cl.`id_lang` AND cl.id_shop = '.$id_shop.') LEFT JOIN `'._DB_PREFIX_.'shop` shop ON (shop.id_shop = '.$id_shop.') LEFT JOIN `'._DB_PREFIX_.'image_shop` image_shop ON (image_shop.`id_image` = i.`id_image` AND image_shop.`cover` = 1 AND image_shop.id_shop='.$id_shop.')'; $this->_where .= 'AND (i.id_image IS null OR image_shop.id_shop='.$id_shop.')'; } else { $this->_join .= ' LEFT JOIN `'._DB_PREFIX_.'product_shop` sa ON (a.`id_product` = sa.`id_product` AND sa.id_shop = p.id_shop_default) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.`id_product` = a.`id_product` AND pl.`id_lang` = '.$id_lang.' AND pl.id_shop = p.id_shop_default) LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON ('.$alias.'.`id_category_default` = cl.`id_category` AND pl.`id_lang` = cl.`id_lang` AND cl.id_shop = p.id_shop_default) LEFT JOIN `'._DB_PREFIX_.'shop` shop ON (shop.id_shop = p.id_shop_default) LEFT JOIN `'._DB_PREFIX_.'image_shop` image_shop ON (image_shop.`id_image` = i.`id_image` AND image_shop.`cover` = 1 AND image_shop.id_shop=p.id_shop_default)'; $this->_where .= 'AND (i.id_image IS null OR image_shop.id_shop=p.id_shop_default)'; } } else { $alias = 'p'; $alias_image = 'i'; $this->_join .= ' LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON ('.$alias.'.`id_category_default` = cl.`id_category` AND cl.id_shop = '.$id_shop.' AND cl.id_lang = '.$id_lang.') LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.`id_product` = a.`id_product` AND pl.`id_lang` = '.$id_lang.') '; } $this->_where .= 'AND a.status IN('.ProductAuction::STATUS_FINISHED.','.ProductAuction::STATUS_CLOSED.') AND pao.status IN ('.ProductAuctionOffer::STATUS_WINNER.')'; $this->_select .= ' pl.`name`, CONCAT(c.`firstname`, " ", c.`lastname`) AS `customer_name`, c.`email`, c.`id_customer`, sp.`price`, pao.`date_add` AS `date_bid`, pao.`customer_price`, '.$alias_image.'.`id_image` '; } public function initToolbar() { parent::initToolbar(); unset($this->toolbar_btn['new']); // Default cancel button - like old back link $back = Tools::safeOutput(Tools::getValue('back', '')); if (empty($back)) if ($this->display == 'view') $back = $this->context->link->getAdminLink('AdminArchivedAuctions'); else $back = $this->context->link->getAdminLink('AdminAuctions'); if (!Validate::isCleanHtml($back)) die(Tools::displayError()); $this->toolbar_btn['back'] = array( 'href' => $back, 'desc' => $this->l('Back to list') ); } public function renderList() { $this->addRowAction('view'); return parent::renderList(); } public function renderView() { if ($this->tabAccess['view']) Tools::redirectAdmin($this->context->link->getAdminLink('AdminAuctionsView').'&id_product_auction='.(int)$this->object->id); } public function setHelperDisplay(Helper $helper) { parent::setHelperDisplay($helper); $helper->override_folder = null; $helper->module = $this->module; } protected function agilemultipleseller_list_override() { $table = $this->table; $this->table = $this->product_table; parent::agilemultipleseller_list_override(); $this->table = $table; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsListController', false)) return; class AuctionsListController extends CoreModuleController { public $cat_products = array(); public $nbProducts = array(); public $default_order_by_id; public $default_order_way_id; public function setMedia() { parent::setMedia(); $this->addCSS(array( _THEME_CSS_DIR_.'product_list.css', $this->module->getPathUri().'css/auctions_list.css', ), 'all'); } public function initContent() { parent::initContent(); $this->productSort(); // Product sort must be called before assignProductList() $this->assignProductList(); $this->context->smarty->assign(array( 'id_customer' => $this->context->customer->id, 'mod_path' => $this->module->getPathUri(), 'mod_dir' => rtrim($this->getTemplatePath('product-auction-auctions.tpl'), 'product-auction-auctions.tpl').DIRECTORY_SEPARATOR, )); $this->context->smarty->assign(array( 'request' => $this->context->link->getPaginationLink(false, false, false, true), )); $this->context->smarty->assign(array( 'products' => (isset($this->cat_products) && $this->cat_products) ? $this->cat_products : null, 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'categorySize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('category')), 'mediumSize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('medium')), 'thumbSceneSize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('m_scene')), 'homeSize' => Image::getSize(CoreModuleTools::getImageTypeFormatedName('home')), 'allow_oosp' => (int)Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'comparator_max_item' => (int)Configuration::get('PS_COMPARATOR_MAX_ITEM') )); $this->setTemplate('product-auction-list.tpl'); } public function productSort() { $stock_management = Configuration::get('PS_STOCK_MANAGEMENT') ? true : false; // no display quantity order if stock management disabled $order_by_values = array( 0 => 'name', 1 => 'price', 2 => 'date_add', 3 => 'date_upd', 4 => 'position', 5 => 'manufacturer_name', 6 => 'from', 7 => 'finished', 8 => 'ending', 9 => 'to', 10 => 'offers' ); $order_way_values = array( 0 => 'asc', 1 => 'desc' ); $default_order_by_id = $this->default_order_by_id ? $this->default_order_by_id : (int)Configuration::get('PS_PRODUCTS_ORDER_BY'); $default_order_way_id = $this->default_order_way_id ? $this->default_order_way_id : (int)Configuration::get('PS_PRODUCTS_ORDER_WAY'); $default_order_by = $order_by_values[$default_order_by_id]; $default_order_way = $order_way_values[$default_order_way_id]; $this->orderBy = Tools::strtolower(Tools::getValue('orderby', $default_order_by)); $this->orderWay = Tools::strtolower(Tools::getValue('orderway', $default_order_way)); if (!in_array($this->orderBy, $order_by_values)) $this->orderBy = $order_by_values[0]; if (!in_array($this->orderWay, $order_way_values)) $this->orderWay = $order_way_values[0]; $this->context->smarty->assign(array( 'orderby' => $this->orderBy, 'orderway' => $this->orderWay, 'orderbydefault' => $default_order_by, 'orderwayposition' => $default_order_way, // Deprecated: orderwayposition 'orderwaydefault' => $default_order_way, 'stock_management' => (int)$stock_management )); } /** * Get instance of current category */ public function getCategory() { return 0; } } <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author Presta<NAME> <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class PowaTagProduct extends PowaTagAbstract { /** * Product Model. * * @var \Product */ private $product; /** * List of combinations. * * @var array */ private $combinations; public function __construct(stdClass $datas) { parent::__construct($datas); $product = PowaTagProductHelper::getProductByCode($datas->id_product, $this->context->language->id); $this->product = $product; } public function setJSONRequest() { if (Validate::isLoadedObject($this->product)) { $product = $this->getProductWithoutOptions(); return $product; } else { $this->addError($this->module->l('Product not found'), PowaTagErrorType::$SKU_NOT_FOUND); return false; } } private function getProductWithoutOptions() { $has_options = $this->hasOptions(); $array = array( 'name' => $this->product->name, 'type' => 'PRODUCT', 'availableCurrencies' => $this->getCurrencies(), 'code' => PowaTagProductHelper::getProductSKU($this->product), 'description' => html_entity_decode(preg_replace("#\r\n#isD", ' ', strip_tags($this->product->description))), 'currency' => $this->context->currency->iso_code, 'language' => $this->context->language->iso_code, 'productImages' => $this->getImages(), 'productVariants' => $this->getVariants(), ); if ($attributes = $this->getAttributes()) { $array['productAttributes'] = $attributes; } if ($fields = $this->getCustomFields()) { $array['customFields'] = $fields; } if ($has_options) { $array['productOptions'] = $this->getOptions(); } return $array; } private function getCurrencies() { $currencies = array(); $shopCurrencies = Currency::getCurrencies(); if ($shopCurrencies && count($shopCurrencies)) { foreach ($shopCurrencies as $currency) { $currencies[] = $currency['iso_code']; } } return $currencies; } private function getImages() { $images = $this->product->getImages((int) $this->context->language->id); $link = $this->context->link; $jsonImages = array(); if ($images && count($images)) { foreach ($images as $image) { $jsonImages[] = array( 'name' => $image['legend'], 'url' => $link->getImageLink( $this->product->link_rewrite, $this->product->id.'-'.$image['id_image'] ) ); } } return $jsonImages; } private function getCombinationImages($attribute_id) { $images = $this->product->getCombinationImages((int) $this->context->language->id); $images = $images[$attribute_id]; $link = $this->context->link; $jsonImages = array(); if ($images && count($images)) { foreach ($images as $image) { $jsonImages[] = array('name' => $image['legend'], 'url' => $link->getImageLink($this->product->link_rewrite, $this->product->id.'-'.$image['id_image'])); } } return $jsonImages; } private function getAttributes() { $productAttributes = array(); $attributes = $this->product->getFeatures(); $id_lang = (int) $this->context->language->id; if ($attributes && count($attributes)) { foreach ($attributes as $attribute) { $feature = new Feature($attribute['id_feature'], $id_lang); $featureValue = new FeatureValue($attribute['id_feature_value'], $id_lang); $productAttributes[$feature->name] = $featureValue->value; } } return $productAttributes; } private function hasOptions() { $this->combinations = $this->product->getAttributeCombinations($this->context->language->id); return (bool) $this->combinations; } private function getOptions() { $combinations = array(); if ($this->combinations && count($this->combinations)) { foreach ($this->combinations as $combination) { if (!array_key_exists($combination['group_name'], $combinations)) { $combinations[$combination['group_name']] = array( 'id' => $combination['id_attribute_group'], 'values' => array(), ); } if (!in_array($combination['attribute_name'], $combinations[$combination['group_name']]['values'])) { $combinations[$combination['group_name']]['values'][] = $combination['attribute_name']; } } } return $combinations; } private function getVariants() { $groups = array(); if ($this->combinations && count($this->combinations)) { foreach ($this->combinations as $combination) { if (!array_key_exists($combination['id_product_attribute'], $groups)) { $groups[$combination['id_product_attribute']] = array( 'code' => PowatagProductAttributeHelper::getVariantCode($combination), 'numberInStock' => PowaTagProductQuantityHelper::getCombinationQuantity($combination), 'productImages' => $this->getCombinationImages($combination['id_product_attribute']), 'originalPrice' => array( 'amount' => $this->formatNumber($this->product->getPrice($this->display_taxes, null), 2), 'currency' => $this->context->currency->iso_code, ), 'finalPrice' => array( 'amount' => $this->formatNumber($this->product->getPrice($this->display_taxes, $combination['id_product_attribute']), 2), 'currency' => $this->context->currency->iso_code, ), ); } $groups[$combination['id_product_attribute']]['options'][$combination['group_name']] = $combination['attribute_name']; } sort($groups); } else { $variant = array( 'code' => PowaTagProductHelper::getProductSKU($this->product), 'numberInStock' => PowaTagProductQuantityHelper::getProductQuantity($this->product), 'finalPrice' => array( 'amount' => $this->formatNumber($this->product->getPrice($this->display_taxes, null), 2), 'currency' => $this->context->currency->iso_code, ), ); $groups = array($variant); } return $groups; } private function getCustomFields() { return array(); } } <file_sep><?php /** * module-update_class.php file defines method for updating the module */ class BT_FpcModuleUpdate { /** * @var $aErrors : store errors */ public $aErrors = array(); /** * Magic Method __construct * * @category update collection */ public function __construct() { } /** * run() method execute required function * @param $aParam */ public function run(array $aParam = null) { // get type $aParam['sType'] = empty($aParam['sType'])? 'tables' : $aParam['sType']; switch ($aParam['sType']) { case 'tables' : // use case - update tables case 'fields' : // use case - update fields case 'hooks' : // use case - update hooks case 'templates' : // use case - update templates // execute match function call_user_func_array(array($this, '_update' . ucfirst($aParam['sType'])), array($aParam)); break; default : break; } } /** * _updateTables() method update tables if required * * @param array $aParam */ private function _updateTables(array $aParam) { // set transaction Db::getInstance()->Execute('BEGIN'); if (!empty($GLOBALS[_FPC_MODULE_NAME . '_SQL_UPDATE']['table'])) { // loop on each elt to update SQL foreach ($GLOBALS[_FPC_MODULE_NAME . '_SQL_UPDATE']['table'] as $sTable => $sSqlFile) { // execute query $bResult = Db::getInstance()->ExecuteS('SHOW TABLES LIKE "' . _DB_PREFIX_ . strtolower(_FPC_MODULE_NAME) . '_'. $sTable .'"'); // if empty - update if (empty($bResult)) { require_once(_FPC_PATH_CONF . 'install.conf.php'); require_once(_FPC_PATH_LIB_INSTALL . 'install-ctrl_class.php'); // use case - KO update if (!BT_InstallCtrl::run('install', 'sql', _FPC_PATH_SQL . $sSqlFile)) { $this->aErrors[] = array('table' => $sTable, 'file' => $sSqlFile); } } } } if (empty($this->aErrors)) { Db::getInstance()->Execute('COMMIT'); } else { Db::getInstance()->Execute('ROLLBACK'); } } /** * _updateFields() method update fields if required * * @param array $aParam */ private function _updateFields(array $aParam) { // set transaction Db::getInstance()->Execute('BEGIN'); if (!empty($GLOBALS[_FPC_MODULE_NAME . '_SQL_UPDATE']['field'])) { // loop on each elt to update SQL foreach ($GLOBALS[_FPC_MODULE_NAME . '_SQL_UPDATE']['field'] as $sFieldName => $aOption) { // execute query $bResult = Db::getInstance()->ExecuteS('SHOW COLUMNS FROM ' . _DB_PREFIX_ . strtolower(_FPC_MODULE_NAME) . '_'. $aOption['table'] . ' LIKE "' . $sFieldName .'"'); // if empty - update if (empty($bResult)) { require_once(_FPC_PATH_CONF . 'install.conf.php'); require_once(_FPC_PATH_LIB_INSTALL . 'install-ctrl_class.php'); // use case - KO update if (!BT_InstallCtrl::run('install', 'sql', _FPC_PATH_SQL . $aOption['file'])) { $aErrors[] = array('field' => $sFieldName, 'linked' => $aOption['table'], 'file' => $aOption['file']); } } } } if (empty($this->aErrors)) { Db::getInstance()->Execute('COMMIT'); } else { Db::getInstance()->Execute('ROLLBACK'); } } /** * _updateHooks() method update hooks if required * * @category admin collection * @param array $aParam */ private function _updateHooks(array $aParam) { require_once(_FPC_PATH_CONF . 'install.conf.php'); require_once(_FPC_PATH_LIB_INSTALL . 'install-ctrl_class.php'); // use case - hook register ko if (!BT_InstallCtrl::run('install', 'config', array('bHookOnly' => true))) { $this->aErrors[] = array('table' => 'ps_hook_module', 'file' => ModuleTemplate::$oModule->l('register hooks KO')); } } /** * _updateTemplates() method update templates if required * * @param array $aParam */ private function _updateTemplates(array $aParam) { require_once(_FPC_PATH_LIB_COMMON . 'dir-reader.class.php'); // get templates files $aTplFiles = BT_DirReader::create()->run(array('path' => _FPC_PATH_TPL, 'recursive' => true, 'extension' => 'tpl', 'subpath' => true)); if (!empty($aTplFiles)) { global $smarty; if (method_exists($smarty, 'clearCompiledTemplate')) { $smarty->clearCompiledTemplate(); } elseif (method_exists($smarty, 'clear_compiled_tpl')) { foreach ($aTplFiles as $aFile) { $smarty->clear_compiled_tpl($aFile['filename']); } } } } /** * getErrors() method returns errors * * @return array */ public function getErrors() { return ( $this->aErrors ); } /** * create() method manages singleton * * @return array */ public static function create() { static $oModuleUpdate; if( null === $oModuleUpdate) { $oModuleUpdate = new BT_FpcModuleUpdate(); } return $oModuleUpdate; } }<file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_ca7d973c26c57b69e0857e7a0332d545'] = 'Os produtos em destaque'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_03c2e7e41ffc181a4e84080b4710e81e'] = 'novo'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_e0e572ae0d8489f8bf969e93d469e89c'] = 'Não há produtos em destaque'; <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcontactinfos}touchmenot1.0.3>blockcontactinfos_02d4482d332e1aef3437cd61c9bcc624'] = 'Kontaktieren Sie uns'; $_MODULE['<{blockcontactinfos}touchmenot1.0.3>blockcontactinfos_d0398e90769ea6ed2823a3857bcc19ea'] = 'Tel:'; $_MODULE['<{blockcontactinfos}touchmenot1.0.3>blockcontactinfos_6a1e265f92087bb6dd18194833fe946b'] = 'E-Mail:'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractProductAuctionBid', false)) return; abstract class AbstractProductAuctionBid { const BID_DECIMALS = 6; protected $bid_price; protected $module; protected $customer; protected $product_auction; /** * * @param Auctions $module */ public function __construct(Auctions $module) { $this->setModule($module); } /** * * @return AbstractProductAuctionBidResult */ abstract public function calculate(); /** * * @return AbstractProductAuctionBidResult */ abstract protected function getBidResult(); public function setModule(Auctions $module) { $this->module = $module; } public function setCustomer(Customer $customer) { $this->customer = $customer; } public function setProductAuction(ProductAuction $product_auction) { $this->product_auction = $product_auction; } public function setBidPrice($price) { $this->bid_price = $price; } protected function getPriceCalculator() { switch (Product::getTaxCalculationMethod((int)$this->customer->id)) { case PS_TAX_INC: $price_calculator = new NetAuctionsPriceCalculator(); break; case PS_TAX_EXC: default: $price_calculator = new NullAuctionsPriceCalculator(); break; } $price_calculator->setModule($this->module); $price_calculator->setProduct($this->product_auction->product); return $price_calculator; } public function getProductAuction() { return $this->product_auction; } public function getProductAuctionOffer() { return $this->getProductAuction()->product_auction_offer; } public function getCustomer() { return $this->customer; } public function getBidPrice() { return $this->getPriceCalculator()->getPrice($this->bid_price, self::BID_DECIMALS); } public function getMinimalPrice() { return $this->product_auction->minimal_price; } public function getInitialPrice() { return $this->product_auction->initial_price; } public function getCurrentPrice() { return $this->product_auction->specific_price->price; } public function getHighestPrice() { if ($this->product_auction->id_product_auction_offer > 0) return $this->product_auction->product_auction_offer->customer_price; return $this->getInitialPrice(); } public function getBidStep() { return $this->product_auction->calculateIncrement($this->getCurrentPrice()); } public function isCurrentWinner() { if ($this->product_auction->id_product_auction_offer > 0) return $this->product_auction->product_auction_offer->id_customer == $this->customer->id; return false; } public function hasProxyBidding() { return (boolean)$this->product_auction->proxy_bidding; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionTemplate', false)) return; class ProductAuctionTemplate extends ProductAuctionObjectModel { /** * @var integer ProductAuctionTemplate id */ public $id_product_auction_template; /** * @var integer ProductAuctionType id */ public $id_product_auction_type = 1; /** * @var string Auction template name */ public $name; /** * @var string Auction template enable_auction */ public $enable_auction = 0; /** * @var float Initial Price in euros */ public $initial_price = 0.010000; /** * @var float Reserve price in euros */ public $minimal_price = 0.000000; /** * @var float Buy now price in euros */ public $buynow_price = 0.000000; /** * @var boolean ProductAuction show buy now price after any offer was placed */ public $buynow_after_bid = 1; /** * @var boolean ProductAuction show buy now price */ public $buynow_visible = 1; /** * @var string Bidding increment rules */ public $bidding_increment = '[{"from":"0.000000","to":"0.000000","step":"0.010000"}]'; /** * @var boolean Auction proxy biddind */ public $proxy_bidding = 1; /** * @var string Auction extend time threshold */ public $extend_threshold; /** * @var string Auction extend time step */ public $extend_by; /** * @var string Auction start date offset */ public $from_fixed; /** * @var string Auction end date offset */ public $to_fixed; /** * @var string Auction start date offset */ public $from_offset; /** * @var string Auction end date offset */ public $to_offset; /** * @var boolean Product default */ public $default = 0; /** * @var boolean Product status */ public $active = 1; /** * @var string Object creation date */ public $date_add; /** * @var string Object last modification date */ public $date_upd; public static $definition = array( 'table' => 'product_auction_template', 'primary' => 'id_product_auction_template', 'multilang' => true, 'multilang_shop' => false, 'fields' => array( 'id_product_auction_type' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'enable_auction' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'name' => array( 'type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isString', 'required' => true, 'size' => 255 ), 'initial_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'minimal_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'buynow_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'buynow_after_bid' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'buynow_visible' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'bidding_increment' => array( 'type' => self::TYPE_STRING, 'validate' => 'isString' ), 'proxy_bidding' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'extend_threshold' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'extend_by' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'from_fixed' => array( 'type' => self::TYPE_STRING, 'validate' => 'isDateFormat' ), 'to_fixed' => array( 'type' => self::TYPE_STRING, 'validate' => 'isDateFormat' ), 'from_offset' => array( 'type' => self::TYPE_STRING, 'validate' => 'isInt' ), 'to_offset' => array( 'type' => self::TYPE_STRING, 'validate' => 'isInt' ), 'default' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'active' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'date_add' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ), 'date_upd' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ) ) ); public static function getTemplatesList(Module $module) { $context = $module->getContext(); $product_auction_template_collection = ProductAuctionTemplateDataManager::getCollection($context->language->id, $context->shop->id); $product_auction_templates = array(); $product_auction_templates[] = array( 'id' => -1, 'name' => '--' ); foreach ($product_auction_template_collection as $product_auction_template) { $product_auction_templates[] = array( 'id' => $product_auction_template->id, 'name' => $product_auction_template->name ); } return $product_auction_templates; } public function __isset($key) { switch ($key) { case 'from': return isset($this->from_fixed) || isset($this->from_offset); case 'to': return isset($this->to_fixed) || isset($this->to_offset); default: return parent::__isset($key); } } public function __get($key) { switch ($key) { case 'from': return !empty($this->from_fixed) && $this->to_fixed != '0000-00-00 00:00:00' ? $this->from_fixed : date('Y-m-d H:i:s', time() + (int)$this->from_offset); case 'to': return !empty($this->to_fixed) && $this->to_fixed != '0000-00-00 00:00:00' ? $this->to_fixed : date('Y-m-d H:i:s', strtotime($this->from) + (int)$this->to_offset); default: return parent::__get($key); } } public function __set($key, $value) { switch ($key) { case 'from': break; case 'to': break; default: parent::__set($key, $value); break; } } public function add($autodate = true, $null_values = false) { return parent::add($autodate, true); } public function update($null_values = false) { return parent::update(true); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractAuctionsDateTime', false)) return; abstract class AbstractAuctionsDateTime { const REMOVE_NONE = 1; const REMOVE_INITIAL = 2; const REMOVE_ALL = 4; /** * * @var DateTime */ protected $start; /** * * @var DateTime */ protected $end; /** * * @var string */ protected $format; /** * * @var string */ protected $zeros_behaviour; /** * * @param integer $start */ public function setStartTimestamp($start) { $this->start = $start; } /** * * @param integer $end */ public function setEndTimestamp($end) { $this->end = $end; } /** * @param string $format */ public function setFormat($format) { $this->format = $format; } /** * @param string $behaviour */ public function setBehaviour($behaviour) { $this->zeros_behaviour = $behaviour; } /** * @return number */ public function get() { return $this->end - $this->start; } abstract public function format(); } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionObjectModel', false)) return; abstract class ProductAuctionObjectModel extends ObjectModelCore { const MINIMAL_BID_INCREMENT = 0.01000; private $increment_cache = array(); /** * @var integer ProductAuctionType id */ public $id_product_auction_type; public function __isset($key) { switch ($key) { case 'bidding_increment_array': return isset($this->bidding_increment); default: return isset($this->{$key}); } } public function __get($key) { switch ($key) { case 'bidding_increment_array': if (!empty($this->increment_cache)) return $this->increment_cache; $value = Tools::jsonDecode(Tools::stripslashes($this->bidding_increment), true); $size = count($value); $first = 0; $last = $size - 1; if (!isset($value[$first]['from'])) $value[$first]['from'] = 0; if (!isset($value[$last]['to'])) $value[$last]['to'] = 0; $this->increment_cache = $value; return $value; default: return isset($this->{$key}) ? $this->{$key} : null; } } public function __set($key, $value) { switch ($key) { case 'bidding_increment_array': $value = array_merge(array(), $value); $size = count($value); $first = 0; $last = $size - 1; if (!isset($value[$first]['from'])) $value[$first]['from'] = 0; if (!isset($value[$last]['to'])) $value[$last]['to'] = 0; $value[$first]['from'] = $value[$first]['from'] > 0 ? 0 : $value[$first]['from']; $value[$last]['to'] = $value[$last]['to'] > 0 ? 0 : $value[$last]['to']; array_walk_recursive($value, array( 'CoreModuleTools', 'priceFormat' ), 6); $this->bidding_increment = Tools::jsonEncode($value); $this->increment_cache = null; break; default: if (isset($this->{$key})) $this->{$key} = $value; break; } } public function getProductAuctionType() { return ProductAuctionTypeFactory::getInstance()->getProductAuctionType($this->id_product_auction_type); } public function calculateIncrement($price) { $raw_increments = $this->bidding_increment_array; if (!is_array($raw_increments) || empty($raw_increments)) return self::MINIMAL_BID_INCREMENT; $increments = array(); foreach ($raw_increments as $raw_increments_item) { $from = isset($raw_increments_item['from']) ? (float)$raw_increments_item['from'] : 0; $step = isset($raw_increments_item['step']) ? (float)$raw_increments_item['step'] : 0.01; $increments[$from] = $step; } $closest = CoreModuleTools::getClosest($price, array_keys($increments)); return $increments[$closest]; } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_2377be3c2ad9b435ba277a73f0f1ca76'] = 'Hersteller'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_49fa2426b7903b3d4c89e2c1874d9346'] = 'Ehr über'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_bf24faeb13210b5a703f3ccef792b000'] = 'Alle Hersteller'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_1c407c118b89fa6feaae6b0af5fc0970'] = 'Kein Hersteller'; <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ require_once 'PowaTagOrdersCosts.php'; class PowaTagCosts extends PowaTagOrdersCosts { /** * Currency. * * @var Currency */ private $currency; /** * Product list. * * @var array */ private $products; public function __construct(stdClass $datas) { parent::__construct($datas); $this->products = $this->datas->order->orderLineItems; } /** * Get currency of request. */ private function getCurrency() { $this->currency = $this->getCurrencyByIsoCode($this->context->currency->iso_code); } /** * Get datas for return of request. * * @return array Datas */ public function getSummary() { $this->getCurrency(); list($id_cart, $id_order, $message) = $this->validateOrder(); if (!$id_cart) { return false; } $id_order = $id_order . $message; // this code prevents validator report unused variable $det = $this->cart->getSummaryDetails(); $detail = array(); $total_discount = 0; foreach ($det['products'] as &$product) { $product['price_without_quantity_discount'] = Product::getPriceStatic( $product['id_product'], false, $product['id_product_attribute'], 6, null, false, false ); // product price without tax $discount = $product['price_without_quantity_discount'] - $product['price']; $total_discount += $discount * $product['quantity']; $detail[] = array( 'code' => $product['id_product'], 'unitPrice' => array( 'amount' => $this->formatNumber($product['price_without_quantity_discount'], 2), 'currency' => $this->currency->iso_code, ), 'unitDiscount' => array( 'amount' => $this->formatNumber($discount, 2), 'currency' => $this->currency->iso_code, ), 'unitTax' => array( 'amount' => $this->formatNumber($product['price_wt'] - $product['price'], 2), 'currency' => $this->currency->iso_code, ), 'quantity' => $product['quantity'], 'total' => array( 'amount' => $this->formatNumber($product['total_wt'], 2), 'currency' => $this->currency->iso_code, ), ); } $shipping_tax = $det['total_shipping'] - $det['total_shipping_tax_exc']; $response = array( 'orderCostSummary' => array( 'subTotal' => array( 'amount' => $this->formatNumber($det['total_products'], 2), 'currency' => $this->currency->iso_code, ), 'discount' => array( 'amount' => $this->formatNumber($total_discount + $det['total_discounts'], 2), 'currency' => $this->currency->iso_code, ), 'shippingCost' => array( 'amount' => $this->formatNumber($det['total_shipping_tax_exc'], 2), 'currency' => $this->currency->iso_code, ), 'shippingDiscount' => array( 'amount' => $this->formatNumber(0, 2), 'currency' => $this->currency->iso_code, ), 'shippingTax' => array( 'amount' => $this->formatNumber($shipping_tax, 2), 'currency' => $this->currency->iso_code, ), 'tax' => array( 'amount' => $this->formatNumber($det['total_tax'], 2), 'currency' => $this->currency->iso_code, ), 'total' => array( 'amount' => $this->formatNumber($det['total_price'], 2), 'currency' => $this->currency->iso_code, ), ), 'orderCostDetails' => $detail, ); return $response; } } <file_sep><?php header("Pragma: no-cache"); header("Expires: 0"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); //header("Content-type: application/xml"); $PS_ROOT_DIR=$_GET['PS_ROOT_DIR']; //$PS_ROOT_DIR='c:\wamp\www\prestashop1-4-4'; require($PS_ROOT_DIR.'/config/config.inc.php'); $chemin=$PS_ROOT_DIR.'/modules/yourbarcode_gp/ean13curl.php'; //$chemin=$PS_ROOT_DIR.'\modules\yourbarcode_gp\logo.jpg'; require('fpdf.php'); //ex: http://127.0.0.1/cd_barre/pdf.php?cd_ean13=3149025043092&url=http://127.0.0.1/cd_barre/EAN13.php $cd_ean13=$_GET['cd_ean13']; $url=$_GET['url']; //recuperation des variables dans la table de configuration $sql='select * from '._DB_PREFIX_.'yourbarcodeconf'; $resultat=Db::getInstance()->ExecuteS($sql); foreach ($resultat as $row) { $prefix_cd=$row['prefix_cd']; $format_pg=$row['format_pg']; $format_spe_lg=$row['format_spe_lg']; $format_spe_ht=$row['format_spe_ht']; $orientation=$row['orientation']; $marge_haut=$row['marge_haut']; $marge_gauche=$row['marge_gauche']; $rotation=$row['rotation']; $largeur_cd=$row['largeur_cd']; $hauteur_cd=$row['hauteur_cd']; $nb_img_lg=$row['nb_img_lg']; $nb_lig=$row['nb_lig']; $esp_lg_lg=$row['esp_lg_lg']; $esp_cl_cl=$row['esp_cl_cl']; } /* $format_pg='A4'; //A3, A4, A5, Letter, Legal sont possible $orientation='P'; //P-> portrait et L-> Landscape $marge_haut=0; $marge_gauche=10; $largeur_cd=30; $hauteur_cd=10; //si 0 garde les proportions $nb_img_lg=5; $nb_lig=19; $esp_lg_lg=0; $esp_cl_cl=0; */ //echo $url.'?numero='.$cd_ean13.'&dimension=5'.'&rotation='.$rotation; $curlHandler=curl_init(); curl_setopt($curlHandler, CURLOPT_URL, $url.'?numero='.$cd_ean13.'&dimension=5'.'&rotation='.$rotation); curl_setopt($curlHandler, CURLOPT_HEADER,0); curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); $output =curl_exec($curlHandler); file_put_contents("test_tmp.png",$output); $pdf = new FPDF(); $pdf->AliasNbPages(); if($format_spe_lg<>0 and $format_spe_ht<>0) { $pdf->AddPage($orientation,array($format_spe_lg,$format_spe_ht)); } else { $pdf->AddPage($orientation,$format_pg); } $pdf->SetFont('Times','',12); $abs_c_gh_cd=$marge_gauche; $ord_c_gh_cd=$marge_haut; //gere les saut de ligne for ($j=1;$j<=$nb_lig;$j++){ //dessine les cd sur la ligne for ($i=1;$i<=$nb_img_lg;$i++){ //$pdf->Image($url.'?numero='.$cd_ean13.'&dimension=5',$abs_c_gh_cd,$ord_c_gh_cd,$largeur_cd,$hauteur_cd,'png'); //$pdf->Image($output,$abs_c_gh_cd,$ord_c_gh_cd,$largeur_cd,$hauteur_cd,'png'); if($rotation==1){ $pdf->Image('test_tmp.png',$abs_c_gh_cd,$ord_c_gh_cd,$hauteur_cd,$largeur_cd,'png'); } else { $pdf->Image('test_tmp.png',$abs_c_gh_cd,$ord_c_gh_cd,$largeur_cd,$hauteur_cd,'png'); } //$pdf->Image($chemin.' "'.$cd_ean13.'" "5"',$abs_c_gh_cd,$ord_c_gh_cd,$largeur_cd,$hauteur_cd,'png'); //$pdf->Image('php '.$chemin,$abs_c_gh_cd,$ord_c_gh_cd,$largeur_cd,$hauteur_cd,'png'); if($rotation==1){ $abs_c_gh_cd=$abs_c_gh_cd+$hauteur_cd+$esp_cl_cl; } else { $abs_c_gh_cd=$abs_c_gh_cd+$largeur_cd+$esp_cl_cl; } } if($rotation==1){ $ord_c_gh_cd=$ord_c_gh_cd+$largeur_cd+$esp_lg_lg; } else { $ord_c_gh_cd=$ord_c_gh_cd+$hauteur_cd+$esp_lg_lg; } $abs_c_gh_cd=$marge_gauche; } $pdf->Output(); curl_close($curlHandler); ?><file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsCronSettings', false)) return; class AuctionsCronSettings extends CoreModuleSettings { const CRON_PROCESSING_NUMBER_ITEMS = 'auct_cron_proc_num_it'; const CRON_MAILING_NUMBER_ITEMS = 'auct_cron_mail_num_it'; const CRON_ARCHIVING_NUMBER_ITEMS = 'auct_cron_arch_num_it'; const CRON_OUTDATE_INTERVAL = 'auct_app_cron_outdat_intv'; const DEFAULT_CRON_PROCESSING_NUMBER_ITEMS = 100; const DEFAULT_CRON_MAILING_NUMBER_ITEMS = 100; const DEFAULT_CRON_ARCHIVING_NUMBER_ITEMS = 100; const DEFAULT_CRON_OUTDATE_INTERVAL = 30; protected $submit_action = 'submitCron'; public function getTitle() { return $this->l('Cron Jobs'); } public function showForm($tab_index) { $module = $this->getModule(); $module_uri = Tools::getShopDomain(true).$module->getPathUri(); $secure_key_process = CoreModuleTools::getSecureKey('AuctionsProcessModuleFrontController'); $secure_key_mailing = CoreModuleTools::getSecureKey('AuctionsMailingModuleFrontController'); $secure_key_archive = CoreModuleTools::getSecureKey('AuctionsArchiveModuleFrontController'); $process_url = $module_uri.'cron/process.php?secure_key='.$secure_key_process; $mailing_url = $module_uri.'cron/mailing.php?secure_key='.$secure_key_mailing; $archive_url = $module_uri.'cron/archive.php?secure_key='.$secure_key_archive; $label_minute = $this->l('run every 1 minutes or lowest possible'); $label_day = $this->l('run once a day'); $link_process = '<a href="'.$process_url.'" target="_blank">'.$process_url.'</a>'; $link_mailing = '<a href="'.$mailing_url.'" target="_blank">'.$mailing_url.'</a>'; $link_archive = '<a href="'.$archive_url.'" target="_blank">'.$archive_url.'</a>'; $this->values['cron_jobs_2'] = '<p class="form-control-static">curl '.$link_process.' <strong>('.$label_minute.')</strong></p>'; $this->values['cron_jobs_3'] = '<p class="form-control-static">curl '.$link_mailing.' <strong>('.$label_minute.')</strong></p>'; $this->values['cron_jobs_4'] = '<p class="form-control-static">curl '.$link_archive.' <strong>('.$label_day.')</strong></p>'; $label_cron = $this->l('Place this URL in the crontab to run it periodically'); $fields_form = array(); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Processing'), 'image' => $this->getModule()->getPathUri().'img/icon/logo16px.png' ), 'input' => array( array( 'type' => 'free', 'label' => $this->l('Command'), 'name' => 'cron_jobs_2', 'desc' => $this->l('This Cron Job command has to be set in your hosting administration panel').'. '.$label_cron.'.' ), array( 'type' => 'text', 'label' => $this->l('Items count'), 'name' => self::CRON_PROCESSING_NUMBER_ITEMS, 'required' => true, 'desc' => $this->l('Decide how many items will be processed during one execution of the cron job.') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Mailing'), 'image' => $this->getModule()->getPathUri().'img/icon/logo16px.png' ), 'input' => array( array( 'type' => 'free', 'label' => $this->l('Command'), 'name' => 'cron_jobs_3', 'desc' => $this->l('This Cron Job command has to be set in your hosting administration panel').'. '.$label_cron.'.' ), array( 'type' => 'text', 'label' => $this->l('Items count'), 'name' => self::CRON_MAILING_NUMBER_ITEMS, 'required' => true, 'desc' => $this->l('Decide how many items will be processed during one execution of the cron job.') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Archiving'), 'image' => $this->getModule()->getPathUri().'img/icon/logo16px.png' ), 'input' => array( array( 'type' => 'free', 'label' => $this->l('Command'), 'name' => 'cron_jobs_4', 'desc' => $this->l('This Cron Job command has to be set in your hosting administration panel').'. '.$label_cron.'.' ), array( 'type' => 'text', 'label' => $this->l('Items count'), 'name' => self::CRON_ARCHIVING_NUMBER_ITEMS, 'required' => true, 'desc' => $this->l('Decide how many items will be processed during one execution of the cron job.') ), array( 'type' => 'text', 'label' => $this->l('Archive auctions after'), 'name' => self::CRON_OUTDATE_INTERVAL, 'required' => false, 'desc' => $this->l('Define how old auctions will be archived (in days).') ) ) ) ); return $this->renderForm($fields_form, $tab_index); } public function init() { $this->setValue(self::CRON_PROCESSING_NUMBER_ITEMS, (int)Configuration::get(self::CRON_PROCESSING_NUMBER_ITEMS)); $this->setValue(self::CRON_MAILING_NUMBER_ITEMS, (int)Configuration::get(self::CRON_MAILING_NUMBER_ITEMS)); $this->setValue(self::CRON_ARCHIVING_NUMBER_ITEMS, (int)Configuration::get(self::CRON_ARCHIVING_NUMBER_ITEMS)); $this->setValue(self::CRON_OUTDATE_INTERVAL, (int)Configuration::get(self::CRON_OUTDATE_INTERVAL)); } public function install() { Configuration::updateValue(self::CRON_PROCESSING_NUMBER_ITEMS, self::DEFAULT_CRON_PROCESSING_NUMBER_ITEMS); Configuration::updateValue(self::CRON_MAILING_NUMBER_ITEMS, self::DEFAULT_CRON_MAILING_NUMBER_ITEMS); Configuration::updateValue(self::CRON_ARCHIVING_NUMBER_ITEMS, self::DEFAULT_CRON_ARCHIVING_NUMBER_ITEMS); Configuration::updateValue(self::CRON_OUTDATE_INTERVAL, self::DEFAULT_CRON_OUTDATE_INTERVAL); return true; } public function uninstall() { Configuration::deleteByName(self::CRON_PROCESSING_NUMBER_ITEMS); Configuration::deleteByName(self::CRON_MAILING_NUMBER_ITEMS); Configuration::deleteByName(self::CRON_ARCHIVING_NUMBER_ITEMS); Configuration::deleteByName(self::CRON_OUTDATE_INTERVAL); return true; } public function update() { Configuration::updateValue(self::CRON_PROCESSING_NUMBER_ITEMS, (int)Tools::getValue(self::CRON_PROCESSING_NUMBER_ITEMS)); Configuration::updateValue(self::CRON_MAILING_NUMBER_ITEMS, (int)Tools::getValue(self::CRON_MAILING_NUMBER_ITEMS)); Configuration::updateValue(self::CRON_ARCHIVING_NUMBER_ITEMS, (int)Tools::getValue(self::CRON_ARCHIVING_NUMBER_ITEMS)); Configuration::updateValue(self::CRON_OUTDATE_INTERVAL, (int)Tools::getValue(self::CRON_OUTDATE_INTERVAL)); return true; } protected function validate() { $condition = true; $condition &= Validate::isInt(Tools::getValue(self::CRON_PROCESSING_NUMBER_ITEMS)); $condition &= Validate::isInt(Tools::getValue(self::CRON_MAILING_NUMBER_ITEMS)); $condition &= Validate::isInt(Tools::getValue(self::CRON_ARCHIVING_NUMBER_ITEMS)); $condition &= Validate::isInt(Tools::getValue(self::CRON_OUTDATE_INTERVAL)); return $condition; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractProductAuctionType', false)) return; abstract class AbstractProductAuctionType extends CoreModuleObject implements ProductAuctionsObjectTemplatesInterface { public function getProductAuctionCreate() { } public function getProductAuctionItem() { } public function getProductAuctionOfferItem() { } public function getProductAuctionValidator() { } public function getProductAuctionBid(Auctions $module) { } public function getProductAuctionPermissions(AuctionsAppearanceSettings $appearance_settings) { } public function getProductAuctionMailingManager(Auctions $module) { } /** * * @param CoreModuleEventListenerInterface $event_listener */ public function notify(CoreModuleEventListenerInterface $event_listener) { $this->dispatcher()->register($event_listener); } /** * * @param AbstractProductAuctionBidResult $product_auction_bid_result */ public function bid(AbstractProductAuctionBidResult $product_auction_bid_result) { if ($product_auction_bid_result->getResult() == AbstractProductAuctionBidResult::INVALID) return AbstractProductAuctionBidResult::INVALID; $product_auction = $product_auction_bid_result->getProductAuction(); $customer = $product_auction_bid_result->getCustomer(); $product_auction_offer = $product_auction->getProductAuctionOffer(); $product_auction_bid_result->setPreviousProductAuctionOffer($product_auction_offer); $product_auction_bid_result->setCurrentProductAuctionOffer($product_auction_offer); $is_winner = $product_auction_bid_result->isWinner(); if (!$is_winner) { $new_product_auction_offer = new ProductAuctionOffer(); $new_product_auction_offer->id_product_auction = (int)$product_auction->id; $new_product_auction_offer->id_customer = (int)$customer->id; $new_product_auction_offer->customer_price = $product_auction_bid_result->getBidPrice(); $new_product_auction_offer->previous_price = $product_auction_bid_result->getPreviousPrice(); $new_product_auction_offer->save(true); $new_product_auction_offer->setProductAuction($product_auction); $new_product_auction_offer->setCustomer($customer); if (!Validate::isLoadedObject($new_product_auction_offer)) return AbstractProductAuctionBidResult::INVALID; if ($product_auction_bid_result->getResult() > AbstractProductAuctionBidResult::VALID_ALREADY_EXIST) { $product_auction_bid_result->setCurrentProductAuctionOffer($new_product_auction_offer); $product_auction->setProductAuctionOffer($new_product_auction_offer); } } $product_auction_offer = $product_auction->getProductAuctionOffer(); if ($product_auction_offer->customer_price <= $product_auction_bid_result->getBidPrice()) { $product_auction_offer->customer_price = $product_auction_bid_result->getBidPrice(); $product_auction_offer->previous_price = $product_auction_bid_result->getCurrentPrice(); $product_auction_offer->save(true); } $product_auction->specific_price->price = $product_auction_bid_result->getCurrentPrice(); if (!$is_winner) $product_auction->offers += 1; if ((strtotime($product_auction->to) - time()) < $product_auction->extend_threshold) $product_auction->to = date('Y-m-d H:i:s', (strtotime($product_auction->to) + $product_auction->extend_by)); $product_auction->save(true); $this->dispatcher()->dispatch(new ProductAuctionEventBid($product_auction, $product_auction_bid_result)); return $product_auction_bid_result->getResult(); } /** * * @param ProductAuctionItemEnglish $product_auction_item */ public function process(ProductAuctionItemEnglish $product_auction_item) { if ($product_auction_item->isStatus(array( ProductAuction::STATUS_PROCESSING ))) { $product_auction = $product_auction_item->getObjectModel(); $product_auction->status = ProductAuction::STATUS_FINISHED; $result = $product_auction->save(true); if ($result && $product_auction_item->hasWinner()) { $product_auction_offer = $product_auction_item->getProductAuctionOffer(); $product_auction_item_is_available = $product_auction_item->isAvailable(); $product_auction_item_is_minimal = $product_auction_item->isMinimalPriceReached(); $product_auction_item_is_valid = $product_auction_offer->status == ProductAuctionOffer::STATUS_VALID; if ($product_auction_item_is_available && $product_auction_item_is_minimal && $product_auction_item_is_valid) { $product_auction_offer->status = ProductAuctionOffer::STATUS_WINNER; $product_auction_offer->save(true); } } $this->dispatcher()->dispatch(new ProductAuctionEventFinish($product_auction)); } } /** * * @param ProductAuction $product_auction */ public function restart(ProductAuction $product_auction) { $product_auction->id_product_auction_offer = null; $product_auction->offers = 0; $product_auction->status = ProductAuction::STATUS_RUNNING; $product_auction->save(true); ProductAuctionOfferDataManager::clearOffersForProductAuction($product_auction); $this->dispatcher()->dispatch(new ProductAuctionEventRestart($product_auction)); } /** * * @param ProductAuction $product_auction */ public function finish(ProductAuction $product_auction) { $product_auction->status = ProductAuction::STATUS_PROCESSING; $product_auction->save(true); $has_offer = is_object($product_auction->product_auction_offer); if ($has_offer) $this->markWinner($product_auction->product_auction_offer); } /** * * @param ProductAuction $product_auction */ public function acceptWinner(ProductAuction $product_auction) { $is_finished = $product_auction->status == ProductAuction::STATUS_FINISHED; $has_offer = is_object($product_auction->product_auction_offer); if ($is_finished && $has_offer) { $this->markWinner($product_auction->product_auction_offer); $this->dispatcher()->dispatch(new ProductAuctionEventAcceptWinner($product_auction)); } } /** * * @param ProductAuction $product_auction */ public function remindWinner(ProductAuction $product_auction) { $this->dispatcher()->dispatch(new ProductAuctionEventRemind($product_auction)); } /** * * @param ProductAuctionOffer $product_auction_offer */ public function markWinner(ProductAuctionOffer $product_auction_offer) { $product_auction = $product_auction_offer->product_auction; if ($product_auction->id_product_auction_offer > 0 && !empty($product_auction->product_auction_offer)) { if ($product_auction->product_auction_offer->customer_price > $product_auction_offer->customer_price) { $product_auction->product_auction_offer->status = ProductAuctionOffer::STATUS_RETIRED; $product_auction->product_auction_offer->update(true); } else { $product_auction->product_auction_offer->status = ProductAuctionOffer::STATUS_VALID; $product_auction->product_auction_offer->update(true); } } $product_auction_offer->setOfferStatus(ProductAuctionOffer::STATUS_WINNER); // Change status to active/inactive return $product_auction_offer; } /** * * @param ProductAuctionOffer $product_auction_offer */ public function rejectWinner(ProductAuctionOffer $product_auction_offer) { $product_auction_offer->setOfferStatus(ProductAuctionOffer::STATUS_RETIRED); $product_auction = $product_auction_offer->getProductAuction(); $current_product_auction_offer = $product_auction->getProductAuctionOffer(); $this->dispatcher()->dispatch(new ProductAuctionEventReject($product_auction, $product_auction_offer, $current_product_auction_offer)); // Change status to active/inactive return $product_auction_offer; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (!class_exists('CoreModuleLink', false)) { class CoreModuleLink extends Link { public function getModuleControllerLink($controller, array $params = null, $ssl = null, $id_lang = null, $id_shop = null) { $context = Context::getContext(); if (empty($params)) $params = array(); return $this->getModuleLink($context->controller->module->name, $controller, $params, $ssl, $id_lang, $id_shop); } public function getPaginationLink($type, $id_object, $nb = false, $sort = false, $pagination = false, $array = false) { if (!$type) { $context = Context::getContext(); if ($context->controller && $context->controller instanceof ModuleFrontController) { $name = Dispatcher::getInstance()->getController(); $previous_get = $_GET; unset($_GET['module']); unset($_GET['fc']); $url = parent::getPaginationLink('ModuleController', $name, $nb, $sort, $pagination, $array); $_GET = $previous_get; return $url; } } return parent::getPaginationLink($type, $id_object, $nb, $sort, $pagination, $array); } } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_2377be3c2ad9b435ba277a73f0f1ca76'] = 'Fabricants'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_49fa2426b7903b3d4c89e2c1874d9346'] = 'Plus d\'informations sur'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_bf24faeb13210b5a703f3ccef792b000'] = 'Tous les fabricants'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_1c407c118b89fa6feaae6b0af5fc0970'] = 'Aucun autre fabricant de'; <file_sep>/** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author Magic Toolbox <<EMAIL>> * @copyright Copyright (c) 2015 Magic Toolbox <<EMAIL>>. All rights reserved * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ var magiczoomplusState = ''; $(document).ready(function() { if(typeof(window['display']) != 'undefined') { window['display_original'] = window['display']; window['display'] = function display(view) { if(typeof(MagicZoomPlus) != 'undefined' && magiczoomplusState != 'stopped') { magiczoomplusState = 'stopped'; MagicZoomPlus.stop(); } var r = window['display_original'].apply(window, arguments); if(typeof(MagicZoomPlus) != 'undefined' && magiczoomplusState != 'started') { magiczoomplusState = 'started'; MagicZoomPlus.start(); } return r; } } }); if($ && $.ajax) { (function($) { //NOTE: override default ajax method var ajax = $.ajax; $.ajax = function(url, options) { var settings = {}; if(typeof url === 'object') { settings = url; } else { settings = options || {}; } if(settings.type == 'GET' && settings.url == baseDir+'modules/blocklayered/blocklayered-ajax.php') { if(typeof(MagicZoomPlus) != 'undefined' && magiczoomplusState != 'stopped') { magiczoomplusState = 'stopped'; MagicZoomPlus.stop(); } settings.url = baseDir+'modules/magiczoomplus/blocklayered-ajax.php'; settings.successOriginal = settings.success; settings.success = function(result) { var r = settings.successOriginal.apply(settings, arguments); if(typeof(MagicZoomPlus) != 'undefined' && magiczoomplusState != 'started') { magiczoomplusState = 'started'; MagicZoomPlus.start(); } return r; }; } return ajax(url, options); } })($); } <file_sep><?php require_once 'RequestResultBase.php'; /** * This class represents the result of a getAdvertisementClickUrl query. * * @package prediggo4php * @subpackage types * * @author Stef */ class GetAdvertisementClickUrlResult extends RequestResultBase { private $clickUrl = ""; /** * @param string $clickUrl */ public function setClickUrl($clickUrl) { $this->clickUrl = $clickUrl; } /** * Returns the URL corresponding to the Ad * @return string */ public function getClickUrl() { return $this->clickUrl; } } <file_sep>{ //rajouter par <NAME>**************************************************** public static $classInModule = array(); public static function getModuleNameFromClass($currentClass) { global $cookie; // Module can now define AdminTab keeping the module translations method, // i.e. in modules/[module name]/[iso_code].php if (!isset(self::$classInModule[$currentClass])) { global $_MODULES; $_MODULE = array(); $reflectionClass = new ReflectionClass($currentClass); $filePath = realpath($reflectionClass->getFileName()); $realpathModuleDir = realpath(_PS_MODULE_DIR_); if (substr(realpath($filePath), 0, strlen($realpathModuleDir)) == $realpathModuleDir) { self::$classInModule[$currentClass] = substr(dirname($filePath), strlen($realpathModuleDir)+1); $id_lang = (!isset($cookie) OR !is_object($cookie)) ? (int)(Configuration::get('PS_LANG_DEFAULT')) : (int)($cookie->id_lang); $file = _PS_MODULE_DIR_.self::$classInModule[$currentClass].'/'.Language::getIsoById($id_lang).'.php'; if (Tools::file_exists_cache($file) AND include_once($file)) $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE; } else self::$classInModule[$currentClass] = false; } // return name of the module, or false return self::$classInModule[$currentClass]; } protected static $l_cache = array(); public static function findTranslation($name, $string, $source) { global $_MODULES; $cache_key = $name . '|' . $string . '|' . $source; if (!isset(self::$l_cache[$cache_key])) { if (!is_array($_MODULES)) return str_replace('"', '&quot;', $string); // set array key to lowercase for 1.3 compatibility $_MODULES = array_change_key_case($_MODULES); $currentKey = '<{'.strtolower($name).'}'.strtolower(_THEME_NAME_).'>'.strtolower($source).'_'.md5($string); $defaultKey = '<{'.strtolower($name).'}prestashop>'.strtolower($source).'_'.md5($string); if (isset($_MODULES[$currentKey])) $ret = stripslashes($_MODULES[$currentKey]); elseif (isset($_MODULES[Tools::strtolower($currentKey)])) $ret = stripslashes($_MODULES[Tools::strtolower($currentKey)]); elseif (isset($_MODULES[$defaultKey])) $ret = stripslashes($_MODULES[$defaultKey]); elseif (isset($_MODULES[Tools::strtolower($defaultKey)])) $ret = stripslashes($_MODULES[Tools::strtolower($defaultKey)]); else $ret = stripslashes($string); self::$l_cache[$cache_key] = str_replace('"', '&quot;', $ret); } return self::$l_cache[$cache_key]; } //fin de rajout par G.PREVEAUX<file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionBidEnglish', false)) return; class ProductAuctionBidEnglish extends AbstractProductAuctionBid { /** * * @return ProductAuctionBidResultEnglish */ public function calculate() { $is_winner = $this->isCurrentWinner(); $has_proxy_bidding = $this->hasProxyBidding(); $bid_price = $this->getBidPrice(); $bid_step = $this->getBidStep(); $minimal_price = $this->getMinimalPrice(); $current_price = $this->getCurrentPrice(); $highest_price = $this->getHighestPrice(); $next_price = 0; $result = AbstractProductAuctionBidResult::INVALID; if ($bid_price > $highest_price) { $result = AbstractProductAuctionBidResult::VALID; $next_price = $has_proxy_bidding ? $highest_price + $bid_step : $bid_price; if ($is_winner) $next_price = $current_price; if ($next_price > $bid_price) $next_price = $bid_price; if ($bid_price >= $minimal_price) { $result = AbstractProductAuctionBidResult::LEADER; if ($next_price < $minimal_price) $next_price = $minimal_price; } else $result = AbstractProductAuctionBidResult::LEADER_MIN_NOT_REACHED; } else { $result = AbstractProductAuctionBidResult::VALID_TOO_LOW; if ($bid_price == $highest_price) $result = AbstractProductAuctionBidResult::VALID_ALREADY_EXIST; $next_price = $bid_price + $bid_step; if ($is_winner) { $result = AbstractProductAuctionBidResult::VALID_TOO_LOW; $next_price = $current_price; } if ($next_price > $highest_price) $next_price = $highest_price; } $bid_result = $this->getBidResult(); $bid_result->setResult($result); $bid_result->setBidPrice($bid_price); $bid_result->setPreviousPrice($current_price); $bid_result->setCurrentPrice($next_price); return $bid_result; } /** * * @return ProductAuctionBidResultEnglish */ protected function getBidResult() { return new ProductAuctionBidResultEnglish($this->getProductAuction(), $this->getCustomer()); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsEmailSender', false)) return; class AuctionsEmailSender { public static function sendEmailEnglish($tpl, $lang_id, $vars, $r_email, $r_name, $s_email, $s_name, $mail_dir) { switch ($tpl) { case 'english_backoffice_finished': // $this->l('Auction ended'); $subject = self::l('Auction ended'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_backoffice_new_offer': // $this->l('New offer on auction'); $subject = self::l('New offer on auction'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_customer_leader': // $this->l('You have put the highest offer'); $subject = self::l('You have put the highest offer'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_customer_outbid': // $this->l('Someone put higher offer'); $subject = self::l('Someone put higher offer'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_customer_new_offer': // $this->l('New offer on auction'); $subject = self::l('New offer on auction'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_customer_won': // $this->l('You have won auction'); $subject = self::l('You have won auction'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_customer_not_won': // $this->l('Auction ended'); $subject = self::l('Auction ended'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_customer_finished': // $this->l('Auction ended'); $subject = self::l('Auction ended'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_customer_accept': // $this->l('Your offer has been accepted'); $subject = self::l('Your offer has been accepted'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_customer_remind': // $this->l('Auction is waiting for checkout'); $subject = self::l('Auction is waiting for checkout'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); case 'english_customer_restart': // $this->l('Auction has been restarted'); $subject = self::l('Auction has been restarted'); return Mail::Send($lang_id, $tpl, $subject, $vars, $r_email, $r_name, $s_email, $s_name, null, null, $mail_dir); } return false; } /** * Get translation for a given module text * * @param string $string String to translate * @param boolean|string $specific filename to use in translation key * @return string Translation */ public static function l($string, $specific = false) { return Translate::getModuleTranslation('auctions', $string, $specific ? $specific : __CLASS__); } } <file_sep><?php require_once 'RequestParamBase.php'; /** * Parameter class for getAdvertisementClickUrl queries.. * * @package prediggo4php * @subpackage types * * @author Stef */ class GetAdvertisementClickUrlParam extends RequestParamBase { protected $clickId = ""; /** * Sets the ID of the clicked Ad * @param string $clickId */ public function setClickId($clickId) { $this->clickId = $clickId; } /** * Gets the ID of the clicked Ad * @return string */ public function getClickId() { return $this->clickId; } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_12641546686fe11aaeb3b3c43a18c1b3'] = 'Ihr Warenkorb'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_7fc68677a16caa0f02826182468617e6'] = 'Warenkorb:'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_f5bf48aa40cad7891eb709fcf1fde128'] = 'produkt'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_86024cad1e83101d97359d7351051156'] = 'produkte'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(leer)'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_a0623b78a5f2cfe415d9dbbd4428ea40'] = 'Ihr Konto'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_83218ac34c1834c26781fe4bde918ee4'] = 'Willkommen'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4b877ba8588b19f1b278510bf2b57ebb'] = 'Melden Sie mich'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4394c8d8e63c470de62ced3ae85de5ae'] = 'Ausloggen'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_bffe9a3c9a7e00ba00a11749e022d911'] = 'Sair'; <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_12641546686fe11aaeb3b3c43a18c1b3'] = 'Votre Panier'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_7fc68677a16caa0f02826182468617e6'] = 'Panier:'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_f5bf48aa40cad7891eb709fcf1fde128'] = 'produit'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_86024cad1e83101d97359d7351051156'] = 'produits'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(Vide)'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_a0623b78a5f2cfe415d9dbbd4428ea40'] = 'Votre compte'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_83218ac34c1834c26781fe4bde918ee4'] = 'Accueil'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4b877ba8588b19f1b278510bf2b57ebb'] = 'Me déconnecter'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4394c8d8e63c470de62ced3ae85de5ae'] = 'Déconnexion'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_bffe9a3c9a7e00ba00a11749e022d911'] = 'Identifiez-vous'; <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_12641546686fe11aaeb3b3c43a18c1b3'] = 'Seu Carrinho de Compras'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_7fc68677a16caa0f02826182468617e6'] = 'Carrinho de Compras:'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_f5bf48aa40cad7891eb709fcf1fde128'] = 'produto'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_86024cad1e83101d97359d7351051156'] = 'produtos'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(vazio)'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_a0623b78a5f2cfe415d9dbbd4428ea40'] = 'Sua Conta'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_83218ac34c1834c26781fe4bde918ee4'] = 'Bem-vindo'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4b877ba8588b19f1b278510bf2b57ebb'] = 'Ligar-me para fora'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4394c8d8e63c470de62ced3ae85de5ae'] = 'Sair'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_bffe9a3c9a7e00ba00a11749e022d911'] = 'Entrar'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionDataManager', false)) return; class ProductAuctionDataManager { /** * * @param Product $product * @return ProductAuction */ public static function getByProduct(Product $product, $language_id = null, $shop_id = null, $enabled_only = true) { $product_auction = null; $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $query = ' SELECT '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE pa.id_product = '.(int)$product->id.' '.($enabled_only ? ' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED : null).' '; $result = Db::getInstance()->executeS($query); if (!empty($result)) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); CoreModuleTools::hydrateObject($product_auction, $result, $language_id); $product_auction->setProduct($product); CoreModuleTools::hydrateObject($product_auction->specific_price, $result, $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, $result, $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, $result, $language_id); } return $product_auction; } /** * * @param integer $product_id * @param string $language_id * @param string $shop_id * @return ProductAuction */ public static function getByProductId($product_id, $language_id = null, $shop_id = null, $enabled_only = true) { $product_auction = null; $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $query = ' SELECT '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE pa.id_product = '.(int)$product_id.' '.($enabled_only ? ' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED : null).' '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' '; $result = Db::getInstance()->executeS($query); if (!empty($result)) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); CoreModuleTools::hydrateObject($product_auction, $result, $language_id); CoreModuleTools::hydrateObject($product_auction->product, $result, $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, $result, $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, $result, $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, $result, $language_id); } return $product_auction; } /** * * @return ProductAuction[] */ public static function getCollectionByProductIds(array $product_ids, $limit = null, $language_id = null, $shop_id = null) { if (empty($product_ids)) return array(); $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $query = ' SELECT i.id_image, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON pa.`id_product` = cp.`id_product` WHERE pa.`id_product` IN ('.implode(',', array_map('intval', $product_ids)).') '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' '.($limit ? 'LIMIT '.(int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) { foreach ($result as $data_row) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); $product_auction->id_image = !empty($data_row['id_image']) ? $data_row['id_image'] : null; CoreModuleTools::hydrateObject($product_auction, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, array( $data_row ), $language_id); $product_auction_collection[] = $product_auction; } } return $product_auction_collection; } /** * * @return ProductAuction[] */ public static function getCollectionByCategory($category_id, $limit = null, $language_id = null, $shop_id = null) { if (empty($category_id)) return array(); $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $query = ' SELECT i.id_image, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON pa.`id_product` = cp.`id_product` WHERE cp.`id_category` = '.(int)$category_id.' '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' '.($limit ? 'LIMIT '.(int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) { foreach ($result as $data_row) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); $product_auction->id_image = !empty($data_row['id_image']) ? $data_row['id_image'] : null; CoreModuleTools::hydrateObject($product_auction, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, array( $data_row ), $language_id); $product_auction_collection[] = $product_auction; } } return $product_auction_collection; } /** * * @return ProductAuction[] */ public static function getCollectionByStartingTime($threshold, $limit = null, $language_id = null, $shop_id = null) { $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $current_datetime = date('Y-m-d H:i:s'); if ($threshold > 0) $threshold = date('Y-m-d H:i:s', time() - (int)$threshold); else $threshold = null; $query = ' SELECT i.id_image, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE 1 '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' AND pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` <= "'.$current_datetime.'" '.($threshold ? 'AND pa.`from` > "'.$threshold.'"' : null).' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' ORDER BY pa.from DESC '.($limit ? 'LIMIT '.(int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) foreach ($result as $data_row) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); $product_auction->id_image = !empty($data_row['id_image']) ? $data_row['id_image'] : null; CoreModuleTools::hydrateObject($product_auction, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, array( $data_row ), $language_id); $product_auction_collection[] = $product_auction; } return $product_auction_collection; } /** * * @return ProductAuction[] */ public static function getCollectionByEndingTime($threshold, $limit = null, $language_id = null, $shop_id = null) { $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $current_datetime = date('Y-m-d H:i:s'); if ($threshold > 0) $threshold = date('Y-m-d H:i:s', time() + (int)$threshold); else $threshold = null; $query = ' SELECT i.id_image, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE 1 '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' AND pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` <= "'.$current_datetime.'" AND pa.`to` > "'.$current_datetime.'" '.($threshold ? 'AND pa.`to` <= "'.$threshold.'"' : null).' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' ORDER BY pa.to ASC '.($limit ? 'LIMIT '.(int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) foreach ($result as $data_row) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); $product_auction->id_image = !empty($data_row['id_image']) ? $data_row['id_image'] : null; CoreModuleTools::hydrateObject($product_auction, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, array( $data_row ), $language_id); $product_auction_collection[] = $product_auction; } return $product_auction_collection; } /** * * @return ProductAuction[] */ public static function getCollectionByPopularity($threshold, $limit = null, $language_id = null, $shop_id = null) { $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $current_datetime = date('Y-m-d H:i:s'); $query = ' SELECT i.id_image, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE 1 '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' AND pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` <= "'.$current_datetime.'" AND pa.`to` > "'.$current_datetime.'" '.($threshold ? 'AND pa.`offers` > "'.(int)$threshold.'"' : null).' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' ORDER BY pa.offers DESC, pa.to ASC '.($limit ? 'LIMIT '.(int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) foreach ($result as $data_row) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); $product_auction->id_image = !empty($data_row['id_image']) ? $data_row['id_image'] : null; CoreModuleTools::hydrateObject($product_auction, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, array( $data_row ), $language_id); $product_auction_collection[] = $product_auction; } return $product_auction_collection; } /** * * @return integer */ public static function getCurrentAuctionsCountByCustomer($customer_id) { $current_datetime = date('Y-m-d H:i:s'); $query = ' SELECT COUNT(pa.id_product_auction) FROM `'._DB_PREFIX_.'product_auction` pa INNER JOIN ( SELECT `id_product_auction`, CASE WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE `status` END AS `status` FROM `'._DB_PREFIX_.'product_auction` ) st ON (pa.`id_product_auction` = st.`id_product_auction`) INNER JOIN ( SELECT DISTINCT id_product_auction FROM `'._DB_PREFIX_.'product_auction_offer` WHERE id_customer = '.(int)$customer_id.' AND status != '.ProductAuctionOffer::STATUS_INVALID.' ) ccpa ON (pa.id_product_auction = ccpa.id_product_auction) WHERE 1 AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND st.status IN ('.ProductAuction::STATUS_RUNNING.') '; return (int)Db::getInstance()->getValue($query); } /** * * @return integer */ public static function getWonAuctionsCountByCustomer($customer_id) { $current_datetime = date('Y-m-d H:i:s'); $query = ' SELECT COUNT(pa.id_product_auction) FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) INNER JOIN ( SELECT `id_product_auction`, CASE WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE `status` END AS `status` FROM `'._DB_PREFIX_.'product_auction` ) st ON (pa.`id_product_auction` = st.`id_product_auction`) WHERE pao.id_customer = '.(int)$customer_id.' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND pao.status IN ('.ProductAuctionOffer::STATUS_VALID.', '.ProductAuctionOffer::STATUS_WINNER.') AND st.status IN ('.ProductAuction::STATUS_FINISHED.', '.ProductAuction::STATUS_CLOSED.') '; return (int)Db::getInstance()->getValue($query); } /** * * @return integer */ public static function getClosedAuctionsCountByCustomer($customer_id) { $current_datetime = date('Y-m-d H:i:s'); $query = ' SELECT COUNT(pa.id_product_auction) FROM `'._DB_PREFIX_.'product_auction` pa INNER JOIN ( SELECT `id_product_auction`, CASE WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE `status` END AS `status` FROM `'._DB_PREFIX_.'product_auction` ) st ON (pa.`id_product_auction` = st.`id_product_auction`) INNER JOIN ( SELECT DISTINCT id_product_auction FROM `'._DB_PREFIX_.'product_auction_offer` WHERE id_customer = '.(int)$customer_id.' AND status != '.ProductAuctionOffer::STATUS_INVALID.' ) ccpa ON (pa.id_product_auction = ccpa.id_product_auction) WHERE 1 AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND st.status IN ('.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.', '.ProductAuction::STATUS_CLOSED.') '; return (int)Db::getInstance()->getValue($query); } /** * * @return integer */ public static function getWatchingAuctionsCountByCustomer($customer_id) { $query = ' SELECT COUNT(pa.id_product_auction) FROM `'._DB_PREFIX_.'product_auction` pa INNER JOIN `'._DB_PREFIX_.'product_auction_subscriptions` pas ON (pa.id_product_auction = pas.id_product_auction) WHERE pas.id_customer = '.(int)$customer_id.' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' '; return (int)Db::getInstance()->getValue($query); } /** * * @return integer */ public static function getWatchingCustomersCountByAuction($auction_id) { $query = ' SELECT COUNT(pa.id_product_auction) FROM `'._DB_PREFIX_.'product_auction` pa INNER JOIN `'._DB_PREFIX_.'product_auction_subscriptions` pas ON (pa.id_product_auction = pas.id_product_auction) WHERE pas.id_product_auction = '.(int)$auction_id.' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' '; return (int)Db::getInstance()->getValue($query); } /** * * @return ProductAuction[] */ public static function getCurrentAuctionsCollectionByCustomer($customer_id, $limit = null, $page = null, $language_id = null, $shop_id = null) { $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $current_datetime = date('Y-m-d H:i:s'); if ($page < 1) $page = 1; $query = ' SELECT i.id_image, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).', CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status` FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) INNER JOIN ( SELECT DISTINCT id_product_auction FROM `'._DB_PREFIX_.'product_auction_offer` WHERE id_customer = '.(int)$customer_id.' AND status != '.ProductAuctionOffer::STATUS_INVALID.' ) ccpa ON (pa.id_product_auction = ccpa.id_product_auction) WHERE 1 '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' HAVING auction_status IN ('.ProductAuction::STATUS_RUNNING.') ORDER BY pa.to ASC, pa.id_product_auction ASC '.($limit ? 'LIMIT '.(int)$limit : null).' '.($limit && $page ? 'OFFSET '.((int)$page - 1) * (int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) foreach ($result as $data_row) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); $product_auction->id_image = !empty($data_row['id_image']) ? $data_row['id_image'] : null; CoreModuleTools::hydrateObject($product_auction, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, array( $data_row ), $language_id); $product_auction_collection[] = $product_auction; } return $product_auction_collection; } /** * * @return ProductAuction[] */ public static function getWonAuctionsCollectionByCustomer($customer_id, $limit = null, $page = null, $language_id = null, $shop_id = null) { $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $current_datetime = date('Y-m-d H:i:s'); if ($page < 1) $page = 1; $query = ' SELECT i.id_image, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).', CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status` FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE pao.id_customer = '.(int)$customer_id.' '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND pao.status IN ('.ProductAuctionOffer::STATUS_VALID.', '.ProductAuctionOffer::STATUS_WINNER.') HAVING auction_status IN ('.ProductAuction::STATUS_FINISHED.', '.ProductAuction::STATUS_CLOSED.') ORDER BY IF(`auction_status` = '.ProductAuction::STATUS_FINISHED.', 0, `auction_status`) ASC, pa.to DESC, pa.id_product ASC '.($limit ? 'LIMIT '.(int)$limit : null).' '.($limit && $page ? 'OFFSET '.((int)$page - 1) * (int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) foreach ($result as $data_row) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); $product_auction->id_image = !empty($data_row['id_image']) ? $data_row['id_image'] : null; CoreModuleTools::hydrateObject($product_auction, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, array( $data_row ), $language_id); $product_auction_collection[] = $product_auction; } return $product_auction_collection; } /** * * @return ProductAuction[] */ public static function getClosedAuctionsCollectionByCustomer($customer_id, $limit = null, $page = null, $language_id = null, $shop_id = null) { $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $current_datetime = date('Y-m-d H:i:s'); if ($page < 1) $page = 1; $query = ' SELECT i.id_image, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).', CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status` FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) INNER JOIN ( SELECT DISTINCT id_product_auction FROM `'._DB_PREFIX_.'product_auction_offer` WHERE id_customer = '.(int)$customer_id.' AND status != '.ProductAuctionOffer::STATUS_INVALID.' ) ccpa ON (pa.id_product_auction = ccpa.id_product_auction) WHERE 1 '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' HAVING auction_status IN ('.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.', '.ProductAuction::STATUS_CLOSED.') '.($limit ? 'LIMIT '.(int)$limit : null).' '.($limit && $page ? 'OFFSET '.((int)$page - 1) * (int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) foreach ($result as $data_row) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); $product_auction->id_image = !empty($data_row['id_image']) ? $data_row['id_image'] : null; CoreModuleTools::hydrateObject($product_auction, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, array( $data_row ), $language_id); $product_auction_collection[] = $product_auction; } return $product_auction_collection; } /** * * @return ProductAuction[] */ public static function getWatchingAuctionsCollectionByCustomer($customer_id, $limit = null, $page = null, $language_id = null, $shop_id = null) { $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $current_datetime = date('Y-m-d H:i:s'); if ($page < 1) $page = 1; $query = ' SELECT i.id_image, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).', CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status` FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) INNER JOIN `'._DB_PREFIX_.'product_auction_subscriptions` pas ON (pa.id_product_auction = pas.id_product_auction) WHERE pas.id_customer = '.(int)$customer_id.' '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' ORDER BY IF(`auction_status` = '.ProductAuction::STATUS_FINISHED.', 0, `auction_status`) ASC, pa.to ASC, pa.id_product ASC '.($limit ? 'LIMIT '.(int)$limit : null).' '.($limit && $page ? 'OFFSET '.((int)$page - 1) * (int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) foreach ($result as $data_row) { $product_auction = new ProductAuction(null, true, $language_id, $shop_id); $product_auction->id_image = !empty($data_row['id_image']) ? $data_row['id_image'] : null; CoreModuleTools::hydrateObject($product_auction, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->specific_price, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer, array( $data_row ), $language_id); CoreModuleTools::hydrateObject($product_auction->product_auction_offer->customer, array( $data_row ), $language_id); $product_auction_collection[] = $product_auction; } return $product_auction_collection; } /** * * @return integer */ public static function getAuctionsToProcessCount() { $current_datetime = date('Y-m-d H:i:s'); $query = ' SELECT COUNT(pa.id_product_auction) FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN ( SELECT `id_product_auction`, CASE WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE `status` END AS `status` FROM `'._DB_PREFIX_.'product_auction` ) st ON (pa.`id_product_auction` = st.`id_product_auction`) WHERE st.status IN ('.ProductAuction::STATUS_PROCESSING.') AND pa.from < "'.$current_datetime.'" AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' '; return (int)Db::getInstance()->getValue($query); } /** * * @return ProductAuction[] */ public static function getAuctionsToProcessCollection($limit = null, $page = null, $language_id = null) { $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $specific_price_fields = CoreModuleTools::convertFields(SpecificPrice::$definition, array( 'prefix' => 'sp' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $current_datetime = date('Y-m-d H:i:s'); if ($page < 1) $page = 1; $query = ' SELECT '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $specific_price_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).', CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status` FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (pa.id_specific_price = sp.id_specific_price) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND pa.from < "'.$current_datetime.'" '.($language_id ? 'AND pl.`id_lang` ='.(int)$language_id : null).' HAVING auction_status IN ('.ProductAuction::STATUS_PROCESSING.') ORDER BY pa.to ASC, pa.id_product ASC '.($limit ? 'LIMIT '.(int)$limit : null).' '.($limit && $page ? 'OFFSET '.((int)$page - 1) * (int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_collection = array(); if (!empty($result)) { $classes = array( 'ProductAuction', 'Product', 'SpecificPrice', 'ProductAuctionOffer', 'Customer' ); $result = CoreModuleTools::hydrateCollection($classes, $result, $language_id); foreach ($result['ProductAuction'] as $product_auction) { if (isset($result['Product'][$product_auction->id_product])) $product_auction->product = $result['Product'][$product_auction->id_product]; if (isset($result['SpecificPrice'][$product_auction->id_specific_price])) $product_auction->specific_price = $result['SpecificPrice'][$product_auction->id_specific_price]; if (isset($result['ProductAuctionOffer'][$product_auction->id_product_auction_offer])) { $product_auction->product_auction_offer = $result['ProductAuctionOffer'][$product_auction->id_product_auction_offer]; if (isset($result['Customer'][$product_auction->product_auction_offer->id_customer])) $product_auction->product_auction_offer->customer = $result['Customer'][$product_auction->product_auction_offer->id_customer]; } $product_auction_collection[] = $product_auction; } } return $product_auction_collection; } /** * * @param array $product_ids */ public static function closeProductAuctionsWithProductIds($product_ids) { if (empty($product_ids)) return; return Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.ProductAuction::$definition['table'].'` SET status = '.ProductAuction::STATUS_CLOSED.' WHERE `id_product` IN('.implode(',', array_map('intval', $product_ids)).') AND `status` = '.ProductAuction::STATUS_FINISHED); } /** * * @param array $product_ids */ public static function finishProductAuctionsWithProductIds($product_ids) { if (empty($product_ids)) return; return Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.ProductAuction::$definition['table'].'` SET status = '.ProductAuction::STATUS_PROCESSING.' WHERE `id_product` IN('.implode(',', array_map('intval', $product_ids)).') AND `status` NOT IN ('.ProductAuction::STATUS_FINISHED.','.ProductAuction::STATUS_CLOSED.')'); } } <file_sep><?php $all_error = array ( '9750d3a87066861bc8827ecfd9e45e5d' => array ( 'msg' => 'Buy It Now price may not exceed £2,500.00 for items that require immediate payment. Please change the price or turn off the immediate payment requirement.<br />£2,500.00', 'products' => array ( 0 => 'Ark Desk Upcycled 1930 Fairground Ride', ), ), 'ef437a9a8fd549afcc3715a3c3ca115b' => array ( 'msg' => 'The quantity must be a valid number greater than 0.<br />To require immediate payment, you must specify a Buy It Now price.<br />Required minimum number of photos: 1. For listings in this category, we recommend uploading 3 or more photos, which may increase your chances of selling by 9%. (Percentage is based on the rates of selling with varying number of images in this category. Actual results may differ and sale is not guaranteed.)<br />Required minimum number of photos: 1. For this category, the ideal number is at least 3. ', 'products' => array ( 0 => 'New York Loft Reclaimed Office Desk', ), ), 'ff095b02660bc7086960807aed0fb4b1' => array ( 'msg' => 'The quantity must be a valid number greater than 0.<br />To require immediate payment, you must specify a Buy It Now price.', 'products' => array ( 0 => 'New York Loft Industrial Chest of Drawers', ), ), '4863dda21dddfd501b15dd38ead309b6' => array ( 'msg' => 'Please enter a valid starting price for your item (eg GBP 0.99).<br />GBP 0.99', 'products' => array ( 0 => 'Industrial Trolley Cart Coffee Table', ), ), '667516d379649388ac8c990dd08f1033' => array ( 'msg' => 'The quantity must be a valid number greater than 0.', 'products' => array ( 0 => 'New York Loft Reclaimed Office Desk', ), ), '5fc0403d24817aedc05506bc22946574' => array ( 'msg' => 'At least one of the variations associated with this listing must have a quantity greater than 0.<br />To require immediate payment, you must specify a Buy It Now price.<br />Variation is required for a listing that previously had variations.', 'products' => array ( 0 => 'Drum Art Side Table', ), ), '0d7af58bb375a5c1edc71e54e7faaa2d' => array ( 'msg' => 'The quantity must be a valid number greater than 0.<br />Required minimum number of photos: 1. For listings in this category, we recommend uploading 3 or more photos, which may increase your chances of selling by 9%. (Percentage is based on the rates of selling with varying number of images in this category. Actual results may differ and sale is not guaranteed.)<br />Required minimum number of photos: 1. For this category, the ideal number is at least 3. ', 'products' => array ( 0 => 'Tolix Industrial dining chairs', ), ), '1f10e77388e5c6f5b523bf538c93fe11' => array ( 'msg' => 'Required minimum number of photos: 1. For listings in this category, we recommend uploading 3 or more photos, which may increase your chances of selling by 9%. (Percentage is based on the rates of selling with varying number of images in this category. Actual results may differ and sale is not guaranteed.)<br />Required minimum number of photos: 1. For this category, the ideal number is at least 3. ', 'products' => array ( 0 => 'Mandela Square Stool', ), ), '1032c59e0af27a41b2ccd3260ddec962' => array ( 'msg' => 'Please enter a valid starting price for your item (eg GBP 0.99).<br />GBP 0.99<br />Required minimum number of photos: 1. For listings in this category, we recommend uploading 3 or more photos, which may increase your chances of selling by 9%. (Percentage is based on the rates of selling with varying number of images in this category. Actual results may differ and sale is not guaranteed.)<br />Required minimum number of photos: 1. For this category, the ideal number is at least 3. ', 'products' => array ( 0 => 'Mandela Cube Stool', ), ), 'e0079906fac40dce17bacaf2ab6478aa' => array ( 'msg' => 'The auction has already been closed.', 'products' => array ( 0 => 'Vintage Style Cafe Chair ', ), ), 'e4dc5928ee9400077589e57fc9961dda' => array ( 'msg' => 'This listing is a duplicate of your item: vintage retro industrial designer furniture (271761423815). Under the Duplicate Listing policy, sellers can\'t have multiple Fixed Price listings, multiple Auction-style (with the Buy It Now option) listings, or in both the Fixed Price and Auction-style (with the Buy It Now option) listings for identical items at the same time. We recommend you create a multiple quantity fixed price listing to sell identical items.<br />vintage retro industrial designer furniture', 'products' => array ( 0 => 'Tolix Industrial dining chairs', ), ), '80211a95a93161265fa3240a1614ca5f' => array ( 'msg' => 'Your application has exceeded usage limit on this call, please make call to GetAPIAccessRules to check your call usage.', 'products' => array ( 0 => 'Ark Reclaimed Coffee Table', ), ), ); $itemConditionError = false; ?><file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_2377be3c2ad9b435ba277a73f0f1ca76'] = 'Fabricantes'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_49fa2426b7903b3d4c89e2c1874d9346'] = 'Más información sobre la'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_bf24faeb13210b5a703f3ccef792b000'] = 'Todos los fabricantes'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_1c407c118b89fa6feaae6b0af5fc0970'] = 'Ningún fabricante'; <file_sep><?php /** * admin.conf.php file defines all needed constants and variables for admin context */ /** include common conf **/ require_once(dirname(__FILE__) . '/common.conf.php'); /** defines modules support mail uses => **/ define('_FPC_MAIL', 'http://www.businesstech.fr/en/contact-us'); /** defines admin library path uses => to include class files **/ define('_FPC_PATH_LIB_ADMIN', _FPC_PATH_LIB . 'admin/'); /** defines constant of connector path tpl uses => to set good absolute path **/ define('_FPC_TPL_CONNECTOR_PATH', 'connectors-form/'); /** defines admin logs path uses => to write log files **/ define('_FPC_PATH_LOGS', _FPC_PATH_ROOT . 'logs/'); /** defines admin path tpl uses => to set good absolute path **/ define('_FPC_TPL_ADMIN_PATH', 'admin/'); /** defines body tpl uses => with display admin interface **/ define('_FPC_TPL_BODY', 'body.tpl'); /** defines basic settings tpl uses => with display admin interface **/ define('_FPC_TPL_BASIC_SETTINGS', 'basic-settings.tpl'); /** defines connectors settings tpl uses => with display admin interface **/ define('_FPC_TPL_CONNECTOR_SETTINGS', 'connector-settings.tpl'); /** defines hook settings tpl uses => with display admin interface **/ define('_FPC_TPL_HOOK_SETTINGS', 'hook-settings.tpl'); /** defines hook form tpl uses => with display admin interface **/ define('_FPC_TPL_HOOK_FORM', 'hook-form.tpl'); /** defines system health settings tpl uses => with display admin interface **/ define('_FPC_TPL_SYS_HEALTH_SETTINGS', 'system-health-settings.tpl'); /** defines curl ssl tpl uses => with display admin interface **/ define('_FPC_TPL_CURL_SSL', 'curl-ssl.tpl'); /** defines constant of body tpl uses => in display admin interface with connector form **/ define('_FPC_TPL_PREREQUISITES_CHECK_SETTINGS', 'prerequisites-check.tpl'); /** defines constant of body tpl uses => in display admin interface with connector form **/ define('_FPC_TPL_CONNECTOR_BODY', _FPC_TPL_CONNECTOR_PATH . 'body.tpl'); /** defines constant for external BT API URL uses => with display admin interface **/ define('_FPC_BT_API_MAIN_URL', '//api.businesstech.fr/prestashop-modules/'); /** defines constant for external BT API URL uses => with display admin interface **/ define('_FPC_BT_FAQ_MAIN_URL', 'http://faq.businesstech.fr/'); /** defines variable for sql update uses => with admin **/ $GLOBALS[_FPC_MODULE_NAME . '_SQL_UPDATE'] = array( 'table' => array( // 'voucher' => _GSR_VOUCHER_SQL_FILE, ), 'field' => array( // 'RTG_LANG_ID' => array('table' => 'rating', 'file' => _GSR_LANG_REVIEW_SQL_FILE), ) ); /** defines variable for setting all request params uses => with admin interface **/ $GLOBALS[_FPC_MODULE_NAME . '_REQUEST_PARAMS'] = array( 'basic' => array('action' => 'update', 'type' => 'basic'), 'connectorForm' => array('action' => 'display', 'type' => 'connectorForm'), 'connector' => array('action' => 'update', 'type' => 'connector'), 'hook' => array('action' => 'update', 'type' => 'hook'), 'hookForm' => array('action' => 'display', 'type' => 'hookForm'), 'curlssl' => array('action' => 'display', 'type' => 'curlssl'), );<file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_34c869c542dee932ef8cd96d2f91cae6'] = 'Nos magasins'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_a82be0f551b8708bc08eb33cd9ded0cf'] = 'Informations'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_d1aa22a3126f04664e0fe3f598994014'] = 'Promotions'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_9ff0635f5737513b1a6f559ac2bff745'] = 'Nouveaux produits'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_3cb29f0ccc5fd220a97df89dafe46290'] = 'Meilleures ventes'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_02d4482d332e1aef3437cd61c9bcc624'] = 'Contactez-nous'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_e1da49db34b0bdfdddaba2ad6552f848'] = 'plan du site'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_5813ce0ec7196c492c97596718f71969'] = 'Plan du site'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_7a52e36bf4a1caa031c75a742fb9927a'] = 'Propulsé par'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuction', false)) return; class ProductAuction extends ProductAuctionObjectModel { const AUCTION_DISABLED = 0; const AUCTION_ENABLED = 1; const STATUS_IDLE = 1; const STATUS_RUNNING = 2; const STATUS_PROCESSING = 3; const STATUS_FINISHED = 4; const STATUS_CLOSED = 5; const ADD = 'add'; const REMOVE = 'remove'; const REMOVE_BULK = 'remove_bulk'; const CLEAR = 'clear'; /** * @var integer ProductAuction id */ public $id_product_auction; /** * @var integer ProductAuctionOffer id */ public $id_product_auction_offer; /** * @var integer SpecificPrice id */ public $id_specific_price; /** * @var integer Product id */ public $id_product; /** * @var integer ProductAuctionType id */ public $id_product_auction_type; /** * @var float Initial Price in euros */ public $initial_price = 0.010000; /** * @var float Reserve price in euros */ public $minimal_price = 0.000000; /** * @var float Buy now price in euros */ public $buynow_price = 0.000000; /** * @var boolean ProductAuction show buy now price after any offer was placed */ public $buynow_after_bid = 1; /** * @var boolean ProductAuction show buy now price */ public $buynow_visible = 1; /** * @var string Bidding increment rules */ public $bidding_increment = '[{"from":"0.000000","to":"0.000000","step":"0.010000"}]'; /** * @var boolean Auction proxy biddind */ public $proxy_bidding = 0; /** * @var string Auction extend time threshold */ public $extend_threshold; /** * @var string Auction extend time step */ public $extend_by; /** * @var string Auction start date */ public $from; /** * @var string Auction finish date */ public $to; /** * @var boolean ProductAuction offers */ public $offers = 0; /** * @var boolean ProductAuction enable auction */ public $enable_auction = 0; /** * @var boolean ProductAuction status */ public $status = 2; /** * @var string Object creation date */ public $date_add; /** * @var string Object last modification date */ public $date_upd; public static $definition = array( 'table' => 'product_auction', 'primary' => 'id_product_auction', 'multilang' => false, 'multilang_shop' => false, 'fields' => array( 'id_product_auction_offer' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isUnsignedId' ), 'id_product_auction_type' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true, ), 'id_product' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true, ), 'id_specific_price' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isUnsignedId' ), 'initial_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true, ), 'minimal_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'buynow_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'buynow_after_bid' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'buynow_visible' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'bidding_increment' => array( 'type' => self::TYPE_STRING, 'validate' => 'isString' ), 'proxy_bidding' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'extend_threshold' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'extend_by' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'from' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat', ), 'to' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat', ), 'offers' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'enable_auction' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'status' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isInt' ), 'date_add' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ), 'date_upd' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ) ) ); /** * * @var Product */ public $product; /** * * @var SpecificPrice */ public $specific_price; /** * * @var ProductAuctionOffer */ public $product_auction_offer; /** * * @var ProductAuctionOffer */ public $current_customer_offer; /** * * @var integer */ public $id_image; public function __construct($id = null, $full = false, $id_lang = null, $id_shop = null) { parent::__construct($id, null, $id_shop); $this->setSpecificPrice(new SpecificPrice($this->id_specific_price, null, $id_shop)); if ($full) { $this->setProduct(new Product($this->id_product, false, $id_lang, $id_shop)); $this->setProductAuctionOffer(new ProductAuctionOffer($this->id_product_auction_offer, true, $id_lang, $id_shop)); } } public static function getStatusList(Module $module) { return array( self::STATUS_IDLE => $module->l('Idle', __CLASS__), self::STATUS_RUNNING => $module->l('Running', __CLASS__), self::STATUS_PROCESSING => $module->l('Processing', __CLASS__), self::STATUS_FINISHED => $module->l('Finished', __CLASS__), self::STATUS_CLOSED => $module->l('Checked out', __CLASS__) ); } /** * * @param Product $product * @return ProductAuction */ public function setProduct(Product $product) { if ($product->id == $this->id_product) $this->product = $product; return $this; } /** * * @param SpecificPrice $specific_price * @return ProductAuction */ public function setSpecificPrice(SpecificPrice $specific_price) { if ($specific_price->id == $this->id_specific_price) $this->specific_price = $specific_price; return $this; } /** * * @param ProductAuctionOffer $specific_price * @return ProductAuction */ public function setProductAuctionOffer(ProductAuctionOffer $product_auction_offer) { $this->id_product_auction_offer = $product_auction_offer->id; $this->product_auction_offer = $product_auction_offer; $this->product_auction_offer->setProductAuction($this); return $this; } /** * * @param ProductAuctionOffer $specific_price * @return ProductAuction */ public function setCurrentCustomerOffer(ProductAuctionOffer $product_auction_offer) { $this->current_customer_offer = $product_auction_offer; $this->current_customer_offer->setProductAuction($this); return $this; } /** * * @param ProductAuctionTemplate $product_auction_template * @return ProductAuction */ public function initializeFromTemplate(ProductAuctionTemplate $product_auction_template) { $fields = array_keys($this->def['fields']); foreach ($fields as $field) if (isset($product_auction_template->{$field})) $this->{$field} = $product_auction_template->{$field}; return $this; } /** * * @return ProductAuctionOffer */ public function getProductAuctionOffer() { return $this->product_auction_offer; } public function add($autodate = true, $null_values = false) { $result = parent::add($autodate, $null_values); if ($result) $this->updateSpecificPrice($this->offers < 1 ? $this->initial_price : null); return $result; } public function update($null_values = false) { $result = parent::update($null_values); if ($result) { $this->updateSpecificPrice($this->offers < 1 ? $this->initial_price : null); $this->updateProductAuctionOffer(); } return $result; } public function delete() { if (parent::delete()) { $this->specific_price->delete(); return true; } return false; } public function toggleStatus() { // Object must have a variable called 'active' if (!array_key_exists('enable_auction', $this)) throw new PrestaShopException('property "enable_auction" is missing in object '.get_class($this)); // Update only active field $this->setFieldsToUpdate(array('enable_auction' => true)); // Update active status on object $this->enable_auction = !(int)$this->enable_auction; // Change status to active/inactive return $this->update(true); } public function calculateCurrentLeader() { $product_auction_offer = ProductAuctionOfferDataManager::getWinnerForProductAuction($this, $this->id_lang, $this->id_shop); if (is_object($product_auction_offer) && $product_auction_offer->id > 0) { if ($this->specific_price->price > $product_auction_offer->customer_price) $this->specific_price->price = $product_auction_offer->customer_price; else if ($this->specific_price->price < $product_auction_offer->previous_price) $this->specific_price->price = $product_auction_offer->previous_price; $this->setProductAuctionOffer($product_auction_offer); } else { $this->id_product_auction_offer = null; $this->specific_price->price = $this->initial_price; } $this->updateProductAuctionOffer(); $this->setFieldsToUpdate(array( 'id_product_auction_offer' => true )); $this->update(true); } protected function updateSpecificPrice($price) { $this->specific_price->id_product = (int)$this->id_product; if ($price) $this->specific_price->price = (float)$price; $this->specific_price->id_shop = 0; $this->specific_price->id_product_attribute = 0; $this->specific_price->id_currency = 0; $this->specific_price->id_country = 0; $this->specific_price->id_group = 0; $this->specific_price->id_customer = 0; $this->specific_price->from_quantity = 1; $this->specific_price->reduction = 0; $this->specific_price->reduction_type = 'amount'; $this->specific_price->from = '0000-00-00 00:00:00'; $this->specific_price->to = '0000-00-00 00:00:00'; if ($this->specific_price->save(true)) { if (!$this->id_specific_price) { $this->id_specific_price = (int)$this->specific_price->id; Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.self::$definition['table'].'` SET `id_specific_price` = '.$this->id_specific_price.' WHERE `id_product_auction` = '.(int)$this->id); } Product::flushPriceCache(); // Set cache of feature detachable to true Configuration::updateGlobalValue('PS_SPECIFIC_PRICE_FEATURE_ACTIVE', '1'); } } protected function updateProductAuctionOffer() { if (!$this->id_product_auction_offer) $this->product_auction_offer = null; } } <file_sep><?php class CmsController extends CmsControllerCore { public function initContent() { parent::initContent(); $this->context->smarty->assign( 'TEST_HOOK', Hook::exec('testhook') ); } } <file_sep><?php class yourbarcode_gp extends Module { private $_html = ''; function __construct() { $this->author = '<NAME>'; $this->name = 'yourbarcode_gp'; $this->tab = 'others'; $this->version = 16.2; $this->module_key = "d854f27af733a69c9c39258a0a2c6590"; parent::__construct(); $this->page = basename(__FILE__, '.php'); $this->displayName = $this->l('Manage your barcode'); $this->description = $this->l('This module allow to manage your barcode'); } //fonction permettant de generer la base de donnée associée au module et de mettre les parametres de configuration par defaut function installDB() { $version = substr(str_replace('.','',_PS_VERSION_),0,3); $date_insert=date('Y-m-d'); $find=0; $query='SELECT count(id_configuration) as find FROM '._DB_PREFIX_.'configuration WHERE name = \'PS_LEGACY_IMAGES\''; $result=Db::getInstance()->ExecuteS($query); foreach($result as $row) { if($row['find']==1) { $find=1; } } //test si la variable PS_SHOP_DOMAIN est presente dans le cas ou celle-ci n'existe pas on crée cette variable de configuration test essentiellement fait pour les versions 1.3 de prestashop if(!Configuration::get('PS_SHOP_DOMAIN')){ //creation de la variable si non trouvé $sql='INSERT INTO '._DB_PREFIX_.'configuration ( id_configuration , name , value , date_add , date_upd ) VALUES ( NULL , \'PS_SHOP_DOMAIN\', \''.$_SERVER['HTTP_HOST'].'\', \''.date("Y-m-d").'\', \''.date("Y-m-d").'\')'; Db::getInstance()->Execute($sql); } //rajout de la variable PS_LEGACY_IMAGE pour les versions inferieur a 1.4.3 pour utiliser l'extension de la class image $version=substr(str_replace('.','',_PS_VERSION_),0,3); if ($version<143 && $find==0) { $query='INSERT INTO '._DB_PREFIX_.'configuration ( id_configuration , name , value , date_add , date_upd ) VALUES ( NULL , \'PS_LEGACY_IMAGES\', \'1\', \''.$date_insert.'\', \''.$date_insert.'\');'; Db::getInstance()->Execute($query); } Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'yourbarcodeconf ( prefix_cd varchar(13) NOT NULL, format_pg varchar(10) NOT NULL, format_spe_lg int(11) NOT NULL, format_spe_ht int(11) NOT NULL, orientation varchar(1) NOT NULL, marge_haut int(11) NOT NULL, marge_gauche int(11) NOT NULL, rotation int(11) NOT NULL, largeur_cd int(11) NOT NULL, hauteur_cd int(11) NOT NULL, nb_img_lg int(11) NOT NULL, nb_lig int(11) NOT NULL, esp_lg_lg int(11) NOT NULL, esp_cl_cl int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8;'); $query='INSERT INTO '._DB_PREFIX_.'yourbarcodeconf ( `prefix_cd` , `format_pg` , format_spe_lg , format_spe_ht , `orientation` , `marge_haut` , `marge_gauche` , `rotation` , `largeur_cd` , `hauteur_cd` , `nb_img_lg` , `nb_lig` , `esp_lg_lg` , `esp_cl_cl` ) VALUES (\'200\',\'A4\', 0, 0, \'P\', 0, 5, 0, 30, 10, 6, 20, 5, 5);'; Db::getInstance()->Execute($query); return true; } //fonction permettant de lancer la desinstallation public function uninstall() { $version=substr(str_replace('.','',_PS_VERSION_),0,3); if ($version<150) { $tabClass='adminbarcode'; } else { $tabClass='adminyourbarcode_gp'; } if(!parent::uninstall() OR !$this->uninstallDB() OR !$this->uninstallModuleTab($tabClass)) return false; return true; } //fonction permettant de supprimer les tables correspondant a ce module dans la base de donnée function uninstallDB() { if (!Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'yourbarcode_gp;') or !Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'yourbarcodeconf;')) { return false; } return true; } //fonction permettant d'installer le hook et d'enregistrer les parametres dans la base de donnée function install() { //rajoute pour les version 1.2 des methodes necessaire dans la class tools $version=substr(str_replace('.','',_PS_VERSION_),0,3); if ($version<130) { $file_tools_tmp=file_get_contents(_PS_ROOT_DIR_.'/classes/Tools.php'); $position_deb=strpos($file_tools_tmp,'function file_exists_cache'); if ($position_deb ==! false) { //deja trouvé je ne fais rien } else { $file_tools_tmp=preg_replace('/{/', file_get_contents(_PS_MODULE_DIR_.'yourbarcode_gp/class/add_tools1-2.php'), $file_tools_tmp, 1); file_put_contents (_PS_ROOT_DIR_.'/classes/Tools.php',$file_tools_tmp); } copy(_PS_MODULE_DIR_.'yourbarcode_gp/adminyourmailing.gif',_PS_IMG_DIR_.'/t/adminyourmailing.gif'); } //rajout pour les versions 1.2 et 1.3 les méthodes necessaire dans la class module au bon fonctionnement de ce module if ($version<140) { $file_tools_tmp=file_get_contents(_PS_ROOT_DIR_.'/classes/Module.php'); $position_deb=strpos($file_tools_tmp,'function getModuleNameFromClass'); if ($position_deb ==! false) { //deja trouvé je ne fais rien } else { $file_tools_tmp=preg_replace('/{/', file_get_contents(_PS_MODULE_DIR_.'yourbarcode_gp/class/add_module1-2_1-3.php'), $file_tools_tmp, 1); file_put_contents (_PS_ROOT_DIR_.'/classes/Module.php',$file_tools_tmp); } } //rajout pour la version 140 uniquement les méthodes necessaire dans la class module au bon fonctionnement de ce module if ($version==140) { $file_tools_tmp=file_get_contents(_PS_ROOT_DIR_.'/classes/Module.php'); $position_deb=strpos($file_tools_tmp,'function getModuleNameFromClass'); if ($position_deb ==! false) { //deja trouvé je ne fais rien } else { $file_tools_tmp=preg_replace('/{/', file_get_contents(_PS_MODULE_DIR_.'yourbarcode_gp/class/add_module_1-4.php'), $file_tools_tmp, 1); file_put_contents (_PS_ROOT_DIR_.'/classes/Module.php',$file_tools_tmp); } } //titre de l'onglet dans toutes les langues //Generer se tableau automatiquement en fonction des langues installée et active //Indice du tableau correspondant a l'indice de la lang rajouter le code iso a la base //type de tab generer $tabName = array('', 'barcode en', 'barcode de', 'barcode es', 'barcode fr', 'barcode it'); $base='barcode '; //recuperation de tous les code langue installé pour generation des onglets $sql='select distinct id_lang,iso_code, max(id_lang) as max_id_lang from '._DB_PREFIX_.'lang group by id_lang order by id_lang'; $resultat_lang=Db::getInstance()->ExecuteS($sql); //construction du tableau permettant de generer les onglets en fonction de la langue $tabName= array('barcode'); $inc_lang=1; foreach ($resultat_lang as $row){ while ($row['id_lang']<>$inc_lang && $row['max_id_lang']>$inc_lang) { array_push($tabName,''); $inc_lang=$inc_lang+1; } array_push($tabName,$base.' '.$row['iso_code']); $inc_lang=$inc_lang+1; } //gestion de la facon d'afficher des onglets en fonction de la version de prestashop if ($version<150){ $idTabParent='1'; $tabClass='adminbarcode'; } else { $sql='select id_tab from '._DB_PREFIX_.'tab where class_name=\'AdminCatalog\''; $resultat_tab=Db::getInstance()->ExecuteS($sql); $idTabParent=''; foreach ($resultat_tab as $row){ $idTabParent=$row['id_tab']; } $tabClass='adminyourbarcode_gp'; } if (!parent::install() OR !$this->installDB() OR !$this->installModuleTab($tabClass, $tabName, $idTabParent) ) return false; return true; } private function installModuleTab($tabClass, $tabName, $idTabParent) { $tab = new Tab(); $tab->name = $tabName; $tab->class_name = $tabClass; $tab->module = $this->name; $tab->id_parent = $idTabParent; if(!$tab->save()) return false; return true; } private function uninstallModuleTab($tabClass) { $idTab = Tab::getIdFromClassName($tabClass); if($idTab != 0) { $tab = new Tab($idTab); $tab->delete(); return true; } return false; } //onglet de configuration du module public function getContent() { if (Configuration::get('PS_SSL_ENABLED')==0) { $this->_html=$this->_html. '<SCRIPT> var http_header=\'http://\';</SCRIPT>'; $http_header='http://'; } else { $this->_html=$this->_html. '<SCRIPT> var http_header=\'https://\';</SCRIPT>'; $http_header='https://'; } //recuperation du code de la boutique $version=substr(str_replace('.','',_PS_VERSION_),0,3); if ($version<150) { $domain=Configuration::get('PS_SHOP_DOMAIN'); $racine=__PS_BASE_URI__; } else { $context = Context::getContext(); $id_shop = (int)$context->shop->id; $sql_url='select * from '._DB_PREFIX_.'shop_url where id_shop='.$id_shop; $result_url = Db::getInstance()->ExecuteS($sql_url); foreach($result_url as $row_url) { $domain=$row_url['domain']; $racine=$row_url['physical_uri']; //ex: / si racine ou alors si repertoire ex: /mon_repertoire/ } } $this->_html=$this->_html. '<SCRIPT> var domain=\''.$domain.'\';</SCRIPT>'; $this->_html=$this->_html. '<SCRIPT> var racine=\''.$racine.'\';</SCRIPT>'; $this->_html=$this->_html. '<link href="'._MODULE_DIR_.'yourbarcode_gp/css/style.css" rel="stylesheet" type="text/css" media="all" />'; $this->_html=$this->_html. '<script type="text/javascript" src="'._MODULE_DIR_.'yourbarcode_gp/js/adminbarcode.js"></script>'; //generation des constantes $ch_jv=str_replace('\\','/',_PS_MODULE_DIR_); //recuperation des variables de configuration $sql='select * from '._DB_PREFIX_.'yourbarcodeconf'; $resultat=Db::getInstance()->ExecuteS($sql); foreach ($resultat as $row) { $prefix_cd=$row['prefix_cd']; $format_pg=$row['format_pg']; $format_spe_lg=$row['format_spe_lg']; $format_spe_ht=$row['format_spe_ht']; $orientation=$row['orientation']; $marge_haut=$row['marge_haut']; $marge_gauche=$row['marge_gauche']; $rotation=$row['rotation']; $largeur_cd=$row['largeur_cd']; $hauteur_cd=$row['hauteur_cd']; $nb_img_lg=$row['nb_img_lg']; $nb_lig=$row['nb_lig']; $esp_lg_lg=$row['esp_lg_lg']; $esp_cl_cl=$row['esp_cl_cl']; } //Liste de choix barcode prefix $select_barcode_prefix='<SELECT ID="prefix_cd" NAME="prefix_cd" title="'.$this->l('Between 200 and 299').'>'; for($i=199;$i<300;$i++){ if($prefix_cd==$i){ $select_barcode_prefix=$select_barcode_prefix.'<option value="'.$i.'" selected>'.$i.'</option>'; } else { $select_barcode_prefix=$select_barcode_prefix.'<option value="'.$i.'">'.$i.'</option>'; } } $select_barcode_prefix=$select_barcode_prefix.'</SELECT>'; //liste de choix format de page $select_format_pg='<SELECT ID="format_pg" NAME="format_pg">'; $format=array('A3','A4','A5','Letter','Legal'); foreach ($format as $value){ $option_format=$this->select_format($value,$format_pg); $select_format_pg=$select_format_pg.$option_format; } $select_format_pg=$select_format_pg.'</SELECT>'; //liste de choix orientation de page $select_orientation_pg='<SELECT ID="orientation" NAME="orientation">'; if($orientation=='P'){ $select_orientation_pg=$select_orientation_pg.'<option value="P" selected>'.$this->l('Portrait').'</option>'; $select_orientation_pg=$select_orientation_pg.'<option value="L">'.$this->l('Landscape').'</option>'; } else { $select_orientation_pg=$select_orientation_pg.'<option value="P">'.$this->l('Portrait').'</option>'; $select_orientation_pg=$select_orientation_pg.'<option value="L" selected>'.$this->l('Landscape').'</option>'; } $select_orientation_pg=$select_orientation_pg.'</SELECT>'; //liste de choix rotation du code barre $select_rotation_cd='<SELECT ID="rotation" NAME="rotation">'; if($rotation=='1'){ $select_rotation_cd=$select_rotation_cd.'<option value="1" selected>'.$this->l('Portrait').'</option>'; $select_rotation_cd=$select_rotation_cd.'<option value="0">'.$this->l('Landscape').'</option>'; } else { $select_rotation_cd=$select_rotation_cd.'<option value="1">'.$this->l('Portrait').'</option>'; $select_rotation_cd=$select_rotation_cd.'<option value="0" selected>'.$this->l('Landscape').'</option>'; } $select_rotation_cd=$select_rotation_cd.'</SELECT>'; //affichage commun a tout les onglets $this->_html=$this->_html. '<fieldset> <legend> '.$this->l('Administration module barcode').' </legend>'; $this->_html=$this->_html. '<FORM ID="formulaire" NAME="formulaire">'; $this->_html=$this->_html. '<input type="hidden" value="'._PS_ROOT_DIR_.'" name="ps_root_dir" id="ps_root_dir"/>'; $this->_html=$this->_html. '<input type="hidden" value="" name="tampon" id="tampon"/>'; $this->_html=$this->_html. '<input type="hidden" name="error_msg" id="error_msg" value="'.$this->l('Number between 1 and 999 mandatory').'"/>'; $this->_html=$this->_html. '<input type="hidden" name="warning_msg" id="warning_msg" value="'.$this->l('Please note this action will create code for all ean13 empty product sheets with a code prefix that you selected. Do you want to continue?').'"/>'; $this->_html=$this->_html. '<input type="hidden" name="msg" id="msg" value="'.$this->l('Parameter saved').'"/>'; $this->_html=$this->_html. '<input type="hidden" name="msg_gen" id="msg_gen" value="'.$this->l('All barcodes are generated').'"/>'; $this->_html=$this->_html. '<input type="hidden" name="msg_gen" id="msg_error" value="'.$this->l('You must already backup before generate the barcode with this prefix').'"/>'; $this->_html=$this->_html. '<TABLE>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Barcode prefix').'</TD><TD>'; $this->_html=$this->_html. '<INPUT id="prefix_cd" name="prefix_cd" value="'.$prefix_cd.'" title="'.$this->l('Type your prefix code').'" TYPE="TEXT"/>'; $this->_html=$this->_html. '<INPUT TYPE="button" value="'.$this->l('Generate barcodes').'" onclick="gen_barcode();"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Page size').'</TD><TD>'.$select_format_pg.'</TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Type your specific width or 0 for standard page size').'</TD><TD><INPUT id="format_spe_lg" name="format_spe_lg" value="'.$format_spe_lg.'" title="'.$this->l('Type your specific width or 0 for standard page size').'" TYPE="TEXT"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Type your specific height or 0 for standard page size').'</TD><TD><INPUT id="format_spe_ht" name="format_spe_ht" value="'.$format_spe_ht.'" title="'.$this->l('Type your specific height or 0 for standard page size').'" TYPE="TEXT"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Sheet orientation').'</TD><TD>'.$select_orientation_pg.'</TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Margin top').'</TD><TD><INPUT id="marge_haut" name="marge_haut" value="'.$marge_haut.'" title="'.$this->l('Type your margin top').'" TYPE="TEXT" onclick="document.getElementById(\'tampon\').value=this.value" onchange=" only_number(3,this.name);"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Margin left').'</TD><TD><INPUT id="marge_gauche" name="marge_gauche" value="'.$marge_gauche.'" title="'.$this->l('Type your margin left').'" TYPE="TEXT" onclick="document.getElementById(\'tampon\').value=this.value" onchange=" only_number(3,this.name);"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Barcode orientation').'</TD><TD>'.$select_rotation_cd.'</TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Width barcode').'</TD><TD><INPUT id="largeur_cd" name="largeur_cd" value="'.$largeur_cd.'" title="'.$this->l('Type your width barcode').'" TYPE="TEXT" onclick="document.getElementById(\'tampon\').value=this.value" onchange=" only_number(3,this.name);"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Height barcode').'</TD><TD><INPUT id="hauteur_cd" name="hauteur_cd" value="'.$hauteur_cd.'" title="'.$this->l('Type your height barcode').'" TYPE="TEXT" onclick="document.getElementById(\'tampon\').value=this.value" onchange=" only_number(3,this.name);"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Number of bar code per line').'</TD><TD><INPUT id="nb_img_lg" name="nb_img_lg" value="'.$nb_img_lg.'" title="'.$this->l('Type your number of bar code per line').'" TYPE="TEXT" onclick="document.getElementById(\'tampon\').value=this.value" onchange=" only_number(3,this.name);"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Line number of barcode on the page').'</TD><TD><INPUT id="nb_lig" name="nb_lig" value="'.$nb_lig.'" title="'.$this->l('Type your line number of barcode on the page').'" TYPE="TEXT" onclick="document.getElementById(\'tampon\').value=this.value" onchange=" only_number(3,this.name);"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Space between lines').'</TD><TD><INPUT id="esp_lg_lg" name="esp_lg_lg" value="'.$esp_lg_lg.'" title="'.$this->l('Type your Space between lines').'" TYPE="TEXT" onclick="document.getElementById(\'tampon\').value=this.value" onchange=" only_number(3,this.name);"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Space between columns').'</TD><TD><INPUT id="esp_cl_cl" name="esp_cl_cl" value="'.$esp_cl_cl.'" title="'.$this->l('Type your Space between lines').'" TYPE="TEXT" onclick="document.getElementById(\'tampon\').value=this.value" onchange=" only_number(3,this.name);"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Save').'</TD><TD><INPUT id="save" name="save" title="'.$this->l('Save all parameters').'" TYPE="button" value="'.$this->l('Save').'" onclick="save_gp(\''.$ch_jv.'yourbarcode_gp/\');"/></TD></TR>'; $this->_html=$this->_html. '<TR><TD>'.$this->l('Print Preview').'</TD><TD><INPUT id="test_pdf" name="test_pdf" title="'.$this->l('Show a print preview').'" TYPE="button" value="'.$this->l('Print Preview').'" onclick="window.open(\''._MODULE_DIR_.'yourbarcode_gp/pdf.php?cd_ean13=2000000000138&PS_ROOT_DIR='.addslashes(_PS_ROOT_DIR_).'&url='.$http_header.$domain._MODULE_DIR_.'yourbarcode_gp/ean13.php\')"/></TD></TR>'; $this->_html=$this->_html. '</TABLE>'; $this->_html=$this->_html. '</FORM>'; return $this->_html; } function select_format($val_format,$val_format_sgbd){ if($val_format==$val_format_sgbd) { return '<option value="'.$val_format.'" selected>'.$val_format.'</option>'; } else { return '<option value="'.$val_format.'">'.$val_format.'</option>'; } } } ?><file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionLoader', false)) return; class ProductAuctionLoader { /** * @var ProductAuctionLoader */ private static $instance; /** * * @var Module */ protected $module; /** * * @var integer[] */ protected $product_ids = array(); /** * * @var ProductAuction[] */ protected $product_auction = array(); /** * * @var ProductAuctionItem[] */ protected $product_auction_item = array(); /** * @var array */ protected $product_auction_fetched = array(); /** * @var array */ protected $subscribed_product_auction_ids = array(); /** * * @param Module $module */ private function __construct(Module $module) { $this->module = $module; } /** * * @param Module $module * @return ProductAuctionLoader */ public static function getInstance(Module $module) { if (empty(self::$instance)) self::setInstance($module); return self::$instance; } /** * * @param Module $module */ public static function setInstance(Module $module) { self::$instance = new self($module); } /** * * @return Module */ protected function getModule() { return $this->module; } /** * @return Language */ protected function getLanguage() { return $this->getModule()->getContext()->language; } /** * @return Customer */ protected function getCustomer() { return $this->getModule()->getContext()->customer; } /** * @return Shop */ protected function getShop() { return $this->getModule()->getContext()->shop; } public function addProductId($product_id) { $product_id = (int)$product_id; if (!in_array($product_id, $this->product_ids)) $this->product_ids[] = $product_id; } public function addProductIds(array $product_ids) { foreach ($product_ids as $product_id) $this->addProductId($product_id); } public function getProductAuctionItem($product_id) { $this->addProductId($product_id); $this->fetchAuctions(); return isset($this->product_auction_item[$product_id]) ? $this->product_auction_item[$product_id] : null; } public function getProductAuctionItemArray($product_id) { $this->addProductId($product_id); $this->fetchAuctions(); return isset($this->product_auction_item[$product_id]) ? $this->product_auction_item[$product_id] : null; } public function isProductAuctionFetched($product_id) { return in_array($product_id, $this->product_auction_fetched); } public function hasProductAuctionItem($product_id) { return array_key_exists($product_id, $this->product_auction_item); } public function fetchAuctions() { $product_ids = $this->product_ids; $missing_product_ids = array(); foreach ($product_ids as $product_id) if ($product_id && !$this->isProductAuctionFetched($product_id)) $missing_product_ids[] = $product_id; if (empty($missing_product_ids)) return; $language = $this->getLanguage(); $shop = $this->getShop(); $product_auctions = ProductAuctionDataManager::getCollectionByProductIds($missing_product_ids, null, $language->id, $shop->id); $product_auctions_items = ProductAuctionItemFactory::getInstance($this->getModule())->makeFrontOfficeItems($product_auctions); foreach ($product_auctions as $product_auction) $this->product_auction[$product_auction->id_product] = $product_auction; foreach ($product_auctions_items as $product_auction_item) $this->product_auction_item[$product_auction_item->getProductId()] = $product_auction_item; $this->product_auction_fetched += $missing_product_ids; } public function getSubscribedAuctionIds(Customer $customer) { if (!isset($this->subscribed_product_auction_ids[$customer->id])) $this->subscribed_product_auction_ids[$customer->id] = ProductAuctionSubscriptionDataManager::getSubscribedProductAuctionIdsForCustomer($customer); return $this->subscribed_product_auction_ids[$customer->id]; } } <file_sep><?php /** * 2007-2014 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit; include_once(_PS_MODULE_DIR_.'/worldpay/classes/request/paymentmodulerequest.php'); class WorldPayRequest extends PaymentModuleRequest { const REQUEST_INSTALLATION_ID = 'instId'; const REQUEST_CART_ID = 'cartId'; const REQUEST_AUTH_MODE = 'authMode'; const REQUEST_TEST_MODE = 'testMode'; const REQUEST_AMOUNT = 'amount'; const REQUEST_CURRENCY = 'currency'; const REQUEST_HIDE_CURRENCY = 'hideCurrency'; const REQUEST_NAME = 'name'; const REQUEST_ADDRESS1 = 'address1'; const REQUEST_ADDRESS2 = 'address2'; const REQUEST_CITY = 'town'; const REQUEST_POSTCODE = 'postcode'; const REQUEST_COUNTRY = 'country'; const REQUEST_TELEPHONE = 'tel'; const REQUEST_EMAIL = 'email'; const REQUEST_LANGUAGE = 'lang'; const REQUEST_DESCRIPTION = 'desc'; const REQUEST_CALLBACK = 'MC_callback'; const REQUEST_FIX_CONTACT = 'fixContact'; const REQUEST_HIDE_CONTACT = 'hideContact'; const REQUEST_NO_LANGUAGE_MENU = 'noLanguageMenu'; const REQUEST_SIGNATURE = 'signature'; const REQUEST_SIGNATURE_FIELDS = 'signatureFields'; /** * @var array */ protected $parameters = array( self::REQUEST_INSTALLATION_ID => null, self::REQUEST_CART_ID => null, self::REQUEST_AUTH_MODE => null, self::REQUEST_TEST_MODE => null, self::REQUEST_AMOUNT => null, self::REQUEST_CURRENCY => null, self::REQUEST_HIDE_CURRENCY => null, self::REQUEST_NAME => null, self::REQUEST_ADDRESS1 => null, self::REQUEST_ADDRESS2 => null, self::REQUEST_CITY => null, self::REQUEST_POSTCODE => null, self::REQUEST_COUNTRY => null, self::REQUEST_TELEPHONE => null, self::REQUEST_EMAIL => null, self::REQUEST_LANGUAGE => null, self::REQUEST_DESCRIPTION => null, self::REQUEST_CALLBACK => null, self::REQUEST_FIX_CONTACT => null, self::REQUEST_HIDE_CONTACT => null, self::REQUEST_NO_LANGUAGE_MENU => null, self::REQUEST_SIGNATURE => null, self::REQUEST_SIGNATURE_FIELDS => null, ); public function initialize(Cart $cart) { // OPC module update by Peter - customer ID doesn't exist yet at load time! $customer_id = ($cart->id_customer >0)?$cart->id_customer:63; $currency = $this->getCurrencyObject($cart->id_currency); $language = $this->getLanguageObject($cart->id_lang); $customer = $this->getCustomerObject($customer_id); $address = $this->getAddressObject($cart->id_address_invoice); $country = $this->getCountryObject($address->id_country); switch ($this->settings->getValue(WorldPaySettings::PAYMENT_MODE)) { case WorldPaySettings::WORLDPAY_LIVE: $this->url = WorldPaySettings::WORLDPAY_LIVE_URL; break; case WorldPaySettings::WORLDPAY_TEST: default: $this->url = WorldPaySettings::WORLDPAY_TEST_URL; break; } $this->title = $this->settings->getValue(WorldPaySettings::PAYMENT_TITLE, null, $cart->id_lang); $this->parameters[self::REQUEST_INSTALLATION_ID] = $this->settings->getValue(WorldPaySettings::PAYMENT_INSTALLATION_ID); $this->parameters[self::REQUEST_CART_ID] = (int)$cart->id; $this->parameters[self::REQUEST_AMOUNT] = number_format($cart->getOrderTotal(true, Cart::BOTH), 2, '.', ''); $this->parameters[self::REQUEST_CURRENCY] = $currency->iso_code; $this->parameters[self::REQUEST_HIDE_CURRENCY] = 'true'; $this->parameters[self::REQUEST_NAME] = $customer->firstname.' '.$customer->lastname; $this->parameters[self::REQUEST_ADDRESS1] = $address->address1; $this->parameters[self::REQUEST_ADDRESS2] = $address->address2; $this->parameters[self::REQUEST_CITY] = $address->city; $this->parameters[self::REQUEST_POSTCODE] = $address->postcode; $this->parameters[self::REQUEST_COUNTRY] = $country->iso_code; $this->parameters[self::REQUEST_TELEPHONE] = !empty($address->phone) ? $address->phone : $address->phone_mobile; $this->parameters[self::REQUEST_EMAIL] = $customer->email; $this->parameters[self::REQUEST_LANGUAGE] = !empty($language->iso_code) ? $language->iso_code : WorldPaySettings::WORLDPAY_DEFAULT_LOCALE; $payment_request_type = $this->settings->getValue(WorldPaySettings::PAYMENT_REQUEST_TYPE); $payment_mode = $this->settings->getValue(WorldPaySettings::PAYMENT_MODE); $this->parameters[self::REQUEST_AUTH_MODE] = $payment_request_type == WorldPaySettings::WORLDPAY_REQUEST_TYPE_PREAUTHORIZATION ? 'E' : 'A'; $this->parameters[self::REQUEST_TEST_MODE] = $payment_mode == WorldPaySettings::WORLDPAY_TEST ? '100' : '0'; $payment_description = $this->settings->getValue(WorldPaySettings::PAYMENT_DESCRIPTION, null, $cart->id_lang); $this->parameters[self::REQUEST_DESCRIPTION] = sprintf($payment_description, Configuration::get('PS_SHOP_NAME')); $this->parameters[self::REQUEST_CALLBACK] = $this->settings->getModule()->getValidationUrl(); if ($this->settings->getValue(WorldPaySettings::PAYMENT_FIX_CONTACT) == WorldPaySettings::YES) $this->parameters[self::REQUEST_FIX_CONTACT] = 1; if ($this->settings->getValue(WorldPaySettings::PAYMENT_HIDE_CONTACT) == WorldPaySettings::YES) $this->parameters[self::REQUEST_HIDE_CONTACT] = 1; if ($this->settings->getValue(WorldPaySettings::PAYMENT_HIDE_LANGUAGE) == WorldPaySettings::YES) $this->parameters[self::REQUEST_NO_LANGUAGE_MENU] = null; $checksum = trim($this->settings->getValue(WorldPaySettings::PAYMENT_MD5_CHECKSUM)); if (!empty($checksum)) { switch ($this->settings->getValue(WorldPaySettings::PAYMENT_SIGNATURE_TYPE)) { case WorldPaySettings::WORLDPAY_SIGNATURE_STATIC: $signature_params = explode(':', $this->settings->getValue(WorldPaySettings::PAYMENT_SIGNATURE_PARAMETERS)); $signature_string = $checksum; foreach ($signature_params as $param) if (array_key_exists($param, $this->parameters)) $signature_string .= ':'.$this->parameters[$param]; $this->parameters[self::REQUEST_SIGNATURE] = md5($signature_string); break; case WorldPaySettings::WORLDPAY_SIGNATURE_DYNAMIC: //'amount:currency:instId:cartId:authMode:email'; $signature_params_string = $this->settings->getValue(WorldPaySettings::PAYMENT_SIGNATURE_PARAMETERS); $signature_params = explode(':', $signature_params_string); $this->parameters[self::REQUEST_SIGNATURE_FIELDS] = $signature_params_string; $signature_string = $checksum.';'.$signature_params_string; foreach ($signature_params as $param) if (array_key_exists($param, $this->parameters)) $signature_string .= ';'.$this->parameters[$param]; $this->parameters[self::REQUEST_SIGNATURE] = md5($signature_string); break; } } $this->initialized = true; } public function getInstallationId() { return $this->parameters[self::REQUEST_INSTALLATION_ID]; } public function getCartId() { return $this->parameters[self::REQUEST_CART_ID]; } public function getAuthMode() { return $this->parameters[self::REQUEST_AUTH_MODE]; } public function getTestMode() { return $this->parameters[self::REQUEST_TEST_MODE]; } public function getAmount() { return $this->parameters[self::REQUEST_AMOUNT]; } public function getCurrency() { return $this->parameters[self::REQUEST_CURRENCY]; } public function getHideCurrency() { return $this->parameters[self::REQUEST_HIDE_CURRENCY]; } public function getName() { return $this->parameters[self::REQUEST_NAME]; } public function getAddress1() { return $this->parameters[self::REQUEST_ADDRESS1]; } public function getAddress2() { return $this->parameters[self::REQUEST_ADDRESS2]; } public function getCity() { return $this->parameters[self::REQUEST_CITY]; } public function getPostCode() { return $this->parameters[self::REQUEST_POSTCODE]; } public function getCountry() { return $this->parameters[self::REQUEST_COUNTRY]; } public function getPhone() { return $this->parameters[self::REQUEST_TELEPHONE]; } public function getEmail() { return $this->parameters[self::REQUEST_EMAIL]; } public function getLanguage() { return $this->parameters[self::REQUEST_LANGUAGE]; } public function getDescription() { return $this->parameters[self::REQUEST_DESCRIPTION]; } public function getCallback() { return $this->parameters[self::REQUEST_CALLBACK]; } public function isFixContact() { return $this->parameters[self::REQUEST_FIX_CONTACT]; } public function isHideContact() { return $this->parameters[self::REQUEST_HIDE_CONTACT]; } public function isNoLanguageMenu() { return $this->parameters[self::REQUEST_NO_LANGUAGE_MENU]; } public function getSignature() { return $this->parameters[self::REQUEST_SIGNATURE]; } public function getSignatureFields() { return $this->parameters[self::REQUEST_SIGNATURE_FIELDS]; } } <file_sep><?php /** * hook-display_class.php file defines controller which manage hooks sequentially */ class BT_FPCHookDisplay implements BT_IFpcHook { /** * @var bool $bProcessHookAndConnector : detect if hook and connectors have been processed */ static protected $bProcessHookAndConnector = null; /** * @var bool $bConnectorsActive : detect if one connector is active at least */ static protected $bConnectorsActive = null; /** * @var string $sCurrentURI : get current URI */ static protected $sCurrentURI = ''; /** * @var string $sModuleURI : get Module web service URI */ protected $sModuleURI = null; /** * @var string $sHookType : define hook type */ protected $sHookType = null; /** * @var int $iCustomerLogged : get customer ID if is logged */ protected $iCustomerLogged = null; /** * Magic Method __construct assigns few information about hook * * @param string */ public function __construct($sHookType) { // set hook type $this->sHookType = $sHookType; $this->iCustomerLogged = BT_FPCModuleTools::getCustomerId(); } /** * Magic Method __destruct */ public function __destruct() { unset($this); } /** * run() method execute hook * * @param array $aParams * @return array */ public function run(array $aParams = array()) { // set variables $aDisplayHook = array(); // set module URI $this->sModuleURI = _FPC_MODULE_URL . 'ws-' . _FPC_MODULE_SET_NAME . '.php'; // process hooks and connectors $this->_processConnectorAndHook(); // get current URL if (empty(self::$sCurrentURI)) { self::$sCurrentURI = urlencode($this->_getCurrentUrl()); } switch ($this->sHookType) { case 'header' : // use case - display in header $aDisplayHook = call_user_func(array($this, '_displayHeader')); break; case 'account' : // use case - display in account $aDisplayHook = call_user_func(array($this, '_displayAccount')); break; case 'top' : // use case - display connect buttons in top $aDisplayHook = call_user_func_array(array($this, '_displayTop'), array($aParams)); break; case 'left' : case 'right' : // use case - display block connect in left or right column $aDisplayHook = call_user_func_array(array($this, '_displayBlock'), array($aParams)); break; case 'footer' : // use case - display connect buttons in footer $aDisplayHook = call_user_func_array(array($this, '_displayFooter'), array($aParams)); break; default : break; } // use case - generic assign if (!empty($aDisplayHook['assign'])) { if (!empty(FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_API_REQUEST_METHOD'])) { $aDisplayHook['assign'] = array_merge($aDisplayHook['assign'], $this->_assign()); } else { $aDisplayHook['assign'] = array('bDisplay' => false); } } return $aDisplayHook; } /** * _assign() method assigns transverse data * * @category hook collection * @see * * @return array */ private function _assign() { // set smarty variables return ( array( 'sModuleURI' => $this->sModuleURI, 'iCurrentLang' => intval(FacebookPsConnect::$iCurrentLang), 'sCurrentLang' => FacebookPsConnect::$sCurrentLang, 'bCustomerLogged' => $this->iCustomerLogged, 'bHookDisplay' => true, 'bVersion16' => version_compare(_PS_VERSION_, '1.6', '>')? true : false, ) ); } /** * _processConnectorAndHook() method unserialize connector and hook content * * @return array */ private function _processConnectorAndHook() { if (self::$bProcessHookAndConnector === null) { // unserialize connectors and hooks data BT_FPCModuleTools::getHookData(); self::$bConnectorsActive = BT_FPCModuleTools::getConnectorData(false, true); foreach ($GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS'] as $sName => &$aConnector) { $aConnector['tpl'] = BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_HOOK_PATH . $aConnector['tpl']); } self::$bProcessHookAndConnector = true; } } /** * _getCurrentUrl() method returns current URL * * @return array */ private function _getCurrentUrl() { $sLink = ''; // PS 1.5 if (version_compare(_PS_VERSION_, '1.5', '>')) { // check if OPC deactivated and get redirect on authentication page if (Tools::getValue('controller') == 'authentication' && Tools::getIsset('back') ) { $sLink = urldecode(Tools::getValue('back')); if ($sLink == 'my-account') { $sLink = BT_FPCModuleTools::getAccountPageLink(); } } // check if OPC URL elseif ( Tools::getValue('controller') == 'orderopc' || Tools::getValue('controller') == 'order' ) { $sLink = $_SERVER['REQUEST_URI']; } // my account page else { $sLink = BT_FPCModuleTools::getAccountPageLink(); } } // PS 1.4 elseif (version_compare(_PS_VERSION_, '1.4', '>')) { // check if OPC deactivated and get redirect on authentication page if (strstr($_SERVER['SCRIPT_NAME'], 'authentication') && Tools::getIsset('back') ) { if ($sLink == 'my-account.php') { $sLink = BT_FPCModuleTools::getAccountPageLink(); } else { $oLink = new Link(); $sLink = $oLink->getPageLink('order.php'); unset($oLink); } } // check if OPC URL elseif (strstr($_SERVER['SCRIPT_NAME'], 'order-opc') || strstr($_SERVER['SCRIPT_NAME'], 'order') ) { $sLink = $_SERVER['REQUEST_URI']; } // my account page else { $sLink = BT_FPCModuleTools::getAccountPageLink(); } } // PS 1.2 & 1.3 else { // check if get redirect on authentication page if (strstr($_SERVER['SCRIPT_NAME'], 'authentication') || Tools::getIsset('back') ) { $sLink = Tools::getValue('back'); // get PS_BASE_URI $sLink = Configuration::get('PS_BASE_URI') . $sLink; } // check if check-out URL elseif (strstr($_SERVER['SCRIPT_NAME'], 'order')) { $sLink = $_SERVER['REQUEST_URI']; } // my account page else { global $smarty; $sLink = $smarty->_tpl_vars['base_dir_ssl'] . 'my-account.php'; } } return $sLink; } /** * _displayHeader() method add to header JS and CSS * * @return array */ private function _displayHeader() { // set $aAssign = array(); // set js msg translation BT_FPCModuleTools::translateJsMsg(); $aAssign['oJsTranslatedMsg'] = BT_FPCModuleTools::jsonEncode($GLOBALS[_FPC_MODULE_NAME . '_JS_MSG']); // old version if (version_compare(_PS_VERSION_, '1.4.1', '<')) { $aAssign['bAddJsCss'] = true; } else { // use case - get context if (version_compare(_PS_VERSION_, '1.5', '>')) { // add in minify process by prestahsop Context::getContext()->controller->addCSS(_FPC_URL_CSS . 'hook.css'); Context::getContext()->controller->addJS(_FPC_URL_JS . 'module.js'); if (Tools::getValue('controller') == 'myaccount') { // get fancybox plugin $aJsCss = Media::getJqueryPluginPath('fancybox'); // add fancybox plugin if (!empty($aJsCss['js']) && !empty($aJsCss['css'])) { Context::getContext()->controller->addCSS($aJsCss['css']); Context::getContext()->controller->addJS($aJsCss['js']); } } } else { // add in minify process by prestahsop Tools::addCSS(_FPC_URL_CSS . 'hook.css'); Tools::addJS(_FPC_URL_JS . 'module.js'); // add fancybox plugin Tools::addCSS(_PS_CSS_DIR_ . 'jquery.fancybox-1.3.4.css'); Tools::addJS(_PS_JS_DIR_ . 'jquery/jquery.fancybox-1.3.4.js'); } $aAssign['bAddJsCss'] = false; } return ( array('tpl' => _FPC_TPL_HEADER, 'assign' => $aAssign) ); } /** * _displayTop() method displays connector buttons * * @param array $aParams * @return array */ private function _displayTop(array $aParams) { // set $aAssign = array(); // get all configured hooks if (array_key_exists($this->sHookType, $GLOBALS[_FPC_MODULE_NAME . '_ZONE']) && false !== $GLOBALS[_FPC_MODULE_NAME . '_ZONE'][$this->sHookType]['data'] && self::$bConnectorsActive ) { $aAssign['bDisplay'] = true; $aAssign['sConnectorButtonsIncl'] = BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_HOOK_PATH . _FPC_TPL_CONNECTOR_BUTTONS); $aAssign['aHookConnectors'] = $GLOBALS[_FPC_MODULE_NAME . '_ZONE'][$this->sHookType]['data']; $aAssign['aConnectors'] = $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS']; $aAssign['sPosition'] = 'top'; $aAssign['sStyle'] = 'badgeTop'; $aAssign['sBackUri'] = self::$sCurrentURI; } else { $aAssign['bDisplay'] = false; } return ( array('tpl' => _FPC_TPL_HOOK_PATH . _FPC_TPL_CONNECTOR_BUTTONS_JS, 'assign' => $aAssign) ); } /** * _displayBlock() method * * @param array $aParams * @return array */ private function _displayBlock(array $aParams) { // set $aAssign = array(); // get all configured hooks if (FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_DISPLAY_BLOCK'] && !empty($GLOBALS[_FPC_MODULE_NAME . '_ZONE'][$this->sHookType]['data']) ) { $aAssign['sStyle'] = strtolower(_FPC_MODULE_NAME).'_mini_button'; $aAssign['bDisplay'] = true; $aAssign['bConnectorsActive'] = self::$bConnectorsActive; $aAssign['sConnectorButtonsIncl'] = BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_HOOK_PATH . _FPC_TPL_CONNECTOR_BUTTONS); $aAssign['aHookConnectors'] = $GLOBALS[_FPC_MODULE_NAME . '_ZONE'][$this->sHookType]['data']; $aAssign['aConnectors'] = $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS']; $aAssign['sPosition'] = 'blockAccount'; $aAssign['sBackUri'] = self::$sCurrentURI; $aAssign['sLinkAccount16'] = BT_FPCModuleTools::getAccountPageLink(); // customer data $aAssign['sCustomerName'] = $this->iCustomerLogged ? BT_FPCModuleTools::getCookieObj()->customer_firstname . ' ' . BT_FPCModuleTools::getCookieObj()->customer_lastname : false; $aAssign['sFirstName'] = $this->iCustomerLogged ? BT_FPCModuleTools::getCookieObj()->customer_firstname : false; $aAssign['sLastName'] = $this->iCustomerLogged ? BT_FPCModuleTools::getCookieObj()->customer_lastname : false; // customer not logged if (!empty($this->iCustomerLogged)) { $aAssign['oCart'] = BT_FPCModuleTools::getCartObj(); $aAssign['iCartQty'] = BT_FPCModuleTools::getCartObj()->nbProducts(); } } else { $aAssign['bDisplay'] = false; } return ( array('tpl' => _FPC_TPL_HOOK_PATH . _FPC_TPL_ACCOUNT_BLOCK, 'assign' => $aAssign) ); } /** * _displayFooter() method displays buttons in footer * * @param array $aParams * @return array */ private function _displayFooter(array $aParams) { // set $aAssign = array(); $aAssign['bDisplay'] = false; $aAssign['bDisplayBlockInfoAccount'] = (int)FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_DISPLAY_BLOCK_INFO_ACCOUNT']; $aAssign['bDisplayBlockInfoCart'] = (int)FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_DISPLAY_BLOCK_INFO_CART']; // get all configured hooks if (array_key_exists($this->sHookType, $GLOBALS[_FPC_MODULE_NAME . '_ZONE']) && self::$bConnectorsActive ) { // set $sContent = ''; $aAssign['aConnectors'] = $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS']; $aAssign['sConnectorButtonsIncl'] = BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_HOOK_PATH . _FPC_TPL_CONNECTOR_BUTTONS); // use case - footer layout if (false !== $GLOBALS[_FPC_MODULE_NAME . '_ZONE']['footer']['data']) { $aAssign['aHookConnectors'] = $GLOBALS[_FPC_MODULE_NAME . '_ZONE']['footer']['data']; $aAssign['sPosition'] = 'bottom'; $aAssign['sStyle'] = 'badgeBottom'; $aAssign['bDisplay'] = true; $aAssign['sBackUri'] = self::$sCurrentURI; $sContent .= FacebookPsConnect::$oModule->displayModule(_FPC_TPL_HOOK_PATH . _FPC_TPL_CONNECTOR_BUTTONS_JS, $aAssign); } // use case - customer authentication page layout if (false !== $GLOBALS[_FPC_MODULE_NAME . '_ZONE']['authentication']['data'] && ( ((version_compare(_PS_VERSION_, '1.5', '>') && Tools::getValue('controller') == 'authentication') || strstr($_SERVER['SCRIPT_NAME'], 'authentication') ) || ((version_compare(_PS_VERSION_, '1.5', '>') && Tools::getValue('controller') == 'orderopc') || strstr($_SERVER['SCRIPT_NAME'], 'order-opc') ) ) ) { $aAssign['sStyle'] = ''; $aAssign['aHookConnectors'] = $GLOBALS[_FPC_MODULE_NAME . '_ZONE']['authentication']['data']; $aAssign['bDisplay'] = true; $aAssign['sBackUri'] = self::$sCurrentURI; if ((version_compare(_PS_VERSION_, '1.5', '>') && Tools::getValue('controller') == 'orderopc') || strstr($_SERVER['SCRIPT_NAME'], 'order-opc') ) { $aAssign['sPosition'] = 'newaccount'; } else { $aAssign['sPosition'] = 'authentication'; } // use case on FB friendly permission option if (!empty($GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS']['facebook']['data']['activeConnector']) && BT_FPCModuleTools::getCustomerId() == 0 ) { if (!empty($GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS']['facebook']['data']['permissions'])) { $aAssign['sFriendlyText'] = FacebookPsConnect::$oModule->l('You can use any of the login buttons above to automatically create an account on our shop.', 'hook-display_class') . '.'; } else { $aAssign['sDefaultText'] = FacebookPsConnect::$oModule->l('You can use any of the login buttons above to automatically create an account on our shop.', 'hook-display_class') . '.'; } } $sContent .= FacebookPsConnect::$oModule->displayModule(_FPC_TPL_HOOK_PATH . _FPC_TPL_CONNECTOR_BUTTONS_JS, $aAssign); } // use case - top block user layout iset test for 1.6 hide block if (isset($GLOBALS[_FPC_MODULE_NAME . '_ZONE']['blockUser']) && false !== $GLOBALS[_FPC_MODULE_NAME . '_ZONE']['blockUser']['data']) { $aAssign['sStyle'] = strtolower(_FPC_MODULE_NAME).'_mini_button'; $aAssign['aHookConnectors'] = $GLOBALS[_FPC_MODULE_NAME . '_ZONE']['blockUser']['data']; $aAssign['sPosition'] = 'blockUser'; $aAssign['bDisplay'] = true; $aAssign['sBackUri'] = self::$sCurrentURI; $sContent .= FacebookPsConnect::$oModule->displayModule(_FPC_TPL_HOOK_PATH . _FPC_TPL_CONNECTOR_BUTTONS_JS, $aAssign); } $aAssign['sContent'] = $sContent; } return ( array('tpl' => _FPC_TPL_HOOK_PATH . _FPC_TPL_CONNECTOR_BUTTONS_CNT, 'assign' => $aAssign) ); } /** * _displayAccount() method displays fancybox if customer do not use a social connector to link his PS account * * @category hook collection * @uses * * @param array $aParams * @return array */ private function _displayAccount() { $aAssign = array( 'iCustomerId' => $this->iCustomerLogged, 'bUseJqueryUI' => true, ); $aAssign['bDisplay'] = false; // if one of connectors is active at least if (self::$bConnectorsActive) { require_once(_FPC_PATH_LIB . 'module-dao_class.php'); // include abstract connector require_once(_FPC_PATH_LIB_CONNECTOR . 'base-connector_class.php'); if (FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_DISPLAY_FB_POPIN'] && !empty($GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS']['facebook']['data']['activeConnector']) ) { // set $bSocialCustomerExist = false; // loop on each connector to check if social account already exists - if not, display FB popin account association foreach ($GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS'] as $sName => $aConnector) { if (!empty($GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS'][$sName]['data'])) { // get connector options $aParams = $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS'][$sName]['data']; // get connector $oConnector = BT_BaseConnector::get($sName, $aParams); // check if customer is already logged from FB connector if ($oConnector->existSocialAccount($aAssign['iCustomerId'], 'ps')) { $bSocialCustomerExist = true; } unset($oConnector); } } if (!BT_FPCModuleDao::existCustomerAssociationStatus(FacebookPsConnect::$iShopId, $this->iCustomerLogged) && empty($bSocialCustomerExist) ) { $aAssign['bDisplay'] = true; $aAssign['bSocialCustomerExist'] = true; $aAssign['sConnectorButtonFacebook']= BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_HOOK_PATH . _FPC_TPL_BUTTON_FB); $aAssign['sModuleURI'] = $this->sModuleURI; $aAssign['bFriendlyPermission'] = $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS']['facebook']['data']['permissions']; $aAssign['sBackUri'] = self::$sCurrentURI; } } // get connector options $aParams = $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS']['twitter']['data']; // test if twitter is already configured if (!empty($aParams)) { // get connector $oConnector = BT_BaseConnector::get('twitter', $aParams); // check if customer is already logged from FB connector if ($oConnector->existSocialAccount($aAssign['iCustomerId'], 'ps') && strstr(FacebookPsConnect::$oCookie->email, 'twitter.com') ) { $aAssign['iCustomerId'] = md5(_FPC_MODULE_NAME . 'twitter' . $aAssign['iCustomerId']); $aAssign['sConnector'] = 'twitter'; $aAssign['bTwitterCustomerExist'] = true; $aAssign['bDisplay'] = true; } unset($oConnector); } // use case - data sent for collecting $sRequestData = Tools::getValue('data'); if (!empty($sRequestData)) { $aRequestData = unserialize(gzuncompress(urldecode(base64_decode($sRequestData)))); if (!empty($aRequestData)) { if (empty($aRequestData['ci'])) { $aRequestData['ci'] = md5('collect' . FacebookPsConnect::$oCookie->id_customer); if (!empty($aRequestData['cn']) && !empty($aRequestData['ca']) &&!empty($aRequestData['ct']) && !empty($aRequestData['oi'])) { // execute social collect method $sReturn = FacebookPsConnect::$oModule->HookSocialCollector(base64_decode($aRequestData['cn']), $aRequestData); if (!empty($sReturn)) { // get collect data array $oResponse = BT_FPCModuleTools::jsonDecode($sReturn); if (!empty($oResponse->status)) { $aAssign['bCustomerCollect'] = true; } } } } } } } $aAssign['sModuleURI'] = _FPC_MODULE_URL . 'ws-' . _FPC_MODULE_SET_NAME . '.php'; return ( array('tpl' => _FPC_TPL_HOOK_PATH . _FPC_TPL_CONNECTOR_ACCOUNT, 'assign' => $aAssign) ); } }<file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class PowaTagOrdersCosts extends PowaTagAbstract { /** * Customer Prestashop. * * @var \Customer */ protected $customer; /** * Address Prestashop. * * @var \Address */ public $address; /** * Cart Prestashop. * * @var \Cart */ public $cart; public function __construct(stdClass $datas) { parent::__construct($datas); if (isset($this->datas->order)) { $order = $this->datas->order; } else { $order = current($this->datas->orders); } $this->datas->customer = $order->customer; if (isset($order->paymentCard)) { $this->datas->customer->billingAddress = $order->paymentCard->billingAddress; } if (!isset($this->datas->customer->shippingAddress)) { $this->addError(sprintf($this->module->l('Missing shipping address')), PowaTagErrorType::$OTHER_ADDRESS_ERROR); return; } if (!isset($this->datas->customer->shippingAddress->city)) { $this->addError(sprintf($this->module->l('City is missing')), PowaTagErrorType::$OTHER_ADDRESS_ERROR); return; } if (empty($order->orderLineItems)) { // return SKU_OUT_OF_STOCK as user probably asked for something that became out of stock $this->addError(sprintf($this->module->l('order is empty, probably because product became out of stock')), PowaTagErrorType::$SKU_OUT_OF_STOCK); return; } $this->datas->customer->shippingAddress->phone = isset($order->customer->phone) ? $order->customer->phone : '000000000'; if (isset($this->datas->customer->billingAddress)) { $this->datas->customer->billingAddress->phone = isset($order->customer->phone) ? $order->customer->phone : '000000000'; } $this->datas->orderLineItems = $order->orderLineItems; if (isset($order->vouchers)) { $this->datas->vouchers = $order->vouchers; } if (isset($order->device)) { $this->datas->device = $order->device; } if (isset($this->datas->paymentResult)) { $this->datas->paymentResult = $this->datas->paymentResult; } if (isset($order->orderCostSummary)) { $this->datas->orderCostSummary = $order->orderCostSummary; } $this->checkProductsAreShippable($this->datas->orderLineItems); $this->initObjects(); } /** * Init objects necessary for orders. */ private function initObjects() { $invoice_address = false; $this->customer = $this->getCustomerByEmail($this->datas->customer->emailAddress, true, $this->datas->customer->lastName, $this->datas->customer->firstName, $this->datas->customer->emailAddress); $addresses = $this->customer->getAddresses((int) $this->context->language->id); $find = false; if (!isset($this->datas->customer->shippingAddress->friendlyName)) { $friendlyName = $this->module->l('My address'); } else { $friendlyName = $this->datas->customer->shippingAddress->friendlyName; } foreach ($addresses as $addr) { if ($addr['alias'] == $friendlyName) { $find = true; $address = new Address((int) $addr['id_address']); break; } } if (!$find) { $address = $this->createAddress($this->datas->customer->shippingAddress); } else { $address = $this->createAddress($this->datas->customer->shippingAddress, $address); } if (isset($this->datas->customer->billingAddress)) { $invoice_address = $this->createAddress($this->datas->customer->billingAddress); } if (Validate::isLoadedObject($address)) { $this->address = $address; $this->invoice_address = $address; } else { $this->address = false; return false; } if (Validate::isLoadedObject($invoice_address)) { $this->invoice_address = $invoice_address; } } public function validateOrder() { $id_cart = $this->createCart(); $id_order = false; if (isset($this->datas->paymentResult) && $id_cart) { $order_state = (int) Configuration::get('PS_OS_PAYMENT'); $this->datas->customer = $this->datas->customer; $payment = new PowaTagPayment($this->datas, $id_cart); $id_order = $payment->confirmPayment(true); $error = $payment->getError(); if ($id_order && empty($error)) { $message = Configuration::get('POWATAG_SUCCESS_MSG', $this->context->language->id) != '' ? Configuration::get('POWATAG_SUCCESS_MSG', $this->context->language->id) : 'Success'; } else { $message = 'Error on order creation'; if (!empty($error)) { $message = $error['message']; } $id_order = 0; $id_cart = 0; } } if ($id_cart) { $transaction = new PowaTagTransaction(); $transaction->id_cart = (int) $this->cart->id; $transaction->id_order = (int) $id_order; $transaction->id_customer = (int) $this->customer->id; if (isset($this->datas->device)) { $transaction->id_device = isset($this->datas->device->deviceID) ? $this->datas->device->deviceID : ''; $transaction->ip_address = isset($this->datas->device->ipAddress) ? $this->datas->device->ipAddress : ''; } $transaction->order_state = isset($order_state) ? (int) $order_state : 0; $transaction->save(); $message = Configuration::get('POWATAG_SUCCESS_MSG', $this->context->language->id) != '' ? Configuration::get('POWATAG_SUCCESS_MSG', $this->context->language->id) : 'Success'; } else { if (empty($message)) { $message = 'Cart has not been created'; } } return array($id_cart, $id_order, $message); } private function createCart() { $firstItem = current($this->datas->orderLineItems); $firstVariant = current($firstItem->product->productVariants); if (!$currency = $this->getCurrencyByIsoCode($firstVariant->finalPrice->currency)) { return false; } $this->shippingCost = $this->getShippingCost($this->datas->orderLineItems, $currency, (int) $this->address->id_country, false); $this->shippingCostWt = $this->getShippingCost($this->datas->orderLineItems, $currency, (int) $this->address->id_country, true); $cart = new Cart(); $cart->id_carrier = (int) Configuration::get('POWATAG_SHIPPING'); $cart->delivery_option = serialize(array($this->address->id => $cart->id_carrier.',')); $cart->id_lang = (int) $this->context->language->id; $cart->id_address_delivery = (int) $this->address->id; $cart->id_address_invoice = (int) $this->invoice_address->id; $cart->id_currency = (int) $currency->id; $cart->id_customer = (int) $this->customer->id; $cart->secure_key = $this->customer->secure_key; if (!$cart->save()) { $this->addError($this->module->l('Impossible to save cart'), PowaTagErrorType::$INTERNAL_ERROR); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create cart', PowaTagLogs::ERROR, $this->error['message']); } return false; } if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create cart', PowaTagLogs::SUCCESS, 'Cart ID : '.$cart->id); } $this->cart = $cart; if (!$this->addProductsToCart($cart, $this->address->id_country)) { return false; } return $this->cart->id; } /** * Add Products to cart. * * @param Cart $cart Cart object */ private function addProductsToCart($cart, $codeCountry) { $products = $this->datas->orderLineItems; $country = $this->getCountry($codeCountry); $address = Address::initialize(); $address->id_country = $country->id; if ($products && count($products)) { foreach ($products as $p) { if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::IN_PROGRESS, 'Product : '.$p->product->code); } $product = PowaTagProductHelper::getProductByCode($p->product->code, $this->context->language->id); if (!Validate::isLoadedObject($product)) { $this->addError(sprintf($this->module->l('This product does not exists : %s'), $p->product->code), PowaTagErrorType::$SKU_NOT_FOUND); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : '.$this->error['message']); } return false; } $variants = $p->product->productVariants; foreach ($variants as $variant) { $variantCurrency = $this->getCurrencyByIsoCode($variant->finalPrice->currency); if (!PowaTagValidate::currencyEnable($variantCurrency)) { $this->addError(sprintf($this->module->l('Currency not found : %s'), $variant->code), PowaTagErrorType::$CURRENCY_NOT_SUPPORTED); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : '.$this->error['message']); } return false; } $id_product_attribute = false; $combination = false; if ($id_product_attribute = PowaTagProductAttributeHelper::getCombinationByCode($product->id, $variant->code)) { $combination = new Combination($id_product_attribute); $qtyInStock = PowaTagProductQuantityHelper::getProductQuantity($product, $id_product_attribute); } elseif ($product) { $qtyInStock = PowaTagProductQuantityHelper::getProductQuantity($product); } else { $this->addError(sprintf($this->module->l('This variant does not exist : %s'), $variant->code), PowaTagErrorType::$SKU_NOT_FOUND); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : '.$this->error['message']); } return false; } if ($qtyInStock == 0) { $this->addError(sprintf($this->module->l('No Stock Available')), PowaTagErrorType::$SKU_OUT_OF_STOCK); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : '.$this->error['message']); } return false; } if ($qtyInStock < $p->quantity) { $this->addError(sprintf($this->module->l('Quantity > Stock Count')), PowaTagErrorType::$INSUFFICIENT_STOCK); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : '.$this->error['message']); } return false; } if ($p->quantity < $product->minimal_quantity || ($combination && $combination->minimal_quantity > $p->quantity)) { $this->addError(sprintf($this->module->l('Quantity < minimal quantity for product')), PowaTagErrorType::$OTHER_STOCK_ERROR); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : '.$this->error['message']); } return false; } $cart->updateQty($p->quantity, $product->id, $id_product_attribute); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::SUCCESS, 'Cart ID : '.$cart->id.' - Product ID : '.$product->id); } break; } } } else { $this->addError($this->module->l('No product found in request'), PowaTagErrorType::$SKU_NOT_FOUND); return false; } // add vouchers if (isset($this->datas->vouchers)) { $this->context->cart = $cart; $vouchers = $this->datas->vouchers; if ($vouchers && count($vouchers)) { foreach ($vouchers as $voucher) { $ci = CartRule::getIdByCode($voucher); if (!$ci) { continue; } $cr = new CartRule($ci); if (!$cr) { continue; } if ($cr->checkValidity($this->context, false, true)) { continue; } $this->context->cart->addCartRule($cr->id); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Added voucher', PowaTagLogs::SUCCESS, 'Cart ID : '.$cart->id.' - Voucher : '.$voucher); } } } } return true; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsFeaturesSettings', false)) return; class AuctionsFeaturesSettings extends CoreModuleSettings { const SHOW_FORM_HINTS = 'auct_app_show_form_hints'; const PERMISSIONS_SET_START_DATE = 'auct_perm_set_start_date'; const PERMISSIONS_SET_END_DATE = 'auct_perm_set_end_date'; const PERMISSIONS_SET_BUY_NOW = 'auct_perm_set_buy_now'; const PERMISSIONS_SET_INCREMENT_RULES = 'auct_perm_set_increment_rules'; const PERMISSIONS_SET_PROXY_BIDDING = 'auct_perm_set_proxy_bidding'; const PERMISSIONS_SET_POPCORN_BIDDING = 'auct_perm_set_popcorn_bidding'; const PERMISSIONS_SHOW_RESTART_AUCTION = 'auct_perm_show_restart_func'; const PERMISSIONS_SHOW_REMIND_AUCTION = 'auct_perm_show_remind_func'; const PERMISSIONS_SHOW_FINISH_AUCTION = 'auct_perm_show_finish_func'; const PERMISSIONS_SHOW_ACCEPT_AUCTION = 'auct_perm_show_accept_func'; const PERMISSIONS_SHOW_WATCH_AUCTION = 'auct_perm_show_watch_func'; protected $submit_action = 'submitBackoffice'; public function getTitle() { return $this->l('Features'); } public function showForm($tab_index) { $fields_form = array(); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Backoffice'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('Show "Starts at"'), 'name' => self::PERMISSIONS_SET_START_DATE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SET_START_DATE.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SET_START_DATE.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable setting start date on auction form') ), array( 'type' => 'radio', 'label' => $this->l('Show "Ends at"'), 'name' => self::PERMISSIONS_SET_END_DATE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SET_END_DATE.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SET_END_DATE.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable setting end date on auction form') ), array( 'type' => 'radio', 'label' => $this->l('Show "Buy Now"'), 'name' => self::PERMISSIONS_SET_BUY_NOW, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SET_BUY_NOW.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SET_BUY_NOW.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable setting "Buy Now" option on auction form') ), array( 'type' => 'radio', 'label' => $this->l('Show "Bidding Increment Rules"'), 'name' => self::PERMISSIONS_SET_INCREMENT_RULES, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SET_INCREMENT_RULES.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SET_INCREMENT_RULES.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable setting "Bidding Increment Rules" option on auction form') ), array( 'type' => 'radio', 'label' => $this->l('Show "Proxy bidding"'), 'name' => self::PERMISSIONS_SET_PROXY_BIDDING, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SET_PROXY_BIDDING.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SET_PROXY_BIDDING.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable setting "Proxy bidding" option on auction form') ), array( 'type' => 'radio', 'label' => $this->l('Show "Popcorn bidding"'), 'name' => self::PERMISSIONS_SET_POPCORN_BIDDING, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SET_POPCORN_BIDDING.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SET_POPCORN_BIDDING.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable setting "Popcorn bidding" option on auction form') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Options'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('Restart auction'), 'name' => self::PERMISSIONS_SHOW_RESTART_AUCTION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SHOW_RESTART_AUCTION.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SHOW_RESTART_AUCTION.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable restarting auctions at any time feature') ), array( 'type' => 'radio', 'label' => $this->l('Finish auction'), 'name' => self::PERMISSIONS_SHOW_FINISH_AUCTION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SHOW_FINISH_AUCTION.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SHOW_FINISH_AUCTION.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable finishing auctions at any time feature') ), array( 'type' => 'radio', 'label' => $this->l('Accept auction'), 'name' => self::PERMISSIONS_SHOW_ACCEPT_AUCTION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SHOW_ACCEPT_AUCTION.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SHOW_ACCEPT_AUCTION.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable accepting winner even if the reserve price was not reached') ), array( 'type' => 'radio', 'label' => $this->l('Remind auction'), 'name' => self::PERMISSIONS_SHOW_REMIND_AUCTION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SHOW_REMIND_AUCTION.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SHOW_REMIND_AUCTION.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable sending remind notifications when the winner did not check out the product') ), array( 'type' => 'radio', 'label' => $this->l('Watch auction'), 'name' => self::PERMISSIONS_SHOW_WATCH_AUCTION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::PERMISSIONS_SHOW_WATCH_AUCTION.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::PERMISSIONS_SHOW_WATCH_AUCTION.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable subscribing to the auction feature') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Additional'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('Show hint blocks'), 'name' => self::SHOW_FORM_HINTS, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::SHOW_FORM_HINTS.'_on', 'value' => 1, 'label' => $this->l('Enabled') ), array( 'id' => self::SHOW_FORM_HINTS.'_off', 'value' => 0, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Enable blue description blocks on the backoffice forms') ) ) ) ); return $this->renderForm($fields_form, $tab_index); } public function init() { $this->setValue(self::SHOW_FORM_HINTS, (boolean)Configuration::get(self::SHOW_FORM_HINTS)); $this->setValue(self::PERMISSIONS_SET_START_DATE, (boolean)Configuration::get(self::PERMISSIONS_SET_START_DATE)); $this->setValue(self::PERMISSIONS_SET_END_DATE, (boolean)Configuration::get(self::PERMISSIONS_SET_END_DATE)); $this->setValue(self::PERMISSIONS_SET_BUY_NOW, (boolean)Configuration::get(self::PERMISSIONS_SET_BUY_NOW)); $this->setValue(self::PERMISSIONS_SET_INCREMENT_RULES, (boolean)Configuration::get(self::PERMISSIONS_SET_INCREMENT_RULES)); $this->setValue(self::PERMISSIONS_SET_PROXY_BIDDING, (boolean)Configuration::get(self::PERMISSIONS_SET_PROXY_BIDDING)); $this->setValue(self::PERMISSIONS_SET_POPCORN_BIDDING, (boolean)Configuration::get(self::PERMISSIONS_SET_POPCORN_BIDDING)); $this->setValue(self::PERMISSIONS_SHOW_RESTART_AUCTION, (boolean)Configuration::get(self::PERMISSIONS_SHOW_RESTART_AUCTION)); $this->setValue(self::PERMISSIONS_SHOW_FINISH_AUCTION, (boolean)Configuration::get(self::PERMISSIONS_SHOW_FINISH_AUCTION)); $this->setValue(self::PERMISSIONS_SHOW_ACCEPT_AUCTION, (boolean)Configuration::get(self::PERMISSIONS_SHOW_ACCEPT_AUCTION)); $this->setValue(self::PERMISSIONS_SHOW_REMIND_AUCTION, (boolean)Configuration::get(self::PERMISSIONS_SHOW_REMIND_AUCTION)); $this->setValue(self::PERMISSIONS_SHOW_WATCH_AUCTION, (boolean)Configuration::get(self::PERMISSIONS_SHOW_WATCH_AUCTION)); } public function install() { Configuration::updateValue(self::SHOW_FORM_HINTS, self::YES); Configuration::updateValue(self::PERMISSIONS_SET_START_DATE, self::YES); Configuration::updateValue(self::PERMISSIONS_SET_END_DATE, self::YES); Configuration::updateValue(self::PERMISSIONS_SET_BUY_NOW, self::YES); Configuration::updateValue(self::PERMISSIONS_SET_INCREMENT_RULES, self::YES); Configuration::updateValue(self::PERMISSIONS_SET_PROXY_BIDDING, self::YES); Configuration::updateValue(self::PERMISSIONS_SET_POPCORN_BIDDING, self::YES); Configuration::updateValue(self::PERMISSIONS_SHOW_RESTART_AUCTION, self::YES); Configuration::updateValue(self::PERMISSIONS_SHOW_FINISH_AUCTION, self::YES); Configuration::updateValue(self::PERMISSIONS_SHOW_ACCEPT_AUCTION, self::YES); Configuration::updateValue(self::PERMISSIONS_SHOW_REMIND_AUCTION, self::YES); Configuration::updateValue(self::PERMISSIONS_SHOW_WATCH_AUCTION, self::YES); return true; } public function uninstall() { Configuration::deleteByName(self::SHOW_FORM_HINTS); Configuration::deleteByName(self::PERMISSIONS_SET_START_DATE); Configuration::deleteByName(self::PERMISSIONS_SET_END_DATE); Configuration::deleteByName(self::PERMISSIONS_SET_BUY_NOW); Configuration::deleteByName(self::PERMISSIONS_SET_INCREMENT_RULES); Configuration::deleteByName(self::PERMISSIONS_SET_PROXY_BIDDING); Configuration::deleteByName(self::PERMISSIONS_SET_POPCORN_BIDDING); Configuration::deleteByName(self::PERMISSIONS_SHOW_RESTART_AUCTION); Configuration::deleteByName(self::PERMISSIONS_SHOW_FINISH_AUCTION); Configuration::deleteByName(self::PERMISSIONS_SHOW_ACCEPT_AUCTION); Configuration::deleteByName(self::PERMISSIONS_SHOW_REMIND_AUCTION); Configuration::deleteByName(self::PERMISSIONS_SHOW_WATCH_AUCTION); return true; } public function update() { Configuration::updateValue(self::SHOW_FORM_HINTS, (boolean)Tools::getValue(self::SHOW_FORM_HINTS)); Configuration::updateValue(self::PERMISSIONS_SET_START_DATE, (boolean)Tools::getValue(self::PERMISSIONS_SET_START_DATE)); Configuration::updateValue(self::PERMISSIONS_SET_END_DATE, (boolean)Tools::getValue(self::PERMISSIONS_SET_END_DATE)); Configuration::updateValue(self::PERMISSIONS_SET_BUY_NOW, (boolean)Tools::getValue(self::PERMISSIONS_SET_BUY_NOW)); Configuration::updateValue(self::PERMISSIONS_SET_INCREMENT_RULES, (boolean)Tools::getValue(self::PERMISSIONS_SET_INCREMENT_RULES)); Configuration::updateValue(self::PERMISSIONS_SET_PROXY_BIDDING, (boolean)Tools::getValue(self::PERMISSIONS_SET_PROXY_BIDDING)); Configuration::updateValue(self::PERMISSIONS_SET_POPCORN_BIDDING, (boolean)Tools::getValue(self::PERMISSIONS_SET_POPCORN_BIDDING)); Configuration::updateValue(self::PERMISSIONS_SHOW_RESTART_AUCTION, (boolean)Tools::getValue(self::PERMISSIONS_SHOW_RESTART_AUCTION)); Configuration::updateValue(self::PERMISSIONS_SHOW_FINISH_AUCTION, (boolean)Tools::getValue(self::PERMISSIONS_SHOW_FINISH_AUCTION)); Configuration::updateValue(self::PERMISSIONS_SHOW_ACCEPT_AUCTION, (boolean)Tools::getValue(self::PERMISSIONS_SHOW_ACCEPT_AUCTION)); Configuration::updateValue(self::PERMISSIONS_SHOW_REMIND_AUCTION, (boolean)Tools::getValue(self::PERMISSIONS_SHOW_REMIND_AUCTION)); Configuration::updateValue(self::PERMISSIONS_SHOW_WATCH_AUCTION, (boolean)Tools::getValue(self::PERMISSIONS_SHOW_WATCH_AUCTION)); return true; } protected function validate() { $condition = true; $condition &= Validate::isBool(Tools::getValue(self::SHOW_FORM_HINTS)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SET_START_DATE)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SET_END_DATE)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SET_BUY_NOW)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SET_INCREMENT_RULES)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SET_PROXY_BIDDING)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SET_POPCORN_BIDDING)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SHOW_RESTART_AUCTION)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SHOW_FINISH_AUCTION)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SHOW_ACCEPT_AUCTION)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SHOW_REMIND_AUCTION)); $condition &= Validate::isBool(Tools::getValue(self::PERMISSIONS_SHOW_WATCH_AUCTION)); return $condition; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionMailingDataManager', false)) return; class ProductAuctionMailingDataManager { /** * * @return ProductAuction[] */ public static function getCollectionToSend($limit = null) { $product_auction_mailing_fields = CoreModuleTools::convertFields(ProductAuctionMailing::$definition, array( 'prefix' => 'pam' )); $winner_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'wc', 'alias' => 'winner_customer' )); $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $employee_fields = CoreModuleTools::convertFields(Employee::$definition, array( 'prefix' => 'e' )); $language_fields = CoreModuleTools::convertFields(Language::$definition, array( 'prefix' => 'l' )); $shop_fields = CoreModuleTools::convertFields(Shop::$definition, array( 'prefix' => 's' )); $cart_fields = CoreModuleTools::convertFields(Cart::$definition, array( 'prefix' => 'ca' )); $currency_fields = CoreModuleTools::convertFields(Currency::$definition, array( 'prefix' => 'cr' )); $query = ' SELECT '.implode(', ', $product_auction_mailing_fields).', '.implode(', ', $winner_customer_fields).', '.implode(', ', $product_fields).', '.implode(', ', $customer_fields).', '.implode(', ', $employee_fields).', '.implode(', ', $language_fields).', '.implode(', ', $shop_fields).', '.implode(', ', $cart_fields).', '.implode(', ', $currency_fields).' FROM `'._DB_PREFIX_.'product_auction_mailing` pam LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pam.id_customer = c.id_customer) LEFT JOIN `'._DB_PREFIX_.'employee` e ON (pam.id_employee = e.id_employee) LEFT JOIN `'._DB_PREFIX_.'lang` l ON ((pam.id_customer IS NOT null AND c.id_lang = l.id_lang) OR (pam.id_employee IS NOT null and e.id_lang = l.id_lang)) LEFT JOIN `'._DB_PREFIX_.'customer` wc ON (pam.data_winner_id_customer = wc.id_customer) INNER JOIN `'._DB_PREFIX_.'product` p ON (pam.id_product = p.id_product) INNER JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product AND pl.id_lang = l.id_lang) INNER JOIN `'._DB_PREFIX_.'shop` s ON (p.id_shop_default = s.id_shop) LEFT JOIN `'._DB_PREFIX_.'cart` ca ON (pam.id_cart = ca.id_cart) LEFT JOIN `'._DB_PREFIX_.'currency` cr ON (pam.id_currency = ca.id_currency) WHERE pam.sent_at IS null ORDER BY pam.id_product_auction_mailing ASC '.($limit ? 'LIMIT '.(int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auction_mailing_collection = array(); if (!empty($result)) { $classes = array( 'ProductAuctionMailing', 'WinnerCustomer', 'Product', 'Customer', 'Employee', 'Language', 'Shop', 'Cart', 'Currency' ); $options = array( 'WinnerCustomer' => array( 'class' => 'Customer', 'alias' => 'winner_customer' ) ); $result = CoreModuleTools::hydrateCollection($classes, $result, null, $options); foreach ($result['ProductAuctionMailing'] as $product_auction_mailing) { if (isset($result['Product'][$product_auction_mailing->id_product])) $product_auction_mailing->product = $result['Product'][$product_auction_mailing->id_product]; if (isset($result['WinnerCustomer'][$product_auction_mailing->data_winner_id_customer])) $product_auction_mailing->winner = $result['WinnerCustomer'][$product_auction_mailing->data_winner_id_customer]; if (isset($result['Customer'][$product_auction_mailing->id_customer])) $product_auction_mailing->customer = $result['Customer'][$product_auction_mailing->id_customer]; if (isset($result['Employee'][$product_auction_mailing->id_employee])) $product_auction_mailing->employee = $result['Employee'][$product_auction_mailing->id_employee]; if (isset($result['Language'][$product_auction_mailing->id_lang])) $product_auction_mailing->language = $result['Language'][$product_auction_mailing->id_lang]; if (isset($result['Shop'][$product_auction_mailing->id_shop])) $product_auction_mailing->shop = $result['Shop'][$product_auction_mailing->id_shop]; if (isset($result['Cart'][$product_auction_mailing->id_cart])) $product_auction_mailing->cart = $result['Cart'][$product_auction_mailing->id_cart]; if (isset($result['Currency'][$product_auction_mailing->id_currency])) $product_auction_mailing->currency = $result['Currency'][$product_auction_mailing->id_currency]; $product_auction_mailing_collection[] = $product_auction_mailing; } } return $product_auction_mailing_collection; } /** * * @param array $product_auction_mailing_ids */ public static function clearProductAuctionMailingWithIds($product_auction_mailing_ids) { if (empty($product_auction_mailing_ids)) return; return Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.ProductAuctionMailing::$definition['table'].'` SET sent_at = '.time().' WHERE `id_product_auction_mailing` IN('.implode(',', array_map('intval', $product_auction_mailing_ids)).')'); } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{auctions}prestashop>auctionsemailsender_6b4640e20074f8aca30c10ae3eb9685d'] = 'Terminou o leilão'; $_MODULE['<{auctions}prestashop>auctionsemailsender_6695943ad93e42d56a08261634f2d4ec'] = 'Nova oferta no leilão'; $_MODULE['<{auctions}prestashop>auctionsemailsender_0a1bc16de755bd3d22179328bce370d2'] = 'Colocou a oferta mais alta'; $_MODULE['<{auctions}prestashop>auctionsemailsender_1f21d19ebc837aaf58c857cfce70f4c2'] = 'Alguém fez uma oferta mais alta'; $_MODULE['<{auctions}prestashop>auctionsemailsender_25463acbe88f5a7cac598391ca670a72'] = 'Você ganhou o leilão!'; $_MODULE['<{auctions}prestashop>auctionsemailsender_601d9680d375e5bb178436a7a47cc61f'] = 'A sua oferta foi aceite!'; $_MODULE['<{auctions}prestashop>auctionsemailsender_c89c970c280c80d8511bd3d71266cd36'] = 'O leilão está aguardando a finalização da compra'; $_MODULE['<{auctions}prestashop>auctionsemailsender_d1f401271c79c8b815e9cb07409eb73c'] = 'O leilão foi reiniciado'; $_MODULE['<{auctions}prestashop>auctions_1acef523f61f49c38ef17356cb13786b'] = 'Leilões'; $_MODULE['<{auctions}prestashop>auctions_c77891139f239889619eb56859712506'] = 'Adicone a funcionalidade de leilões à sua loja prestashop'; $_MODULE['<{auctions}prestashop>auctions_9d5b40ff49295ac0b4a5a13a88ccd285'] = ' A extensão cURL tem que estar ativada no seu servidor para usar este módulo'; $_MODULE['<{auctions}prestashop>auctions_ea2eb89cd24b00200260231a79eae5f1'] = 'Não tem acesso para editar os detalhes do leilão'; $_MODULE['<{auctions}prestashop>auctions_e91209929df975f7276bd8601889f615'] = 'Não tem acesso para adicionar detalhes ao leilão.'; $_MODULE['<{auctions}prestashop>auctions_1768859972d9f45b43f6755242490943'] = 'Deve gravar este produto antes de adicionar detalhes ao leilão'; $_MODULE['<{auctions}prestashop>auctions_e33bee3315cfcba4bf9c73798892998d'] = 'Últimos leilões'; $_MODULE['<{auctions}prestashop>auctions_09654b12350ebfcd8c3d3b2c3b1983e6'] = 'Não há Últimos leilões neste momento'; $_MODULE['<{auctions}prestashop>auctions_b3866ac96226a56bdab09d910eae29c9'] = 'Todos os últimos'; $_MODULE['<{auctions}prestashop>auctions_d3da97e2d9aee5c8fbe03156ad051c99'] = 'Mais'; $_MODULE['<{auctions}prestashop>auctions_4351cfebe4b61d8aa5efa1d020710005'] = 'Ver'; $_MODULE['<{auctions}prestashop>auctions_b7c0efb135647306d6f789c4afb6f121'] = 'Leilões terminando'; $_MODULE['<{auctions}prestashop>auctions_fc49663c1491dec7c35df8567eec138d'] = 'Não há leilões a terminar neste momento'; $_MODULE['<{auctions}prestashop>auctions_211659e97a0cc79c466c3436f221794b'] = 'Todos a terminar'; $_MODULE['<{auctions}prestashop>auctions_8ac34ce12ca7e5139197675652b2b167'] = 'Leilões populares'; $_MODULE['<{auctions}prestashop>auctions_270e9d4c24c53bf58b0de63abce59fbc'] = 'Não há leilões populares nesta altura'; $_MODULE['<{auctions}prestashop>auctions_f39f1150704432effe2478938b4f2768'] = 'Todos os populares'; $_MODULE['<{auctions}prestashop>auctions_e60d143810b5e7455d8f6527478148a9'] = 'Leilões em destaque'; $_MODULE['<{auctions}prestashop>auctions_f633d5ee0ff10a3104b61a0988224dd1'] = 'Não há leilões em destaque neste momento'; $_MODULE['<{auctions}prestashop>auctions_6a7856ee7793df295047fef99e9a8a23'] = 'Todos em destaque'; $_MODULE['<{auctions}prestashop>auctions_adef6b4076aaceea523f43cbdab73bcd'] = 'Não pode adicionar este leilão ao carrinho.'; $_MODULE['<{auctions}prestashop>auctions_ace1d137a73af7e93d57d9896c1c4fbb'] = 'Não se iniciou'; $_MODULE['<{auctions}prestashop>auctions_8f3d10eb21bd36347c258679eba9e92b'] = 'Terminado'; $_MODULE['<{auctions}prestashop>auctionsmyauctionscontroller_90d77b86534fedc93c9c992ae10cade4'] = 'Minhas licitações'; $_MODULE['<{auctions}prestashop>auctionsmyauctionscontroller_2b52a9e614964c3237aaf4917efdeff6'] = 'Os meus items ganhos'; $_MODULE['<{auctions}prestashop>auctionsmyauctionscontroller_2938446b0add768774e595f8b8e2cd6a'] = 'Meu histórico de licitações'; $_MODULE['<{auctions}prestashop>auctionsmyauctionscontroller_cacdba086b9c4ae0599b27df9c2870cc'] = 'Lista de leilões que acompanho'; $_MODULE['<{auctions}prestashop>auctionsmyauctionscontroller_3d4e3acd2c5b425db1b08f00cc2ad2df'] = 'Você não tem qualquer leilão.'; $_MODULE['<{auctions}prestashop>auctionsmyauctionscontroller_a958dbb46713e59856c35f89e5092a5e'] = 'Voltar à sua conta'; $_MODULE['<{auctions}prestashop>auctionsmyauctionscontroller_8cf04a9734132302f96da8e113e80ce5'] = 'Início'; $_MODULE['<{auctions}prestashop>auctionsmyauctionscontroller_ff837d4be2f632591a54182a22c85f6f'] = 'Tem que fazer o login para gerir os seus leilões'; $_MODULE['<{auctions}prestashop>coremodule_24fec0549cc3296697f5521be787f26b'] = 'This version of the% s module can only be installed on the Following versions of the Prestashop:% s'; $_MODULE['<{auctions}prestashop>coremodule_6a793d2fecdc5ba402a4410097d52988'] = 'Arquivos de \"/ modules /% s / override\" pasta não foram copiados para o diretório \"override\".'; $_MODULE['<{auctions}prestashop>coremodule_a3b8f87c4462929982eb8051c1102eac'] = 'Não foi possível desinstalar a base de dados dos %s modulos'; $_MODULE['<{auctions}prestashop>coremodule_5c0b05c984da5120aea9e90b507fb3a2'] = 'Não foi possível instalar a base de dados dos %s modulos'; $_MODULE['<{auctions}prestashop>coremodule_6fbd7933c1f31e4239d8c341671cc75c'] = 'Não foi possível atualizar a base de dados dos %s modulos'; $_MODULE['<{auctions}prestashop>coremodule_1b58ec2bb7e7562e5ac0a67f1dc627d6'] = 'Ganchos reinstalados'; $_MODULE['<{auctions}prestashop>coremodule_4af8d834bb8bf1c8a6d20c7d0b826c5e'] = 'BD reinstalada'; $_MODULE['<{auctions}prestashop>coremodule_929e69092c9160e35e4c8a6b63853133'] = 'BD desinstalada'; $_MODULE['<{auctions}prestashop>coremodule_3249e3ec3816fdafe686d0a775c599f9'] = 'Não foi possível registar %s ganchos no %s modulo.'; $_MODULE['<{auctions}prestashop>coremodule_a1e89854a31754c43c7ce9418a189748'] = 'Não foi possível instalar %s separador no %s modulo.'; $_MODULE['<{auctions}prestashop>coremodule_624032888fbb2b88aedeecbb5071c485'] = 'Não foi possível desinstalar %s (%s) separador nos %s modulo.'; $_MODULE['<{auctions}prestashop>coremodule_615999cf273cd4eb8089e8156b5c80b1'] = 'Não foi possível instalar %s definições no %s modulo.'; $_MODULE['<{auctions}prestashop>coremodule_05a85e54439e0d66dd3e0a8939264827'] = 'Não foi possível desinstalar %s definições nos %s modulo.'; $_MODULE['<{auctions}prestashop>coremodulesettings_254f642527b45bc260048e30704edb39'] = 'Configuração'; $_MODULE['<{auctions}prestashop>coremodulesettings_c6716cc4f90f02684947a2a859c6f7fa'] = 'Erro enquanto gravava a confirguração'; $_MODULE['<{auctions}prestashop>coremodulesettings_c9cc8cce247e49bae79f15173ce97354'] = 'Gravar'; $_MODULE['<{auctions}prestashop>coremodulesettings_db5eb84117d06047c97c9a0191b5fffe'] = 'Suporte'; $_MODULE['<{auctions}prestashop>coremodulesettings_d354bbb7b0736cda3cd9e50a905cfe4d'] = 'Se tiver alguma questão por favor contacte'; $_MODULE['<{auctions}prestashop>coremodulecolumnformatter_4cc12dc9c26dd705f3a1bed6c2a2a1ac'] = 'Agora +%s'; $_MODULE['<{auctions}prestashop>coremodulecolumnformatter_fc7b8f00e2016c316ff96aa32b974bd3'] = 'Agora -%s'; $_MODULE['<{auctions}prestashop>coremodulecolumnformatter_d90561e0a1bec8494c7b989c34420217'] = 'Data início + %s'; $_MODULE['<{auctions}prestashop>coremodulecolumnformatter_0fd9e5bb839e7a7f9a6c62eb8a6407a9'] = 'Data iníco + %'; $_MODULE['<{auctions}prestashop>hiddenauctionscustomername_ab86a1e1ef70dff97959067b723c5c24'] = 'eu'; $_MODULE['<{auctions}prestashop>hiddenauctionscustomername_13bbf54a6850c393fb8d1b2b3bba997b'] = '******'; $_MODULE['<{auctions}prestashop>productauctionoffer_3ac705f2acd51a4613f9188c05c91d0d'] = 'Valido'; $_MODULE['<{auctions}prestashop>productauctionoffer_4bbb8f967da6d1a610596d7257179c2b'] = 'Inválido'; $_MODULE['<{auctions}prestashop>productauctionoffer_85144ab5880edc8513c39cfeb1bd5a5e'] = 'Vencedor'; $_MODULE['<{auctions}prestashop>productauctionoffer_d109ac74df282488efd1dd7621a847d2'] = 'Retirado'; $_MODULE['<{auctions}prestashop>productauction_e599161956d626eda4cb0a5ffb85271c'] = 'Inativo'; $_MODULE['<{auctions}prestashop>productauction_5bda814c4aedb126839228f1a3d92f09'] = 'Decorrendo'; $_MODULE['<{auctions}prestashop>productauction_643562a9ae7099c8aabfdc93478db117'] = 'Processando'; $_MODULE['<{auctions}prestashop>productauction_8f3d10eb21bd36347c258679eba9e92b'] = 'Terminado'; $_MODULE['<{auctions}prestashop>productauction_7d8e944117a45c8dde9a8e2779ca61de'] = 'Finalizado (checked out)'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_f11b368cddfe37c47af9b9d91c6ba4f0'] = 'Nome completo'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_20db0bfeecd8fe60533206a2b5e9891a'] = 'Primeiro nome'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_8d3f5eff9c40ee315d452392bed5309b'] = 'Apelido'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_ce8ae9da5b7cd6c3df2929543a9af92d'] = 'Email'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_6758c19ef3f1e6b404caaf4fc64bb733'] = 'Alias email'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_1771b8284280660537e3e533f88af3b2'] = 'Nome de utilizador (nickname)'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_7acdf85c69cc3c5305456a293524386e'] = 'Oculto'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_a1c58e94227389415de133efdf78ea6e'] = 'Aparênca'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_0db377921f4ce762c62526131097968f'] = 'Geral'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_9cc66dcc868f2213439d4b38867dd72e'] = 'Nome de Licitador'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_c885472c2d13dc0baa1ed7b05633696e'] = 'Escolha como o nome do licitador vencedor será mostrado'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_e271a4596c24eed9cb455736c942c425'] = 'Comprimento máximo do nome do licitador'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_f397c4af4f09690ff24156e5c10f77ff'] = 'Introduza o número máximo de caracteres para o nome do Licitador'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_c790b867b70b8275f8b6b7d7870c28fe'] = 'Detalhes do leilão'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_f6d8f10519d6af4e40d3453d50c46714'] = 'Mostrar a hora de início'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_00d23a76e43b46dae9ec7aa9dcbebb32'] = 'Ativo'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_b9f5c797ebbf55adccdd8539a65a0241'] = 'Desativo'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_ead0252bcb4c6e4514d3dd8234f988a7'] = 'Mostrar a hora de fecho'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_b117e056a52daecf9956f394a36002d6'] = 'Mostrar a duração'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_4cc1b8534c7948b6f63232c13bb3b3d1'] = 'Mostrar o número de licitações'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_740571fcc8aece0eca01e3aacbb51b15'] = 'Mostrar a lista de licitações'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_5c6ba25104401c9ee0650230fc6ba413'] = 'Separador'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_c89686a387d2b12b3c729ce35a0bcb5b'] = 'Janela'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_f44d6196b2423ff4f48b380e6c2a37f5'] = 'Mostrar o licitador vencedor'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_60e3049f515c89f6315d8315ae25658c'] = 'Mostrar o preço inicial'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_1f1e07eee50620404998a20ac3c442e9'] = 'Mostrar a contagem decrescente'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_84a8921b25f505d0d2077aeb5db4bc16'] = 'Estático'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_971fd8cc345d8bd9f92e9f7d88fdf20c'] = 'Dinâmico'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_b1dac2f1f7df89baf1c89f23e82a7d13'] = 'Formato do contador'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_46a0f1a94acfa5b94096cbe49b5436c2'] = 'Formato para tempo deixou de contagem regressiva. Maiúsculas para sempre exibido, minúsculas somente se não zero, semanas \'W\', dia \'D\', hora \'H\', minutos \'M\', segundo \'S\''; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_5318fd056a25b00af3264333b3d1fe8d'] = 'Lista de leilões'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_cbf99d4c4eb420d77f3463d57c4d1553'] = 'Blocos do lado'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_cb2e5f2a9cfc0fc7ead88afe92e7c888'] = 'Mostrar o preço corrente'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_349429a698a743119eb0c539c4fe4789'] = 'Os meus leilões'; $_MODULE['<{auctions}prestashop>auctionsappearancesettings_9790b70b0772c3b35108155cf340f315'] = 'Emails'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_04c4f9f595c4f21d1de65eb07056c15a'] = 'Blocos'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_e33bee3315cfcba4bf9c73798892998d'] = 'Últimos leilões'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_2a63f555989152ba866b43a1faacd680'] = 'Limiar '; $_MODULE['<{auctions}prestashop>auctionsblockssettings_c78e0342693cd05c7a09382439d619c8'] = 'Decida quantos segundos depois de começar o leilão, o mesmo é considerado \"último\". Se \"0\", esta opção é desativada'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_cbf99d4c4eb420d77f3463d57c4d1553'] = 'Blocos laterais'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_b9f5c797ebbf55adccdd8539a65a0241'] = 'Desativado'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_945d5e233cf7d6240f6b783b36a374ff'] = 'Esquerda'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_92b09c7c48c520c3c55e497875da437c'] = 'Direita'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_78067b381789876958f79eb3f714bf3d'] = 'Decida onde o bloco será localizado na página'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_62d86174ba04c2313712ec610b26ac4d'] = 'Contagem dos items no lado'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_62e365b310a0217a0aae8eb7f1efa375'] = 'Decida quantos items serão mostrados no bloco'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_7ae4d104ca0aba15734021a427a7b39e'] = 'Bloco Home (início)'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_00d23a76e43b46dae9ec7aa9dcbebb32'] = 'Ativado'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_1fc0a2d9e19e59c6de272a294584c213'] = 'Decida se o módulo \"Últimos leilões\" aparecerá na página principal (home)'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_19f339d07ef3e22b8536555d68625521'] = 'Contagem dos items na página principal (home)'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_b7c0efb135647306d6f789c4afb6f121'] = 'Leilões terminando'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_9a8166047d5f2ee6ff77bf92a9695669'] = 'Decida quantos segundos antes do fim do leilão, o mesmo é considerado \"Terminando\". Se \"0\", esta opção é desativada'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_64ca9d2c614c04994f01994b111ad4fd'] = 'Decida se o bloco \" Leilões terminando\" será mostrado na pagina principal (home)'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_8ac34ce12ca7e5139197675652b2b167'] = 'Leilões populares'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_e348e3f75ebdabc88efb730424864e01'] = 'Decida quantas licitações num leilão, faz que o mesmo seja \"Popular\". Se \"0\" esta opção será desativada'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_4766cfed7ff695aa8b563c43c726a50c'] = 'Decida se o bloco \"Leilões populares\" será mostrado na página principal.'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_e60d143810b5e7455d8f6527478148a9'] = 'Leilões em destaque'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_3adbdb3ac060038aa0e6e6c138ef9873'] = 'Categoria'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_da1e7bb781da5fe5832aeb9f9a6f2587'] = 'Decida qual á categoria que faz o leilão ser \"destacado\"'; $_MODULE['<{auctions}prestashop>auctionsblockssettings_fa8ec3aeeb4418d07ea100f8ccc91e4f'] = 'Decida se o bloco \"Leilões destacados\" aparecerá na página principal (home)'; $_MODULE['<{auctions}prestashop>auctionscronsettings_f07df04fd61cf1288efe070d50ae0b7f'] = 'Tarefas de cron'; $_MODULE['<{auctions}prestashop>auctionscronsettings_332e1df622cdfd832a8bb3b081ffc893'] = 'correr a cada 1 minuto ou o mais devagar possível'; $_MODULE['<{auctions}prestashop>auctionscronsettings_d6e75013e088fc5c86a14721e69aef76'] = 'correr uma vez por dia'; $_MODULE['<{auctions}prestashop>auctionscronsettings_30e11ece394c8b203678433d30a92745'] = 'Coloque este uRL no separador de cron para corre-lo periódicamente'; $_MODULE['<{auctions}prestashop>auctionscronsettings_643562a9ae7099c8aabfdc93478db117'] = 'Processando'; $_MODULE['<{auctions}prestashop>auctionscronsettings_ee97be03cb04119af45014d815621ce1'] = 'Comando'; $_MODULE['<{auctions}prestashop>auctionscronsettings_fbef0c7d92eeefb93f160419edad9ce8'] = 'Este comando cron tem que ser definido no painel de admininistração da hospedagem'; $_MODULE['<{auctions}prestashop>auctionscronsettings_835b732bbba0fcb6bf3e7b33ca2ab559'] = 'Contagem de items'; $_MODULE['<{auctions}prestashop>auctionscronsettings_73f2bad0064a365d431ca1a2bf2419f4'] = 'Decida quantos itens serão processados duraante a execução de uma tarefa de cron'; $_MODULE['<{auctions}prestashop>auctionscronsettings_c8896d70102b6711dc07718df1996885'] = 'Mailing'; $_MODULE['<{auctions}prestashop>auctionscronsettings_2fc383c67ed70aa7f93a5ece39b4abf0'] = 'Arquivando'; $_MODULE['<{auctions}prestashop>auctionscronsettings_766aae7bbe0d9e792edc6ee82cf3a62d'] = 'Arquivar os leilões depois'; $_MODULE['<{auctions}prestashop>auctionscronsettings_3b22e1849f556591cd29f36b8d3ea686'] = 'Defina como os velhos leilões serão arquivados (em dias)'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_98f770b0af18ca763421bac22b4b6805'] = 'Características'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_d960986ff0c20cac70c1ce64456f9020'] = 'Backoffice'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_f191618696b55885420ccecfa9e31ae7'] = 'Mostrar \"Começa a\"'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_00d23a76e43b46dae9ec7aa9dcbebb32'] = 'Ativado'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_b9f5c797ebbf55adccdd8539a65a0241'] = 'Desativado'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_7ccbd058e48bde28b0bc83a98e7c6e50'] = 'Ativar no formulário do leilão a definição da data de começo'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_24e572eb60d20b4398ecd71d83c250bd'] = 'Mostrar\" acaba em\"'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_1a5287100a8e7988bcc6d50f53d5260c'] = 'Ativara a definição de data final no formulário do leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_edb4d22aee0b8231614d58bd030eaf89'] = 'Mostrar\" Comprar agora\"'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_2a4479fe3f72ee1a3830590e5ce73907'] = 'Ativar a opção de definição \" Comprar agora\" no formulário do leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_95638a0a3716dfc5f5275868e8809a8c'] = 'Mostrar\" Regras de incremento de licitação\"'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_0210ab3d2a6c0ec45ef79b644485e2cb'] = 'Ativar a opção de definir \"Regras de incremento de licitação\" no formulário do leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_3857a626bbf7a1dcf362f797c2a16388'] = 'Mostrar \" licitação proxy\"'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_4074dae80728682f8ecc7432c8e0f8ee'] = 'Permitir a definição de \"Licitação proxy\" no formulário de leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_afe6d717dc37299cc5dd3029ea35fb38'] = 'Mostrar\" Licitação em pipocas\"'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_7ca23831e76dbebec4b836be48f9deb5'] = 'Permitir a definição de \"Licitação em pipocas\" nas opções do formulários de leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_dae8ace18bdcbcc6ae5aece263e14fe8'] = 'Opções'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_d69f436f31791c560855363d12707e20'] = 'Recomeçar o leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_31e7ab8433e142d4af16f3a2b797963c'] = 'Permitir a característica de reiniciar leilões a qualquer momento'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_ab040bf9fbd1d141c5cc7528a460915d'] = 'Finalizar o leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_2f77f3dcd1bad06fe653361b2e2dee6e'] = 'Permitir a característica de terminar leilões a qualquer momento'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_c3dd8ecd089fde5975736160fef48fbd'] = 'Aceitar o leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_faa4d76c6cfe413728b9bc3e8bbfa578'] = 'Permitir a aceitação do vencedor mesmo que o preço mínimo de reserva não tenha sido atingido'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_f9a7949d581da9722f25f740c99388e2'] = 'Relembrar o leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_888206e117eb507bd82c9c2e1de95362'] = 'Permitir o envio de notificações para relembrar o vencedor que não fez o check out do produto'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_a164c87aab3d8460ce09cc4fa973cff5'] = 'Vigiar o leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_6b72fc884fe8d8a47617415765f16eaa'] = 'Permitir a característica de subscrever-se ao leilão'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_27b948ac5b24cd345b14faa60c455f67'] = 'Adicional'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_5d0bea05b63f7472176cb2e883ea7ee6'] = 'Mostrar bloco de dicas'; $_MODULE['<{auctions}prestashop>auctionsfeaturessettings_4bf0490a6a3852c4285831cd5f39477a'] = 'Permintir a descrição azul dos blocos nos formulários de backoffice'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_c8896d70102b6711dc07718df1996885'] = 'Correio'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_daa5ea5586a1043f9db2158628cd0410'] = 'Correio de clientes'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_766e0f1cff9aa299228cd5f79f2b7c14'] = 'Uma nova oferta foi colocada'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_2c93e7383e48779cfeeecfecec54361e'] = 'Tarefa de cron'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_54828f327f31abd59f2f459c0247756d'] = 'Instante'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_b9f5c797ebbf55adccdd8539a65a0241'] = 'Desativado'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_531522d7c8882e0112319dfb5cecc4ac'] = 'O email foi enviado aos licitadores (excepto a pessoa que ganhou e a pessoa que foi ultrapassado)'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_343e6b80ed22abe92cdf6d30c8991536'] = 'A melhor oferta foi colocada'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_e8af018658b67a3b4d10f4b6c271f6f8'] = 'O email é enviado apenas para a pessoa que colocou o maior preço (se estiver desativado, um email de nova oferta é enviado.'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_9081970fa716042a63fd0ae6d7a97874'] = 'A oferta foi ultrapassada'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_f801515b63e16adb3e0c838d3c8f1c09'] = 'Um email é enviado apenas à pessoa que foi ultrapassada (se desativada, um email de nova oferta é enviado)'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_3665b18fa0daf8d132e497c0cc9d5b46'] = 'O leilão terminou'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_b723201d9c313ac678a37718cad2ccd1'] = 'Um email é enviado aos participantes no leilão'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_e79e043dea42bb8101404a5b2f74d286'] = 'Cliente venceu o leilão'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_3f36799f0b53c86bd09829371ae09b08'] = 'Um email é enviado ao vencedor (se desativado, um email de fim do leilão é enviado).'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_94b916fb8610ecb40e48c273fc2313f3'] = 'Cliente não ganhou o leilão'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_b096d7f593281c7be283b852d13b3967'] = 'Um email é enviado a todos os participantes no leilão excepto o vencedor (se desativado, um email de fim de leilão é enviado)'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_357a763f208f55b5c49bd35626df8429'] = 'O leilão foi reiniciado'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_e7865deaa7d87fc419da759ba663529b'] = 'Os participantes recebem notificações quando um leilão é reiniciado'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_0c8f2f9b89c9bedc0541e53c880fe417'] = 'O vencedor foi aceite'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_05561a4a58aa3a8c98ed4a6a68b8ae3d'] = 'Um email é enviado para a pessoa que apesar do preço de reserva não ter sido atingido é aceitada como vencedora, podendo comprar.'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_7831075bbce4eec21e2c3ebd29573cb9'] = 'O vencedor foi relembrado'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_1a1992cc9d7e755be45e3d73d0d08664'] = 'Um email é enviado à pessoa que apesar de ter vencido o leilão não fez o checkout'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_43d5d556744f259cb3ab6aa30ca91361'] = 'Subscritor de mailing'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_c8128ce274bfcccff782e07df93ad56b'] = 'Subscritores recebem notificações quando uma nova oferta é feita'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_c56d4f831fabd5dff14b977b629294b1'] = 'Subscritores recebem notificações quando um leilão acabou'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_a0da4a9337dfb3231df49730b22862c9'] = 'Subscritores recebem notificações quando um leilão recomeçou'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_5de46aea66786d714c15390c166dc190'] = 'Administrador de mailing'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_459dcbf7276a9d4380ddde25a5b9c757'] = 'Administradores recebem notificações quando uma oferta é feita'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_68256094609fd599a2500e5085728116'] = 'Administradores recebem notificações quando um leilão terminou'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_c58cbba011e545f3a14ad7b21ac958ce'] = 'Enviar a estes administradores'; $_MODULE['<{auctions}prestashop>auctionsmailingsettings_2869b4ab4fb70256d68da70d1fff3a35'] = 'Enviar um mailing ao administrador para os administradores seleccionados'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_1812d6e173f72df75972c1dd49ca0992'] = 'Seleccionar o modelo para o leilão corrente'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_7984e84e2398bcf338147f623d4cae51'] = 'Ativar leilão'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_93cba07454f06a4a960172bbd6e2a435'] = 'Sim'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_bafd7322c6e97d25b6299b5d6fe8920b'] = 'Não '; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_3e765928acecf65f5ba979913ee8dab3'] = 'Mudar para ativar leilão no produto corrente'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_9d4dbe6bfa8415975911ba5b0a0e0945'] = 'Começa a:'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_0273f367d29fef9fcca08ba93dbe61bd'] = 'Data quando o leilão começa'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_e839d98ae568edc3cd419f7c250aa319'] = 'Acaba em:'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_f81a5a6ef01c7cc1a55b01f41da750af'] = 'Data quando o leilão termina'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_cc7a1e792bca8ccb1946b7a07f6dbc03'] = '1d'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_c309f0daf5910cf7ac2038ce9520448a'] = '2d'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_1ade4e4b25d0e4d4ada27a3231c31f06'] = '5d'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_9b61b18c46b6449e9967b7672569b07f'] = '7d'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_97d7e117f62a5a28540fe51c4e233f61'] = '10d'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_9f090cd0e4880a062d9ffff7de48b604'] = '14d'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_3ed06919ecdcec94dee6ff18ffa21d60'] = '30d'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_ec068e2996d469a480d7b7cfab52034b'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_b590bcf2d58a204bb860080dca6a73e8'] = 'Preço inicial a que o leilão começará'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_b5a6f6d044c4d98cafe31d080b3917e9'] = 'Preço de reserva:'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_5f888b0a132fb1bee481e1c9135bd612'] = 'Minimo preço a que estás disposto a vender o produto'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_5f93eefbbb2e79c57779494a4afdf189'] = 'Preço Comprar Agora:'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_f8b8f5a2af536b6e666f6d4645bf1d29'] = 'Preço comprar agora é aquele que estás pronto a vender sem leilão'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_55c35fbc02011d64ad04bf3cd014bdbc'] = 'Compre agora antes da primeira licitação'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_d2e3fecf1d9323b2c7203c18804e746e'] = 'Defina se quer a opção \"Comprar agora\" ainda disponível a seguir à primeira licitação feita'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_328015aff573270c6a4d650ae0b51161'] = 'Intervalo de licitação'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_e43ce71d73dca6b95bedd52bdb1f98d8'] = 'Defina intervalos de prelos e , estando dentro deles, estabeleça os incrementos de licitação considerados válidos'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_4f8844ac10890919c9c3d6112e0d70e7'] = 'Ativar a licitação proxy'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_c5f25b130c5785eec6f2ef963d4f943f'] = 'Permitir licitação automática no leilão corrente'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_aa5f283d25b11eafa06f9455355636f7'] = 'Extender o prazo de licitação durante :'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_48694b006a3d11b95ef8a137c7b4b07f'] = 'Extender o prazo de licitação quando a licitação é feita dentro de um determinado montante de segundos antes que o leilão acabe.'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_783e8e29e6a8c3e22baa58a19420eb4f'] = 'segundos'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_911a2a27f6422f2d7ed7f6d531b69218'] = 'Extender o prazo de licitação por:'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_d0d0e25694c9729d0187d4e06a8ad884'] = 'Extender o prazo limite para licitar concedento alguns segundos'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_278c491bdd8a53618c149c4ac790da34'] = 'Modelo (template)'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_caba6d8dbf070fe4ca83977167d2c102'] = 'Se você alterar o modelo, todos os valores não salvos serão perdidos e substituídos com valores padrão definidos no modelo selecionado.'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_f4f70727dc34561dfde1a3c529b6205c'] = 'Definições'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_5f0ca3e8b37b653d3bb4b9898d7d6317'] = 'Datas'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_e16dd6e118732c5d1586d6aba0b62f3a'] = 'Preços'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_a0201917e36870ce31a7bfec01b7bf7f'] = 'Todos os preços devem ser antes de impostos. Imposto será calculado automaticamente com base no imposto definido nas configurações de preços e da loja'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_10204c18b9fed4140430785a27d9b6c4'] = 'Regras de incremento de licitação'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_075daf1730d17f56dae9b2b3ce69221a'] = 'Defina o valor mínimo pelo qual a oferta será gerada. Você pode criar um número de intervalos de licitação (regras de incremento).'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_0490fcb99e76584b3a5484cd72291178'] = 'Licitação Proxy'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_550884725eacafa2e65c00005afdde76'] = 'Licitações proxy permite que o cliente coloque o montante máximo que está disposto a pagar para o item. Esse preço não é visível para outros usuários e oferta do cliente é gerada automaticamente quando alguém coloca maior oferta, até que seja atingido o valor máximo definido pelo cliente. O cliente pode obter o produto por menos do que sua oferta real.'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_d672daf213e0f9304b6b9825fc23f19b'] = 'Licitação pipoca'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_e77ffd3a839de53486e0bd23a2317abc'] = 'A licitação pipoca dá a todos os licitantes chances iguais de ganhar um leilão, estendendo a hora final do leilão, se for colocada uma oferta de última hora. É usado para simular um leilão ao vivo e impede que outros concorrentes \"snipers\" um leilão no último segundo sem dar a todos os interessados a chance de ganhar.'; $_MODULE['<{auctions}prestashop>productauctioncreateenglish_c9cc8cce247e49bae79f15173ce97354'] = 'Gravar'; $_MODULE['<{auctions}prestashop>productauctionvalidatorenglish_7b7560b3b183bfa1722553f6a442dc51'] = 'O leilão ainda não começou!'; $_MODULE['<{auctions}prestashop>productauctionvalidatorenglish_9ed8db6767477ce5247bb726ea726ae0'] = 'O leilão já acobou!'; $_MODULE['<{auctions}prestashop>productauctionvalidatorenglish_6ed84ac6ceae83cdf2fcbadaecf934e7'] = 'Por favor introduza um valor válido'; $_MODULE['<{auctions}prestashop>productauctionvalidatorenglish_119616f3cd7a6792e06d85d42331422c'] = 'O preço licitado é demasiado baixo'; $_MODULE['<{auctions}prestashop>adminauctionsarchivedcontroller_b718adec73e04ce3ec720dd11a06a308'] = 'ID'; $_MODULE['<{auctions}prestashop>adminauctionsarchivedcontroller_49ee3087348e8d44e1feda1917443987'] = 'Nome'; $_MODULE['<{auctions}prestashop>adminauctionsarchivedcontroller_3ad87dfe0bb7c480033b20e5261e499c'] = 'Começa a '; $_MODULE['<{auctions}prestashop>adminauctionsarchivedcontroller_b922e4b5d391a9427b85a4608b8b2506'] = 'Acaba a '; $_MODULE['<{auctions}prestashop>adminauctionsarchivedcontroller_9461bed8b71377318436990e57106729'] = 'Ofertas'; $_MODULE['<{auctions}prestashop>adminauctionsarchivedcontroller_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>adminauctionsarchivedcontroller_ed26f5ba7a0f0f6ca8b16c3886eb68ad'] = 'Preço final'; $_MODULE['<{auctions}prestashop>adminauctionsarchivedcontroller_85144ab5880edc8513c39cfeb1bd5a5e'] = 'Vencedor'; $_MODULE['<{auctions}prestashop>adminauctionsarchivedcontroller_630f6dc397fe74e52d5189e2c80f282b'] = 'Voltar à lista'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_1f1230b97639cd1593587be352604814'] = 'Tem a certeza que quer apagar permanentemente o leilão seleccionado?'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_d3b206d196cd6be3a2764c1fb90b200f'] = 'Apagar seleccionados'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_613a34750554b7dce16d2949cd3fc940'] = 'Tem a certeza que quer apagar os items seleccionados?'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_b718adec73e04ce3ec720dd11a06a308'] = 'ID'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_00d23a76e43b46dae9ec7aa9dcbebb32'] = 'Ativado'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_c54d89ebff53a223c8c6257cac924cf9'] = 'Loja por defeito'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_3adbdb3ac060038aa0e6e6c138ef9873'] = 'Categoria'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_c03d53b70feba4ea842510abecd6c45e'] = 'Foto'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_49ee3087348e8d44e1feda1917443987'] = 'Nome'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_db3794c7d704611ce61c9d8cc09cd806'] = 'Data inícial'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_fc6083fc2d037ce4acf71257cc9a2e4f'] = 'Data final'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_e02d2ae03de9d493df2b6b2d2813d302'] = 'Duração'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_e097ef46f9822ad0cf6f9bcabf87e174'] = 'Tempo que falta'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_ad4462475964d47e6b172faf9096836d'] = 'Preço de reserva atingido'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_fb025c599976fb9e3bec007d38ed9e4e'] = 'Preço atual'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_5a7d87de341dba85983b6b94b751df76'] = 'Licitações'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_5668e16d85b190bc09062d1e23f0dbab'] = 'Licitação vencedora'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_ec53a8c4f07baed5d8825072c89799be'] = 'Estado'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_ef61fb324d729c341ea8ab9901e23566'] = 'Adicionar novo'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_72d6d7a1885885bb55a565fd1070581a'] = 'Importar'; $_MODULE['<{auctions}prestashop>adminauctionscontroller_f1c9d977cc8d6b86d65a9848e1517ca8'] = 'Leilões arquivados'; $_MODULE['<{auctions}prestashop>adminauctionssettingscontroller_b718adec73e04ce3ec720dd11a06a308'] = 'ID'; $_MODULE['<{auctions}prestashop>adminauctionssettingscontroller_49ee3087348e8d44e1feda1917443987'] = 'Nome'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_d3b206d196cd6be3a2764c1fb90b200f'] = 'Apagar seleccionados'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_613a34750554b7dce16d2949cd3fc940'] = 'Tem a certeza que quer eliminar pernamentemente estes items?'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_d37c2bf1bd3143847fca087b354f920e'] = 'ID do Cliente'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_b78a3223503896721cca1303f776159b'] = 'Titulo'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_8d3f5eff9c40ee315d452392bed5309b'] = 'Último nome'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_bc910f8bdf70f29374f496f05be0330c'] = 'Primeiro nome'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_b357b524e740bc85b9790a0712d84a30'] = 'Endereço de email'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_9d8d2d5ab12b515182a505f54db7f538'] = 'Idade'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_00d23a76e43b46dae9ec7aa9dcbebb32'] = 'Ativado'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_44749712dbec183e983dcd78a7736c41'] = 'Data'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_2eee5dbccd81393d35aa1007951aaa78'] = 'Voltar aos detalhes'; $_MODULE['<{auctions}prestashop>adminauctionssubscriptionscontroller_a333339eb21abf3d5a04f5ede8f73ae9'] = '%s de eliminação'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_b718adec73e04ce3ec720dd11a06a308'] = 'ID'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_7a1920d61156abc05a60135aefe8bc67'] = 'Defeito'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_49ee3087348e8d44e1feda1917443987'] = 'Nome'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_f87872326eba967bb0488cfd70956c62'] = 'Preço de reserva'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_50120cbe63d4f163f6eb8be895ff9d2e'] = 'Preço comprar agora'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_80498ad991a786c73928dad359fb04f0'] = 'Comprar agora depois da licitação'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_db3794c7d704611ce61c9d8cc09cd806'] = 'Data início'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_fc6083fc2d037ce4acf71257cc9a2e4f'] = 'Data final'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_e02d2ae03de9d493df2b6b2d2813d302'] = 'Duração'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_0490fcb99e76584b3a5484cd72291178'] = 'Licitação Proxy'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_2f760a17ace84eeba24650bb71041f4d'] = 'Duranção da prologação'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_7004d8344329f120a8d264b7f3d5ee5d'] = 'Prolongado por'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_69c06afb596f02fc7b3f7dd7f0248bb5'] = 'Modelo ativo'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_0eceeb45861f9585dd7a97a3e36f85c6'] = 'Criado'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_35e0c8c0b180c95d4e122e55ed62cc64'] = 'Modificado'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_ef61fb324d729c341ea8ab9901e23566'] = 'Adicionar novo'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_f4f70727dc34561dfde1a3c529b6205c'] = 'Definições'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_4e140ba723a03baa6948340bf90e2ef6'] = 'Nome:'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_9527f108e93386b51e434530c58659e9'] = 'O nome do modelo'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_681f8b0cd9e03bd02833cf8c36cfbb97'] = 'Modelo por defeito'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_93cba07454f06a4a960172bbd6e2a435'] = 'Sim'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_bafd7322c6e97d25b6299b5d6fe8920b'] = 'Nao'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_8b7323fe4ae696420824078458ec709c'] = 'Assinale a caixa para definir este modelo como \"por defeito\"'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_5f0ca3e8b37b653d3bb4b9898d7d6317'] = 'Datas'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_9d4dbe6bfa8415975911ba5b0a0e0945'] = 'Começa em:'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_0273f367d29fef9fcca08ba93dbe61bd'] = 'Data quando o leilão começa'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_e839d98ae568edc3cd419f7c250aa319'] = 'Termina em:'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_f81a5a6ef01c7cc1a55b01f41da750af'] = 'Data quando o leilão acaba'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_cc7a1e792bca8ccb1946b7a07f6dbc03'] = '1d'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_c309f0daf5910cf7ac2038ce9520448a'] = '2d'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_1ade4e4b25d0e4d4ada27a3231c31f06'] = '5d'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_9b61b18c46b6449e9967b7672569b07f'] = '7d'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_97d7e117f62a5a28540fe51c4e233f61'] = '10d'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_9f090cd0e4880a062d9ffff7de48b604'] = '14d'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_3ed06919ecdcec94dee6ff18ffa21d60'] = '30d'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_9b8e4d1df12a77ef1b1f98a9b4d07178'] = 'Começa dentro de:'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_a61af2120e82dc335eeefd3d496bd4a1'] = 'Tempo que falta para começar o leilão'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_783e8e29e6a8c3e22baa58a19420eb4f'] = 'segndos'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_e72046dd81cc4656bb368992cf625d05'] = 'Final do tempo de pronlongamento'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_7563bca26159bb13e4d3504e34e2dceb'] = 'Prolongamento quando o leilão acaba'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_e16dd6e118732c5d1586d6aba0b62f3a'] = 'Preços'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_a0201917e36870ce31a7bfec01b7bf7f'] = 'Todos os preços deverão ser antes de impostos. A taxa será calculada automáticamente baseada na taxa definida em \"prços\" e definições'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_ec068e2996d469a480d7b7cfab52034b'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_b590bcf2d58a204bb860080dca6a73e8'] = 'Preço inicial em que cada leilão começará'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_b5a6f6d044c4d98cafe31d080b3917e9'] = 'Preço de reserva'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_5f888b0a132fb1bee481e1c9135bd612'] = 'O preço de reserva é o preço mínimo em que está disponível a vender o produto'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_5f93eefbbb2e79c57779494a4afdf189'] = 'Preço comprar agora'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_f8b8f5a2af536b6e666f6d4645bf1d29'] = 'O preço \"compraragora\" é aquele em que estás pronto a vender o produto sem ser em leilão'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_55c35fbc02011d64ad04bf3cd014bdbc'] = 'Comprar agora depois da primeira licitação'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_d2e3fecf1d9323b2c7203c18804e746e'] = 'Defina se quer que a opção \"Comprar agora\" se manteha disponível depois da primeira licitação ser colocada'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_10204c18b9fed4140430785a27d9b6c4'] = 'Regras de incremento das licitações'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_075daf1730d17f56dae9b2b3ce69221a'] = 'Defina um valor mínimo em que cada licitação será incrementada. Pode criar intervalos de licitação com regras de incremento diferentes'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_328015aff573270c6a4d650ae0b51161'] = 'Intervalo de licitação:'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_61cb9b18ed8e3fe5d513110b1dcd9857'] = 'Define intervalos de preços em que, sendo respeitados, as regras de incremento farão com que sejam consideradas licitações váidades. Se \"Até ao preço\" for 0.00 todo o intervalo será abrangido pela regra de incremento.'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_550884725eacafa2e65c00005afdde76'] = 'Licitações proxy permite que o cliente coloque o montante máximo que está disposto a pagar para o item. Esse preço não é visível para outros usuários e oferta do cliente é gerada automaticamente quando alguém coloca maior oferta, até que seja atingido o valor máximo definido pelo cliente. O cliente pode obter o produto por menos do que sua oferta real.'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_4f8844ac10890919c9c3d6112e0d70e7'] = 'Ativar a licittação proxy'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_c5f25b130c5785eec6f2ef963d4f943f'] = 'Permitir a licitação automática no leilão atual'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_d672daf213e0f9304b6b9825fc23f19b'] = 'Licitação em pipoca'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_e77ffd3a839de53486e0bd23a2317abc'] = 'A licitação em pipoca dá a todos os licitadores a chance de ganhar um leilão extendendo o tempo limite do leilão se no último minuto for colocada uma licitação. É usado para simular um leilão ao vivo para prevenir que outros licitadores estejam atentos apenas para licitar no último segundo não dando a hipótese a outros interessados de vencer o leilão'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_aa5f283d25b11eafa06f9455355636f7'] = 'Extender o prazo limite de licitação em:'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_48694b006a3d11b95ef8a137c7b4b07f'] = 'Extender o prazo limite de licitação quando uma oferta é feita num determinado número de segundos antes do leilão terminar.'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_911a2a27f6422f2d7ed7f6d531b69218'] = 'Extender o limite do prazo de licitação em:'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_d0d0e25694c9729d0187d4e06a8ad884'] = 'Extender o limite do prazo de licitação dando um determinado número de segundos adicionais'; $_MODULE['<{auctions}prestashop>adminauctionstemplatescontroller_c9cc8cce247e49bae79f15173ce97354'] = 'Gravar'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_b718adec73e04ce3ec720dd11a06a308'] = 'ID'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_b8e97dd2df718b18ba0111008a745c57'] = 'Nome do cliente'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_03361eda68f746619c2ae3341eaa2f07'] = 'Email do cliente'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_e55b586356b9b7ed345a2c0ea06be4ae'] = 'Máxima oferta do cliente'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_51aa40e214d39cada27aec2074df80d9'] = 'Preço anterior'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_1211e96d5221508e4e2100b99fee6048'] = 'Data oferta'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_f6abe02e3204cd69b751bf2d6783589d'] = 'Estado da licitação'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_d69f436f31791c560855363d12707e20'] = 'Recomeção o leilão'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_c09b3b48f5d601ae2153892e7213d1a4'] = 'Tem a certeza que quer recomeçar o leilão? Todas as licitações serão removidos e o leilão começará novamente. Poderá necessitar de ajustar as datas de começo e de fim do leilão.'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_ab040bf9fbd1d141c5cc7528a460915d'] = 'Finalizar o leilão'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_62f4e6f857c9fa8b965a01c90b54cab4'] = 'Tem a certeza que quer finalizar o leilão e fazer que a mais alta licitação seja a vencedora?'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_d642e59e9d333ac4afb99e71b1e4cc05'] = 'Aceitar o vencedor'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_2590de97603216454614bf0f3ccd070e'] = 'Tem a certeza que quer aceitar a oferta mais alta como a vencedora?'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_1df6e9f0774d7550c68e5db1af3a6782'] = 'Relembrar o vencedor'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_c2d2730b00d3313ec59b1c7ee126c2a9'] = 'Vigilantes'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_31fde7b05ac8952dacf4af8a704074ec'] = 'Pré-visualizar'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_7dce122004969d56ae2e0245cb754d35'] = 'Editar'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_f2a6c498fb90ee345d997f888fce3b18'] = 'Apagar'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_1f1230b97639cd1593587be352604814'] = 'Tem a certeza que quer eliminar todos os leilões seleccionados?'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_630f6dc397fe74e52d5189e2c80f282b'] = 'Voltar à lista'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_b5cca090e495c29153e14b6d874e0432'] = 'Marcar como inválido'; $_MODULE['<{auctions}prestashop>adminauctionsviewcontroller_1e964a1bc4514dfdb4b150985fcf2fcf'] = 'Marcar como válido'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_b718adec73e04ce3ec720dd11a06a308'] = 'ID'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_c03d53b70feba4ea842510abecd6c45e'] = 'Fotografia'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_df644ae155e79abf54175bd15d75f363'] = 'Nome do produto'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_4df07df1d45054591139d3918e390188'] = 'Nome do vencedor'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_f0b4199fc5d39d7da5d03bd0b14ade8f'] = 'Email do vencedor'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_9b32154a8f7ae73f56f07fa48792d22a'] = 'Licitação final'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_3641c2067ad878a90eddd3276ccef19c'] = 'Data de licitação'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_59758c8f7f9cbef6939ca9991aaa8939'] = 'Estado de pagamento'; $_MODULE['<{auctions}prestashop>adminauctionswinnerscontroller_630f6dc397fe74e52d5189e2c80f282b'] = 'Voltar à lista'; $_MODULE['<{auctions}prestashop>all_1acef523f61f49c38ef17356cb13786b'] = 'Leilões'; $_MODULE['<{auctions}prestashop>all_5c86408b49b0f1e484c361f1fcc00224'] = 'Sem leilões'; $_MODULE['<{auctions}prestashop>bid_2773a08a91b309fa9b6a4a7ee8dd68fc'] = 'Tem que fazer o login para fazer uma oferta'; $_MODULE['<{auctions}prestashop>bid_81fced3dc83c53f41fcdd828a1efde04'] = 'O leilão não pode ser encontrado'; $_MODULE['<{auctions}prestashop>bid_e35c593445625735f75bb906b17ca22d'] = 'Não pode colocar uma oferta!'; $_MODULE['<{auctions}prestashop>ending_b7c0efb135647306d6f789c4afb6f121'] = 'Leilões terminando'; $_MODULE['<{auctions}prestashop>ending_997435af1b7b7b5394eff45708940f56'] = 'Não há leilões a terminar'; $_MODULE['<{auctions}prestashop>featured_e60d143810b5e7455d8f6527478148a9'] = 'Leilões em destaque'; $_MODULE['<{auctions}prestashop>featured_141c0e638735dbf644bfe6bfdb68a548'] = 'Não há leilões em destaque'; $_MODULE['<{auctions}prestashop>latest_e33bee3315cfcba4bf9c73798892998d'] = 'Últimos leilões'; $_MODULE['<{auctions}prestashop>latest_5854cb486f2e7aa491cf9737a1606f20'] = 'Não há últimos leilões'; $_MODULE['<{auctions}prestashop>popular_8ac34ce12ca7e5139197675652b2b167'] = 'Leilões populares'; $_MODULE['<{auctions}prestashop>popular_b3494031c139cfd6f2561735c733e22d'] = 'Não há leilões populares'; $_MODULE['<{auctions}prestashop>view_7d69b3cb4cada18ae61811304f8fbcb5'] = 'Arquivivado'; $_MODULE['<{auctions}prestashop>view_9662d6bc35df3b4e8ea3ab0b1e753a50'] = 'Arquivado em '; $_MODULE['<{auctions}prestashop>view_3ec365dd533ddb7ef3d1c111186ce872'] = 'Detalhes'; $_MODULE['<{auctions}prestashop>view_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>view_f87872326eba967bb0488cfd70956c62'] = 'Preço de reserva'; $_MODULE['<{auctions}prestashop>view_50120cbe63d4f163f6eb8be895ff9d2e'] = 'Preço para comprar agora'; $_MODULE['<{auctions}prestashop>view_3ad87dfe0bb7c480033b20e5261e499c'] = 'Começa em:'; $_MODULE['<{auctions}prestashop>view_b922e4b5d391a9427b85a4608b8b2506'] = 'Termina em:'; $_MODULE['<{auctions}prestashop>view_e02d2ae03de9d493df2b6b2d2813d302'] = 'Duração'; $_MODULE['<{auctions}prestashop>view_c7a12d267a249d8c37240213e89af737'] = 'Sumário de ofertas:'; $_MODULE['<{auctions}prestashop>view_ec53a8c4f07baed5d8825072c89799be'] = 'Estado'; $_MODULE['<{auctions}prestashop>view_ed26f5ba7a0f0f6ca8b16c3886eb68ad'] = 'Preço final'; $_MODULE['<{auctions}prestashop>view_228cfc5fe796c9b7bab6ce2781af7837'] = 'Preço de reserva atingido'; $_MODULE['<{auctions}prestashop>view_60245576c684a91e0e59cb1e3a3c0a66'] = 'Preço de reserva não atingido'; $_MODULE['<{auctions}prestashop>view_4df07df1d45054591139d3918e390188'] = 'Nome vencedor'; $_MODULE['<{auctions}prestashop>view_f0b4199fc5d39d7da5d03bd0b14ade8f'] = 'Email do vencedor'; $_MODULE['<{auctions}prestashop>view_9461bed8b71377318436990e57106729'] = 'Ofertas'; $_MODULE['<{auctions}prestashop>list_header_3ec365dd533ddb7ef3d1c111186ce872'] = 'Detalhes'; $_MODULE['<{auctions}prestashop>list_header_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>list_header_f87872326eba967bb0488cfd70956c62'] = 'Preço de reserva '; $_MODULE['<{auctions}prestashop>list_header_50120cbe63d4f163f6eb8be895ff9d2e'] = 'Preço de comprar agora'; $_MODULE['<{auctions}prestashop>list_header_3ad87dfe0bb7c480033b20e5261e499c'] = 'Começa em'; $_MODULE['<{auctions}prestashop>list_header_b922e4b5d391a9427b85a4608b8b2506'] = 'Termina em'; $_MODULE['<{auctions}prestashop>list_header_e02d2ae03de9d493df2b6b2d2813d302'] = 'Duração'; $_MODULE['<{auctions}prestashop>list_header_290612199861c31d1036b185b4e69b75'] = 'Sumário'; $_MODULE['<{auctions}prestashop>list_header_ec53a8c4f07baed5d8825072c89799be'] = 'Estado'; $_MODULE['<{auctions}prestashop>list_header_72537e0a811807462310d2cfa98292ad'] = 'Tempo para começar'; $_MODULE['<{auctions}prestashop>list_header_2530e001571cd06cf7ed5db531b07544'] = 'Tempo que falta'; $_MODULE['<{auctions}prestashop>list_header_8f3d10eb21bd36347c258679eba9e92b'] = 'Terminado'; $_MODULE['<{auctions}prestashop>list_header_fb025c599976fb9e3bec007d38ed9e4e'] = 'Preço corrente'; $_MODULE['<{auctions}prestashop>list_header_228cfc5fe796c9b7bab6ce2781af7837'] = 'Preço de reserva atingido'; $_MODULE['<{auctions}prestashop>list_header_60245576c684a91e0e59cb1e3a3c0a66'] = 'Preço de reserva não atingido'; $_MODULE['<{auctions}prestashop>list_header_85144ab5880edc8513c39cfeb1bd5a5e'] = 'Vencedor'; $_MODULE['<{auctions}prestashop>list_header_9461bed8b71377318436990e57106729'] = 'Ofertas'; $_MODULE['<{auctions}prestashop>base-form_2efd89b3ccc76b0b03a34196fc6d1c8b'] = 'Adicionar separador'; $_MODULE['<{auctions}prestashop>base-form_93cba07454f06a4a960172bbd6e2a435'] = 'Sim'; $_MODULE['<{auctions}prestashop>base-form_bafd7322c6e97d25b6299b5d6fe8920b'] = 'Não'; $_MODULE['<{auctions}prestashop>base-form_26ce1315d2bff025e8fb8a0c6259e58c'] = 'Alterar password'; $_MODULE['<{auctions}prestashop>base-form_d9c2d86a66aa5a45326c3757f3a272cc'] = 'Password atual'; $_MODULE['<{auctions}prestashop>base-form_3544848f820b9d94a3f3871a382cf138'] = 'Nova password'; $_MODULE['<{auctions}prestashop>base-form_4c231e0da3eaaa6a9752174f7f9cfb31'] = 'Confirmar password'; $_MODULE['<{auctions}prestashop>base-form_2871afea416378d2772937c4d67d6c2c'] = 'Gerar password'; $_MODULE['<{auctions}prestashop>base-form_ed400dc4c641d6e5672616ac56a669ec'] = 'Mandar-me esta nova password por email'; $_MODULE['<{auctions}prestashop>base-form_ea4788705e6873b424c65e91c2846b19'] = 'Cancelar'; $_MODULE['<{auctions}prestashop>base-form_4bbb8f967da6d1a610596d7257179c2b'] = 'Invalido'; $_MODULE['<{auctions}prestashop>base-form_26b63f278101527e06a5547719568bb5'] = 'Ok'; $_MODULE['<{auctions}prestashop>base-form_0c6ad70beb3a7e76c3fc7adab7c46acc'] = 'Bom'; $_MODULE['<{auctions}prestashop>base-form_b8dc7c80939667637db7ac31ece215b9'] = 'Fabuloso'; $_MODULE['<{auctions}prestashop>base-form_01e8202cf69f19ea7cf3a80f7673066a'] = 'Confirmação de password inválida'; $_MODULE['<{auctions}prestashop>base-form_86f5978d9b80124f509bdb71786e929e'] = 'Janeiro'; $_MODULE['<{auctions}prestashop>base-form_659e59f062c75f81259d22786d6c44aa'] = 'fevereiro'; $_MODULE['<{auctions}prestashop>base-form_fa3e5edac607a88d8fd7ecb9d6d67424'] = 'março'; $_MODULE['<{auctions}prestashop>base-form_3fcf026bbfffb63fb24b8de9d0446949'] = 'abril'; $_MODULE['<{auctions}prestashop>base-form_195fbb57ffe7449796d23466085ce6d8'] = 'maio'; $_MODULE['<{auctions}prestashop>base-form_688937ccaf2a2b0c45a1c9bbba09698d'] = 'junho'; $_MODULE['<{auctions}prestashop>base-form_1b539f6f34e8503c97f6d3421346b63c'] = 'julho'; $_MODULE['<{auctions}prestashop>base-form_41ba70891fb6f39327d8ccb9b1dafb84'] = 'agosto'; $_MODULE['<{auctions}prestashop>base-form_cc5d90569e1c8313c2b1c2aab1401174'] = 'setembro'; $_MODULE['<{auctions}prestashop>base-form_eca60ae8611369fe28a02e2ab8c5d12e'] = 'outubro'; $_MODULE['<{auctions}prestashop>base-form_7e823b37564da492ca1629b4732289a8'] = 'novembro'; $_MODULE['<{auctions}prestashop>base-form_82331503174acbae012b2004f6431fa5'] = 'dezembro'; $_MODULE['<{auctions}prestashop>product-auction-fields_04b1214f9d88b525cf1183551e50040e'] = 'Do preço'; $_MODULE['<{auctions}prestashop>product-auction-fields_3a5bc844a7f48cbab68bd7945df80d16'] = 'Ao preço'; $_MODULE['<{auctions}prestashop>product-auction-fields_c90c6f2ddbfc6b9d503f42810ec6c141'] = 'Incremento da licitação'; $_MODULE['<{auctions}prestashop>product-auction-fields_004bf6c9a40003140292e97330236c53'] = 'Acção'; $_MODULE['<{auctions}prestashop>product-auction-fields_291e42d1980715d16a496042133baa2b'] = 'Apagar este intervalo'; $_MODULE['<{auctions}prestashop>product-auction-fields_e5c1b89d1aa1fab063d9de51e2d555e7'] = 'Adicionar uma nova regra'; $_MODULE['<{auctions}prestashop>product-auction-scripts_1e1cc9bdeb2f29f5480106aec7e9bc48'] = 'Agora'; $_MODULE['<{auctions}prestashop>product-auction-scripts_f92965e2c8a7afb3c1b9a5c09a263636'] = 'Feito'; $_MODULE['<{auctions}prestashop>product-auction-scripts_3964fd83339fec5014c831822005653a'] = 'Escolha o tempo'; $_MODULE['<{auctions}prestashop>product-auction-scripts_a76d4ef5f3f6a672bbfab2865563e530'] = 'Tempo'; $_MODULE['<{auctions}prestashop>product-auction-scripts_b55e509c697e4cca0e1d160a7806698f'] = 'Hora'; $_MODULE['<{auctions}prestashop>product-auction-scripts_62902641c38f3a4a8eb3212454360e24'] = 'Minuto'; $_MODULE['<{auctions}prestashop>product-auction-scripts_8f19a8c7566af54ea8981029730e5465'] = 'Segundos'; $_MODULE['<{auctions}prestashop>product-auction-bid-errors_9f4a189c659e98db07eb762d8ad111ac'] = 'Sumário das ofertas'; $_MODULE['<{auctions}prestashop>product-auction-bid-errors_532893f7fcd70c590c719156ffe74b48'] = 'A sua oferta é inválida'; $_MODULE['<{auctions}prestashop>product-auction-bid-errors_deb10517653c255364175796ace3553f'] = 'Produto'; $_MODULE['<{auctions}prestashop>product-auction-bid-errors_2530e001571cd06cf7ed5db531b07544'] = 'Tempo que falta'; $_MODULE['<{auctions}prestashop>product-auction-bid-errors_664b13315c97047b2ba2a1ac2375e0ce'] = 'Tempo inicial'; $_MODULE['<{auctions}prestashop>product-auction-bid-errors_be874332d03c079ef30ea63aef08a8e4'] = 'Tempo final'; $_MODULE['<{auctions}prestashop>product-auction-bid-errors_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>product-auction-bid-errors_fb025c599976fb9e3bec007d38ed9e4e'] = 'Preço atual'; $_MODULE['<{auctions}prestashop>product-auction-bid-errors_fb5c14c95dd23a277e04bbf6d3a0d977'] = 'Voltar ao leilão'; $_MODULE['<{auctions}prestashop>product-auction-bid-step1_5d2679d629ef3fc23e3cee6ff965a5b1'] = 'A sua oferta'; $_MODULE['<{auctions}prestashop>product-auction-bid-step1_deb10517653c255364175796ace3553f'] = 'Produto'; $_MODULE['<{auctions}prestashop>product-auction-bid-step1_2530e001571cd06cf7ed5db531b07544'] = 'Tempo que falta'; $_MODULE['<{auctions}prestashop>product-auction-bid-step1_664b13315c97047b2ba2a1ac2375e0ce'] = 'Tempo de início'; $_MODULE['<{auctions}prestashop>product-auction-bid-step1_be874332d03c079ef30ea63aef08a8e4'] = 'Tempo de fecho'; $_MODULE['<{auctions}prestashop>product-auction-bid-step1_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>product-auction-bid-step1_f10d4c72337247b18992e99c24badb44'] = 'Oferta mínima'; $_MODULE['<{auctions}prestashop>product-auction-bid-step1_70d9be9b139893aa6c69b5e77e614311'] = 'Confirmar'; $_MODULE['<{auctions}prestashop>product-auction-bid-step1_0557fa923dcee4d0f86b1409f5c2167f'] = 'Voltar'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_9f4a189c659e98db07eb762d8ad111ac'] = 'Sumário de ofertas'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_532893f7fcd70c590c719156ffe74b48'] = 'A sua oferta é inválida'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_f6e70929a77d673f7ca4ac427cea4bc8'] = 'Por favor tente novamente'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_4309331a2db578b8d5db25be6ba450e5'] = 'Alguém colocou uma oferta superior'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_bf9382586cef57d67b0c439046376a85'] = 'Pode continuar a fazer licitações'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_38fb87b00cf984b063b6a7dca2d9e687'] = 'Alguém ofereceu o mesmo preço antes'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_2e781e46cd473612f108b29a62e711ab'] = 'Parabéns'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_56c0fc823dfb82face203a51ffaf04c7'] = 'Você colocou uma oferta'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_267314042b37424788de2a8b39ffc53d'] = 'A sua oferta é a maior agora, mas o preço mínimo ainda não foi atingido'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_861bbe4ac4c497123ead09d2a35936f1'] = 'A sua oferta é a maior agora'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_deb10517653c255364175796ace3553f'] = 'Produto'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_2530e001571cd06cf7ed5db531b07544'] = 'Tempo que falta'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_664b13315c97047b2ba2a1ac2375e0ce'] = 'Tempo inicial'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_be874332d03c079ef30ea63aef08a8e4'] = 'Tempo de fecho'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_fb025c599976fb9e3bec007d38ed9e4e'] = 'Preço atual'; $_MODULE['<{auctions}prestashop>product-auction-bid-step2_fb5c14c95dd23a277e04bbf6d3a0d977'] = 'Voltar ao leilão'; $_MODULE['<{auctions}prestashop>product-auction-my-auctions-info_664b13315c97047b2ba2a1ac2375e0ce'] = 'Tempo inicial'; $_MODULE['<{auctions}prestashop>product-auction-my-auctions-info_be874332d03c079ef30ea63aef08a8e4'] = 'Tempo final'; $_MODULE['<{auctions}prestashop>product-auction-my-auctions-info_5a7d87de341dba85983b6b94b751df76'] = 'Licitações'; $_MODULE['<{auctions}prestashop>product-auction-my-auctions-info_4fc841b21d544a170fc82e6f2fd0ab3b'] = 'Ver todas a licitações'; $_MODULE['<{auctions}prestashop>product-auction-my-auctions-info_e02d2ae03de9d493df2b6b2d2813d302'] = 'Duração'; $_MODULE['<{auctions}prestashop>product-auction-my-auctions-info_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_d95cf4ab2cbf1dfb63f066b50558b07d'] = 'Minha conta'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_90d77b86534fedc93c9c992ae10cade4'] = 'Minhas licitações'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_1516a4ce3cf0f06e5a0fd911eecceced'] = 'Gerir/ver as suas licitações correntes'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_deb10517653c255364175796ace3553f'] = 'Produto'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_85144ab5880edc8513c39cfeb1bd5a5e'] = 'Vencedor'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_4ce8d28822f029527da7b2b83302e841'] = 'Meu preço'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_3601146c4e948c32b6424d2c0a7f0118'] = 'Preço'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_8f7f4c1ce7a4f933663d10543562b096'] = 'Acerca'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_ad4462475964d47e6b172faf9096836d'] = 'Preço de reserva atingido'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_46df75197a1363ae4aae18a504bfcb75'] = 'Preço de reserva não atingido'; $_MODULE['<{auctions}prestashop>product-auction-my-bids_3d4e3acd2c5b425db1b08f00cc2ad2df'] = 'Você não tem qualquer leilão'; $_MODULE['<{auctions}prestashop>product-auction-my-history_d95cf4ab2cbf1dfb63f066b50558b07d'] = 'Minha conta'; $_MODULE['<{auctions}prestashop>product-auction-my-history_2938446b0add768774e595f8b8e2cd6a'] = 'Histórico das minhas licitações'; $_MODULE['<{auctions}prestashop>product-auction-my-history_d52945500cae291eb3afecc99da76e35'] = 'Ver o seu histórico de licitações'; $_MODULE['<{auctions}prestashop>product-auction-my-history_deb10517653c255364175796ace3553f'] = 'Produto'; $_MODULE['<{auctions}prestashop>product-auction-my-history_85144ab5880edc8513c39cfeb1bd5a5e'] = 'Vencedor'; $_MODULE['<{auctions}prestashop>product-auction-my-history_4ce8d28822f029527da7b2b83302e841'] = 'Meu preço'; $_MODULE['<{auctions}prestashop>product-auction-my-history_3601146c4e948c32b6424d2c0a7f0118'] = 'Preço'; $_MODULE['<{auctions}prestashop>product-auction-my-history_8f7f4c1ce7a4f933663d10543562b096'] = 'Acerca'; $_MODULE['<{auctions}prestashop>product-auction-my-history_1d3bb92700ca25028c3edfb675c9f0dd'] = 'Oferta rejeitada'; $_MODULE['<{auctions}prestashop>product-auction-my-history_ad4462475964d47e6b172faf9096836d'] = 'Preço reserva atingido'; $_MODULE['<{auctions}prestashop>product-auction-my-history_46df75197a1363ae4aae18a504bfcb75'] = 'Preço de reserva não atingido'; $_MODULE['<{auctions}prestashop>product-auction-my-history_3d4e3acd2c5b425db1b08f00cc2ad2df'] = 'Você não tem qualquer leilão'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_d95cf4ab2cbf1dfb63f066b50558b07d'] = 'Minha conta'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_2b52a9e614964c3237aaf4917efdeff6'] = 'Os meus items ganhos'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_27ff159b6313407d9e39c1e8a4ddc352'] = 'Gerir/ver os meus items ganhos'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_55968b8e23c01963de14e392a50e13f9'] = 'Checkout seleccionado'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_15675297ac2ee43aed72978c1564dbc1'] = 'Checkout para todos'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_deb10517653c255364175796ace3553f'] = 'Produto'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_710e67129ca5154cb3fe6b8683d5d04b'] = 'Meu preço máximo'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_3601146c4e948c32b6424d2c0a7f0118'] = 'Preço'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_2ea78fadfafeae47ad786c288667eadf'] = 'Estado do pagamento'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_8f7f4c1ce7a4f933663d10543562b096'] = 'Acerca'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_ad4462475964d47e6b172faf9096836d'] = 'Preço reserva atingido'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_46df75197a1363ae4aae18a504bfcb75'] = 'Preço reserva não atingido'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_e0010a0a1a3259ab5c06a19bad532851'] = 'Pago'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_f288862a19714ed90855dacec5bfa9ee'] = 'Não pago'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_643562a9ae7099c8aabfdc93478db117'] = 'Processando'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_b6ec7abeb6ae29cc35a4b47475e12afe'] = 'Processar'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_2d0f6b8300be19cf35e89e66f0677f95'] = 'Adicionar ao carinho'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_377e99e7404b414341a9621f7fb3f906'] = 'Finalizar a comra'; $_MODULE['<{auctions}prestashop>product-auction-my-payment_3d4e3acd2c5b425db1b08f00cc2ad2df'] = 'Você não tem qualquer leilão'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_d95cf4ab2cbf1dfb63f066b50558b07d'] = 'Minha conta'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_3c5cc387eaab8754cbe46eb642ab4209'] = 'Os leilões que estou a seguir'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_439e9ef6436bb4c2b29919e9526bdca1'] = 'Gerir/Ver os leilões que está a seguir'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_f69b87ad617bd3b9187e55bbf0f1e757'] = 'Parar de seguir os seleccionados'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_deb10517653c255364175796ace3553f'] = 'Produto'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_85144ab5880edc8513c39cfeb1bd5a5e'] = 'Vencedor'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_3601146c4e948c32b6424d2c0a7f0118'] = 'Preço'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_8f7f4c1ce7a4f933663d10543562b096'] = 'Acerca'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_cfab1ba8c67c7c838db98d666f02a132'] = '--'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_ad4462475964d47e6b172faf9096836d'] = 'Preço de reserva atingido'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_46df75197a1363ae4aae18a504bfcb75'] = 'Preço de reserva não atingido'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_afe3104f0ffd6d371c8de41a8ae2b470'] = 'Parar de seguir'; $_MODULE['<{auctions}prestashop>product-auction-my-watching_3d4e3acd2c5b425db1b08f00cc2ad2df'] = 'Você não tem nenhum leilão.'; $_MODULE['<{auctions}prestashop>product-auction-sort_df25de42c84837baf5fa15049a8bc764'] = 'Ver:'; $_MODULE['<{auctions}prestashop>product-auction-sort_5174d1309f275ba6f275db3af9eb3e18'] = 'Grelha'; $_MODULE['<{auctions}prestashop>product-auction-sort_4ee29ca12c7d126654bd0e5275de6135'] = 'Lista'; $_MODULE['<{auctions}prestashop>product-auction-sort_33d8042bd735c559cc3206f4bc99aedc'] = 'Ordenado por'; $_MODULE['<{auctions}prestashop>product-auction-sort_cfab1ba8c67c7c838db98d666f02a132'] = '--'; $_MODULE['<{auctions}prestashop>product-auction-sort_fa92f312bf9abca068774decc226390d'] = 'Preço: Mais baixo primeiro'; $_MODULE['<{auctions}prestashop>product-auction-sort_f45727d0a4fb599b8e6fbd133b06a5a7'] = 'Preço: Mais alto primeiro'; $_MODULE['<{auctions}prestashop>product-auction-sort_5820b5a5298779a25d98c41173b931bd'] = 'Nome do produto: A a Z'; $_MODULE['<{auctions}prestashop>product-auction-sort_4f4f552919d5a7ad3435b5fdb7fcae61'] = 'Nome do produto: Z a A'; $_MODULE['<{auctions}prestashop>product-auction-sort_442f3ce6c1fad993aa86f3f4df8c303b'] = 'Data inicio: primeiro'; $_MODULE['<{auctions}prestashop>product-auction-sort_4e88db3a124d418d41c347ca5b124143'] = 'Data inicio: último'; $_MODULE['<{auctions}prestashop>product-auction-sort_97297c6ad18c785f68c168d430066546'] = 'Data final: primeiro'; $_MODULE['<{auctions}prestashop>product-auction-sort_d433ad4bd604d903813f971dc22fd750'] = 'Data final: último'; $_MODULE['<{auctions}prestashop>product-auction-sort_fcfa4e20eac7352c189d197c3e37c7f8'] = 'Não terminou em primeiro'; $_MODULE['<{auctions}prestashop>product-auction-sort_292028f6dc3b5e104cbb1696cf883f2f'] = 'Não terminou em último'; $_MODULE['<{auctions}prestashop>product-auction-sort_1c08c072224a847106eb1b0695421d85'] = 'Ofertas mais baixas primeiro'; $_MODULE['<{auctions}prestashop>product-auction-sort_2dc90e317e2fc32269448dc423bd22ce'] = 'Ofertas mais altas primeiro'; $_MODULE['<{auctions}prestashop>product-auction-bid_4b0666d501ffb7f063e0e57a3679b710'] = 'A sua oferta máxima'; $_MODULE['<{auctions}prestashop>product-auction-bid_dc43e863c176e9b9f2a0b6054b24bd1a'] = 'mínimo'; $_MODULE['<{auctions}prestashop>product-auction-bid_2e390f97a6e2a6aa36944493a2289921'] = 'Fazer uma licitação'; $_MODULE['<{auctions}prestashop>product-auction-bid_f8475fa736bbeda23386752b05c6434e'] = 'Por favor faça o login para fazer uma oferta'; $_MODULE['<{auctions}prestashop>product-auction-bid_8f03a0039a68d9dc8278418464617fd4'] = 'O leilão ainda não começou'; $_MODULE['<{auctions}prestashop>product-auction-buynow_ce5c84e9cdd556547feccefa544a63e7'] = 'Comprar agora por'; $_MODULE['<{auctions}prestashop>product-auction-buynow_eeceac1af4e7620894d6d2083921bb73'] = 'Comprar agora'; $_MODULE['<{auctions}prestashop>product-auction-buynow_9603b0643661cba534ae1fbb03074375'] = 'Esta opção desaparecerá à primeira licitação'; $_MODULE['<{auctions}prestashop>product-auction-details-subscription_ab969e2e7f1be90ea97f26cbfe1eb696'] = 'Parar de seguir o leilão'; $_MODULE['<{auctions}prestashop>product-auction-details-subscription_a164c87aab3d8460ce09cc4fa973cff5'] = 'Seguir o leilão'; $_MODULE['<{auctions}prestashop>product-auction-info_664b13315c97047b2ba2a1ac2375e0ce'] = 'Hora de início'; $_MODULE['<{auctions}prestashop>product-auction-info_be874332d03c079ef30ea63aef08a8e4'] = 'Hora de fecho'; $_MODULE['<{auctions}prestashop>product-auction-info_e02d2ae03de9d493df2b6b2d2813d302'] = 'Duração'; $_MODULE['<{auctions}prestashop>product-auction-info_5a7d87de341dba85983b6b94b751df76'] = 'Licitações'; $_MODULE['<{auctions}prestashop>product-auction-info_4fc841b21d544a170fc82e6f2fd0ab3b'] = 'Ver todas as licitações'; $_MODULE['<{auctions}prestashop>product-auction-info_5668e16d85b190bc09062d1e23f0dbab'] = 'Licitador vencendo'; $_MODULE['<{auctions}prestashop>product-auction-info_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>product-auction-list-buttons_ab969e2e7f1be90ea97f26cbfe1eb696'] = 'Parar de seguir o leilão'; $_MODULE['<{auctions}prestashop>product-auction-list-buttons_a164c87aab3d8460ce09cc4fa973cff5'] = 'Seguir o leilão'; $_MODULE['<{auctions}prestashop>product-auction-my-account_90d77b86534fedc93c9c992ae10cade4'] = 'Minhas licitações'; $_MODULE['<{auctions}prestashop>product-auction-price-reserve_ad4462475964d47e6b172faf9096836d'] = 'Preço de reserva alcançado'; $_MODULE['<{auctions}prestashop>product-auction-price-reserve_46df75197a1363ae4aae18a504bfcb75'] = 'Preço de reserva não alcançado'; $_MODULE['<{auctions}prestashop>product-auction-side-block-items_49fa2426b7903b3d4c89e2c1874d9346'] = 'Mais acerca'; $_MODULE['<{auctions}prestashop>product-auction-side-block-items_664b13315c97047b2ba2a1ac2375e0ce'] = 'Data início'; $_MODULE['<{auctions}prestashop>product-auction-side-block-items_be874332d03c079ef30ea63aef08a8e4'] = 'Data fecho'; $_MODULE['<{auctions}prestashop>product-auction-side-block-items_e02d2ae03de9d493df2b6b2d2813d302'] = 'Duração'; $_MODULE['<{auctions}prestashop>product-auction-side-block-items_5a7d87de341dba85983b6b94b751df76'] = 'Licitações'; $_MODULE['<{auctions}prestashop>product-auction-side-block-items_4fc841b21d544a170fc82e6f2fd0ab3b'] = 'Ver todas as licitações'; $_MODULE['<{auctions}prestashop>product-auction-side-block-items_5668e16d85b190bc09062d1e23f0dbab'] = 'Licitador vencendo'; $_MODULE['<{auctions}prestashop>product-auction-side-block-items_f0dec80a9e4065b22150db6b4621ff83'] = 'Preço inicial'; $_MODULE['<{auctions}prestashop>product-auction-tab-content_5a7d87de341dba85983b6b94b751df76'] = 'Licitações'; $_MODULE['<{auctions}prestashop>product-auction-tab-table_44749712dbec183e983dcd78a7736c41'] = 'Data'; $_MODULE['<{auctions}prestashop>product-auction-tab-table_78a27f1328136b77864bd562c49b902e'] = 'Licitante'; $_MODULE['<{auctions}prestashop>product-auction-tab-table_6bb24468956384c482a8b5a901fb6383'] = 'Oferta'; $_MODULE['<{auctions}prestashop>product-auction-tab-table_da602f0b162fccbf6b150cfcfc7a7379'] = 'eliminado'; $_MODULE['<{auctions}prestashop>product-auction-tab-table_5587bebac795507cfc0f4c3a2fc664ec'] = 'Sem licitações'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionArchivedDataManager', false)) return; class ProductAuctionArchivedDataManager { /** * * @return ProductAuction[] */ public static function getCollectionByInterval($outdate_interval, $limit = null, $lang_id = null) { if (empty($outdate_interval)) $outdate_interval = AuctionsFeaturesSettings::DEFAULT_OUTDATE_INTERVAL; $product_fields = CoreModuleTools::convertFields(Product::$definition, array( 'prefix' => 'p' )); $product_auction_fields = CoreModuleTools::convertFields(ProductAuction::$definition, array( 'prefix' => 'pa' )); $product_auction_offer_fields = CoreModuleTools::convertFields(ProductAuctionOffer::$definition, array( 'prefix' => 'pao' )); $product_auction_offer_customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $current_datetime = date('Y-m-d H:i:s'); $query = ' SELECT pl.id_lang, '.implode(', ', $product_fields).', '.implode(', ', $product_auction_fields).', '.implode(', ', $product_auction_offer_fields).', '.implode(', ', $product_auction_offer_customer_fields).' FROM `'._DB_PREFIX_.'product_auction` pa LEFT JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.id_product_auction_offer = pa.id_product_auction_offer) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (pao.id_customer = c.id_customer) WHERE pa.status IN ('.ProductAuction::STATUS_FINISHED.', '.ProductAuction::STATUS_CLOSED.') AND TIMESTAMPDIFF(DAY, pa.`to`, "'.$current_datetime.'") > '.(int)$outdate_interval.' '.($lang_id ? 'AND pl.`id_lang` ='.(int)$lang_id : null).' '.($limit ? 'LIMIT '.(int)$limit : null).' '; $result = Db::getInstance()->executeS($query); $product_auctions = array(); if (!empty($result)) { $classes = array( 'ProductAuction', 'Product', 'ProductAuctionOffer', 'Customer' ); $result = CoreModuleTools::hydrateCollection($classes, $result, $lang_id); foreach ($result['ProductAuction'] as $product_auction) { if (isset($result['Product'][$product_auction->id_product])) $product_auction->product = $result['Product'][$product_auction->id_product]; if (isset($result['ProductAuctionOffer'][$product_auction->id_product_auction_offer])) { $product_auction->product_auction_offer = $result['ProductAuctionOffer'][$product_auction->id_product_auction_offer]; if (isset($result['Customer'][$product_auction->product_auction_offer->id_customer])) $product_auction->product_auction_offer->customer = $result['Customer'][$product_auction->product_auction_offer->id_customer]; } $product_auctions[] = $product_auction; } } return $product_auctions; } public static function doArchive(ProductAuction $product_auction) { if (!is_array($product_auction->product->name)) { $name = $product_auction->product->name; $product_auction->product->name = array(); foreach (Language::getLanguages(true) as $language) $product_auction->product->name[$language['id_lang']] = $name; } $product_auction_archive = new ProductAuctionArchive(); $product_auction_archive->id = $product_auction->id; $product_auction_archive->id_product_auction = $product_auction->id; $product_auction_archive->id_product = $product_auction->id_product; $product_auction_archive->name = $product_auction->product->name; $product_auction_archive->initial_price = $product_auction->initial_price; $product_auction_archive->buynow_price = $product_auction->buynow_price; $product_auction_archive->minimal_price = $product_auction->minimal_price; $product_auction_archive->bid_step = $product_auction->bidding_increment; $product_auction_archive->from = $product_auction->from; $product_auction_archive->to = $product_auction->to; $product_auction_archive->offers = $product_auction->offers; $product_auction_archive->status = $product_auction->status; if (is_object($product_auction->product_auction_offer)) { $product_auction_archive->final_price = $product_auction->product_auction_offer->previous_price; $product_auction_archive->firstname = $product_auction->product_auction_offer->customer->firstname; $product_auction_archive->lastname = $product_auction->product_auction_offer->customer->lastname; $product_auction_archive->email = $product_auction->product_auction_offer->customer->email; } $success = $product_auction_archive->add(true, true); if ($success) $success &= $product_auction->product->delete(); return $success; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsBidsModuleFrontController', false)) return; class AuctionsBidsModuleFrontController extends CoreModuleController { public $display_column_left = false; public $display_column_right = false; protected $bidders = array(); public function process() { // Check page token if (!$this->isTokenValid()) die(Tools::displayError('Invalid token.')); parent::process(); $product_auction_id = Tools::getValue('id_product_auction'); if ($product_auction_id < 1) return; $product_auction_offer_status = array( ProductAuctionOffer::STATUS_VALID, ProductAuctionOffer::STATUS_WINNER ); $production_auction = new ProductAuction($product_auction_id, true, $this->context->language->id, $this->context->shop->id); $product_auction_type = $production_auction->getProductAuctionType(); $product_auction_offer_collection = ProductAuctionOfferDataManager::getCollectionByProductAuction($production_auction, $product_auction_offer_status, $this->context->language->id, $this->context->shop->id); $product_auction_offer_items = ProductAuctionOfferItemFactory::getInstance($this->module)->makeFrontOfficeItems($product_auction_offer_collection, $product_auction_type); foreach ($product_auction_offer_items as $product_auction_offer_item) { $this->bidders[] = array( 'customer_name' => $product_auction_offer_item->getCustomerName(), 'customer_name_full' => $product_auction_offer_item->getCustomerNameFull(), 'customer_bid' => $product_auction_offer_item->getCustomerBid(), 'date_add' => $product_auction_offer_item->getOfferDate() ); } $this->setTemplate('product-auction-tab-table.tpl'); } public function display() { if (isset($_SERVER['HTTP_REFERER'])) Tools::redirect($_SERVER['HTTP_REFERER']); } public function displayHeader($display = true) { } public function displayFooter($display = true) { } protected function smartyOutputContent($content) { $this->context->cookie->write(); if (is_array($content)) foreach ($content as $tpl) $html = $this->context->smarty->fetch($tpl); else $html = $this->context->smarty->fetch($content); echo $html; } public function displayAjax() { $this->context->smarty->assign(array( 'offers' => $this->bidders )); return $this->smartyOutputContent($this->template); } /** * Get path to front office templates for the module * * @return string */ public function getTemplatePath($template) { if (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$this->module->name.'/'.$template)) return _PS_THEME_DIR_.'modules/'.$this->module->name.'/'.$template; elseif (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$this->module->name.'/views/templates/hook/'.$template)) return _PS_THEME_DIR_.'modules/'.$this->module->name.'/views/templates/hook/'.$template; elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$this->module->name.'/views/templates/hook/'.$template)) return _PS_MODULE_DIR_.$this->module->name.'/views/templates/hook/'.$template; return false; } } <file_sep><?php require_once "common.php"; //capture code from auth $code = $_GET["code"]; //construct POST object for access token fetch request $postvals = sprintf("client_id=%s&client_secret=%s&grant_type=authorization_code&code=%s&redirect_uri=%s", KEY, SECRET, $code, urlencode(CALLBACK_URL)); //get JSON access token object (with refresh_token parameter) $token = json_decode(run_curl(ACCESS_TOKEN_ENDPOINT, 'POST', $postvals)); //construct URI to fetch profile information for current user $profile_url = sprintf("%s?oauth_token=%s", PROFILE_ENDPOINT, $token->access_token); //fetch profile of current user $profile = run_curl($profile_url); var_dump($profile); ?> <file_sep><?php abstract class Controller extends ControllerCore { public function run() { //if the module is disabled, do not process the override if(!Module::isInstalled('expresscache') || !Module::isEnabled('expresscache')) { return parent::run(); } if(Configuration::get('EXPRESSCACHE_PROFILING')) { $then = microtime(true); } $cache = false; $page_name = Dispatcher::getInstance()->getController(); $c_controllers = explode(',', Configuration::get('EXPRESSCACHE_CONTROLLERS')); $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; $isLogged = isset($this->context->customer) ? $this->context->customer->isLogged() : false; $isMobile = $this->context->getMobileDevice(); //check if we have to serve cached page or not if(in_array($page_name, $c_controllers) && !isset($_GET['refresh_cache']) && !isset($_GET['live_edit']) && !isset($_GET['no_cache']) && count($_POST) == 0 && !$isAjax && !$isLogged && !$isMobile) { $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://'; $page_id = md5($proto.$_SERVER['REQUEST_URI']); $context = Context::getContext(); $id_langauge = (int)$this->context->language->id; $id_country = (int)$this->context->country->id; $id_shop = (int)$this->context->shop->id; //currency is still not set in Front controller. $currency = Tools::setCurrency($this->context->cookie); $id_currency = $currency->id; $cache = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(" SELECT cache, last_updated FROM "._DB_PREFIX_."express_cache WHERE page_id = '".$page_id."' and id_language = ".$id_langauge." and id_currency = ".$id_currency." and id_country = ".$id_country." and id_shop = ".$id_shop); //var_dump($cache); if($cache != false) { if(!Configuration::get('EXPRESSCACHE_STORE_IN_DB')) { $filename = $cache[0]['cache']; //read from filesystem with filename $cache_dir = _PS_MODULE_DIR_.'expresscache/cache/'; $content = file_get_contents($cache_dir.$filename); } else { $content = $cache[0]['cache']; } //check if cache is within timeout reach, otherwise delete the cache to get a fresh entry in FrontController.php $last_updated = strtotime($cache[0]['last_updated']); $now = strtotime(date('Y-m-d H:i:s')); if(round(abs($now - $last_updated) / 60,2) > Configuration::get('EXPRESSCACHE_TIMEOUT')) { Db::getInstance(_PS_USE_SQL_SLAVE_)->execute(" DELETE FROM "._DB_PREFIX_."express_cache WHERE page_id = '".$page_id."'"); $cache = false; } } } //do not show POST request as cache. if($cache) { //write cookie and echo the content $this->context->cookie->write(); if(Configuration::get('EXPRESSCACHE_PROFILING')) { $now = microtime(true); $cache_time = "Cached Page - "; $cache_time .= sprintf("Elapsed: %f", $now-$then); $content = str_replace('</body>',$cache_time.'</body>',$content); } $expresscache_cookie = new Cookie('expresscache', '/'); if(Configuration::get('ADVCACHEMGMT') == true && $expresscache_cookie->advcachemgmt == 1) { //$this->context->controller->addCSS(($this->_path).'advcachemgmt.css', 'all'); /*return "<script>$(document).ready(function() { clearCacheBtn = '<input type='submit' value='".$this->l('Refresh Cache')."' id='refreshCache' class='button' style='background: #333 none; color:#fff; border:1px solid #000; float:right; margin-right:10px;'>'; $('#closeLiveEdit').after('Vikas'); }); </script>";*/ $content .= '<div style=" background-color:000; background-color: rgba(0,0,0, 0.7); border-bottom: 1px solid #000; width:100%;height:30px; padding:5px 10px; position:fixed;top:0;left:0;z-index:9999;">'; $content .= "<form method='GET'><input type='submit' name = 'refresh_cache' value='".'Refresh Cache'."' id='refreshCache' class='button' style='background: #333 none; color:#fff; border:1px solid #000; float:right; margin-right:20px;'>"; $content .= '<input type="submit" value="View Live Page" name="no_cache" id="viewLivePage" class="exclusive" style="color:#fff;float:right; text-shadow: 0 -1px 0 #157402; margin-right:10px;">'; foreach($_GET as $key=>$val) { $content .= '<input type="hidden" value="'.Tools::getValue($key).'" name="'.$key.'">'; } $content .= '</form></div>'; } echo $content; } else { $display = parent::run();/* if(Configuration::get('EXPRESSCACHE_PROFILING') && in_array($page_name, $c_controllers)) { $now = microtime(true); echo "<!-- Live Page - "; echo sprintf("Elapsed: %f", $now-$then).' -->'; }*/ return; } } } ?><file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractProductAuctionObjectItem', false)) return; abstract class AbstractProductAuctionObjectItem { /** * * @var ObjectModel */ protected $object_model; /** * * @var ProductAuctionDateTime */ protected $date_time_formatter; /** * * @var AbstractAuctionsPriceCalculator */ protected $price_calculator; /** * * @var AbstractAuctionsCustomerName */ protected $customer_name_formatter; public function __construct(ObjectModelCore $object_model = null) { if ($object_model) $this->setObjectModel($object_model); $this->setDateTimeFormatter(new NullAuctionsDateTime()); $this->setPriceCalculator(new NullAuctionsPriceCalculator()); $this->setCustomerNameFormatter(new NullAuctionsCustomerName()); } /** * * @return Product */ abstract public function getProduct(); /** * * @return ObjectModel */ public function getObjectModel() { return $this->object_model; } /** * * @param ObjectModelCore $object_model */ public function setObjectModel(ObjectModelCore $object_model) { $this->object_model = $object_model; } /** * * @param AbstractAuctionsDateTime $date_time_formatter */ public function setDateTimeFormatter(AbstractAuctionsDateTime $date_time_formatter) { $this->date_time_formatter = $date_time_formatter; } /** * * @param AbstractAuctionsPriceCalculator $price_calculator */ public function setPriceCalculator(AbstractAuctionsPriceCalculator $price_calculator) { $this->price_calculator = $price_calculator; } /** * * @param AbstractAuctionsCustomerName $customer_name_formatter */ public function setCustomerNameFormatter(AbstractAuctionsCustomerName $customer_name_formatter) { $this->customer_name_formatter = $customer_name_formatter; } } <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'PowaTagAPIAbstract.php'; class PowaTagAPI extends PowaTagAPIAbstract { public function __construct($request) { $this->loadClasses(); parent::__construct($request); // Abstracted out for example $APIKey = new PowaTagAPIKey(); if (!Module::isInstalled('powatag') || !Module::isEnabled('powatag')) { throw new Exception('Module not enable'); } if (!array_key_exists('HTTP_HMAC', $_SERVER)) { throw new Exception('No API Key provided'); } elseif (!$APIKey->verifyKey($_SERVER['HTTP_HMAC'], $this->data)) { throw new Exception('Invalid API Key'); } $this->data = Tools::jsonDecode($this->data); } /** * Load classes. */ private function loadClasses() { $path = dirname(__FILE__).DIRECTORY_SEPARATOR; foreach (scandir($path) as $file) { if (is_file($path.$file) && preg_match('#.php$#isD', $file) && $file != 'index.php') { require_once $path.$file; } } $path .= 'classes'.DIRECTORY_SEPARATOR; foreach (scandir($path) as $file) { if (is_file($path.$file) && preg_match('#.php$#isD', $file) && $file != 'index.php') { require_once $path.$file; } } } /** * Products endpoint. */ protected function products($args) { if ($args || $this->verb) { if ($args) { $idProduct = current($args); } elseif ($this->verb) { $idProduct = $this->verb; } if (self::apiLog()) { PowaTagLogs::initAPILog('Process get products', PowaTagLogs::IN_PROGRESS, 'Id product : '.$idProduct); } if (self::requestLog()) { PowaTagLogs::initRequestLog('Process get products', PowaTagLogs::IN_PROGRESS, $args); } $stdClass = new stdClass(); $stdClass->id_product = $idProduct; $powatagProduct = new PowaTagProduct($stdClass); //Handle to get one specific products if ($value = $powatagProduct->setJSONRequest()) { if (self::apiLog()) { PowaTagLogs::initAPILog('Process get products', PowaTagLogs::SUCCESS, 'Id product : '.$idProduct); } if (self::requestLog()) { PowaTagLogs::initRequestLog('Process get products', PowaTagLogs::SUCCESS, $value); } return array('products' => array($value)); } else { $error = $powatagProduct->getError(); if (self::apiLog()) { PowaTagLogs::initAPILog('Process get products', PowaTagLogs::ERROR, $error['message']); } return self::powaError($error); } } else { $msg = 'No product mentionned'; if (self::apiLog()) { PowaTagLogs::initAPILog('Process get products', PowaTagLogs::ERROR, $msg); } return $msg; } } /** * Orders endpoint. */ protected function orders($args) { // Manage informations $datas = $this->data; if (is_null($datas)) { return self::powaError(array( 'error' => PowaTagErrorType::$BAD_REQUEST, 'message' => 'Empty request' )); } if ($this->verb == 'costs') { if (isset($datas->order)) { $customer = $datas->order->customer; } else { $customer = current($datas->orders)->customer; } if (self::apiLog()) { PowaTagLogs::initAPILog('Process calculate Costs', PowaTagLogs::IN_PROGRESS, 'Customer : '.$customer->firstName.' '.$customer->lastName); } if (self::requestLog()) { PowaTagLogs::initRequestLog('Process calculate Costs', PowaTagLogs::IN_PROGRESS, $datas); } $powatagcosts = new PowaTagCosts($datas); if ($error = $powatagcosts->getError()) { $message = $error['message']; if (self::apiLog()) { PowaTagLogs::initAPILog('Process order', PowaTagLogs::ERROR, $message); } return self::powaError($error); } if ($value = $powatagcosts->getSummary()) { if (self::apiLog()) { PowaTagLogs::initAPILog('Process calculate Costs', PowaTagLogs::SUCCESS, 'Customer : '.$customer->firstName.' '.$customer->lastName); } if (self::requestLog()) { PowaTagLogs::initRequestLog('Process calculate Costs', PowaTagLogs::SUCCESS, $value); } return $value; } else { $error = $powatagcosts->getError(); if (self::apiLog()) { PowaTagLogs::initAPILog('Process calculate Costs', PowaTagLogs::ERROR, $error['message']); } return self::powaError($error); } } elseif (count($args) == 2 && Validate::isInt($args[0]) && $args[1] = 'confirm-payment') { //Three step payment confirmation if (self::apiLog()) { PowaTagLogs::initAPILog('Process payment', PowaTagLogs::IN_PROGRESS, 'Order ID : '.$args[0]); } if (self::requestLog()) { PowaTagLogs::initRequestLog('Create payment', PowaTagLogs::IN_PROGRESS, $datas); } $payment = new PowaTagPayment($datas, (int) $args[0]); if ($id_order = $payment->confirmPayment()) { if (self::apiLog()) { PowaTagLogs::initAPILog('Process payment', PowaTagLogs::SUCCESS, 'ID Order : '.$id_order); } if (self::requestLog()) { PowaTagLogs::initRequestLog('Process payment', PowaTagLogs::SUCCESS, $id_order); } $data = array( 'providerTxCode' => isset($datas->paymentResult->providerTxCode) ? $datas->paymentResult->providerTxCode : 'providerTxCode Empty', 'message' => 'Authorization success order '.$id_order.' created', ); if ($payment->checkOrderState($id_order, $data) == 'error') { $this->setResponse($data['response']); } return $data; } else { $error = $payment->getError(); if (self::apiLog()) { PowaTagLogs::initAPILog('Process payment', PowaTagLogs::ERROR, $error['message']); } return self::powaError($error); } } elseif (!count($args)) { //Two step payment or three step payment if (isset($datas->order)) { $customer = $datas->order->customer; } else { $customer = current($datas->orders)->customer; } if (self::apiLog()) { PowaTagLogs::initAPILog('Process order 123', PowaTagLogs::IN_PROGRESS, 'Customer : '.$customer->firstName.' '.$customer->lastName); } if (self::requestLog()) { PowaTagLogs::initRequestLog('Create order', PowaTagLogs::IN_PROGRESS, $datas); } $order = new PowaTagOrders($datas); if ($error = $order->getError()) { $message = $error['message']; if (self::apiLog()) { PowaTagLogs::initAPILog('Process order', PowaTagLogs::ERROR, $message); } return self::powaError($error); } list($id_cart, $id_order, $message) = $order->validateOrder(); if ($id_order || $id_cart) { if (self::apiLog()) { PowaTagLogs::initAPILog('Process order', PowaTagLogs::SUCCESS, 'Order has been created : '.$id_order); } $link = new Link(); $cart = new Cart($id_cart); $data = array( 'orderResults' => array( array( 'orderId' => $id_order ? $id_order : $id_cart, 'message' => $message, 'redirectUrl' => $link->getModuleLink('powatag', 'confirmation', array('id_cart' => (int) $id_cart, 'id_customer' => (int) $cart->id_customer)), ), ), ); if ($error = $order->getError()) { return self::powaError($error); } if ($order->checkOrderState($id_order, $data)) { $this->setResponse($data['response']); } return $data; } else { if ($error = $order->getError()) { $message = $error['message']; } else { $error = array( 'error' => PowaTagErrorType::$FAILED_TO_PLACE_ORDER, 'message' => $message ); } if (self::apiLog()) { PowaTagLogs::initAPILog('Process order', PowaTagLogs::ERROR, $message); } return self::powaError($error); } } } /** * getproducts endpoint - multiple SKU getProduct. */ protected function getproducts() { $sku = Tools::getValue('sku'); if (self::requestLog()) { PowaTagLogs::initRequestLog('Process get multiple products', PowaTagLogs::SUCCESS, $sku); } if ($sku == '') { return self::powaError(array( 'error' => PowaTagErrorType::$SKU_NOT_FOUND, 'message' => 'Missing SKU value', )); } $asku = explode(',', $sku); $reply = array(); foreach ($asku as $idProduct) { $stdClass = new stdClass(); $stdClass->id_product = $idProduct; $powatagProduct = new PowaTagProduct($stdClass); $detail = $powatagProduct->setJSONRequest(); if ($detail === false) { $detail = array( 'code' => $idProduct, 'availability' => 'false', ); } else { $detail['availability'] = 'true'; } $reply[] = $detail; } return array('products' => $reply); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (!class_exists('CoreModuleCronController', false)) { class CoreModuleCronController extends CoreModuleController { const FLAG_EXPIRATION = 600; protected $file_path = __FILE__; public $ssl = false; public $display_header = false; public $display_footer = false; public $display_column_left = false; public $display_column_right = false; public $content_only = true; public $auth = false; public $php_self = null; public $redirect_after = null; public $status; public function __construct() { parent::__construct(); $this->display_column_left = false; $this->display_column_right = false; $this->display_header = false; $this->display_footer = false; $this->content_only = true; $this->auth = false; $secure_key = CoreModuleTools::getSecureKey(get_class($this)); if ($secure_key !== Tools::getValue('secure_key')) exit('UNAUTHORIZED'); if ($this->hasFlag($this->getFlagFile())) exit('ALREADY RUNNING'); $this->setFlag($this->getFlagFile()); } public function __destruct() { $this->unsetFlag($this->getFlagFile()); } protected function getFlagFile() { return $this->module->getLocalPath()."cache/cron/{$this->getLocalFile()}.flag"; } protected function getLocalFile() { return Tools::str_replace_once('.php', '', pathinfo($this->file_path, PATHINFO_FILENAME)); } protected function hasFlag($flag) { return file_exists($flag) && time() - filemtime($flag) < self::FLAG_EXPIRATION; } protected function setFlag($flag) { if (!is_dir(dirname($flag))) mkdir(dirname($flag), 0777, true); return file_put_contents($flag, time()); } protected function unsetFlag($flag) { return unlink($flag); } protected function smartyOutputContent($content) { $this->context->smarty->display($content); } /** * * @see Controller::checkAccess() * * @return boolean */ public function checkAccess() { return true; } /** * * @see Controller::viewAccess * * @return boolean */ public function viewAccess() { return true; } public function initHeader() { } public function initContent() { } public function initFooter() { } public function process() { } public function redirect() { } public function recoverCart() { return false; } public function displayMaintenancePage() { return false; } public function displayRestrictedCountryPage() { return false; } } } <file_sep><?php return array ( 'AbstractAuctionsCustomerName' => 'classes/helpers/name/abstractauctionscustomername.php', 'AbstractAuctionsDateTime' => 'classes/helpers/datetime/abstractauctionsdatetime.php', 'AbstractAuctionsPriceCalculator' => 'classes/helpers/pricecalculator/abstractauctionspricecalculator.php', 'AbstractProductAuctionBid' => 'classes/types/abstract/bid/abstractproductauctionbid.php', 'AbstractProductAuctionBidResult' => 'classes/types/abstract/bid/abstractproductauctionbidresult.php', 'AbstractProductAuctionBuilder' => 'classes/builders/abstractproductauctionbuilder.php', 'AbstractProductAuctionCreate' => 'classes/types/abstract/create/abstractproductauctioncreate.php', 'AbstractProductAuctionEvent' => 'classes/events/AbstractProductAuctionEvent.php', 'AbstractProductAuctionItem' => 'classes/types/abstract/abstractproductauctionitem.php', 'AbstractProductAuctionItemFactory' => 'classes/factories/abstractproductauctionitemfactory.php', 'AbstractProductAuctionMailingItem' => 'classes/types/abstract/abstractproductauctionmailingitem.php', 'AbstractProductAuctionMailingManager' => 'classes/types/abstract/mailing/abstractproductauctionmailingmanager.php', 'AbstractProductAuctionMailingRecipient' => 'classes/types/abstract/mailing/abstractproductauctionmailingrecipient.php', 'AbstractProductAuctionObjectItem' => 'classes/builders/abstractproductauctionobjectitem.php', 'AbstractProductAuctionOfferItem' => 'classes/types/abstract/abstractproductauctionofferitem.php', 'AbstractProductAuctionPermissions' => 'classes/types/abstract/permissions/abstractproductauctionpermissions.php', 'AbstractProductAuctionType' => 'classes/types/abstract/type/abstractproductauctiontype.php', 'AbstractProductAuctionValidator' => 'classes/types/abstract/validator/abstractproductauctionvalidator.php', 'AdminAuctionsArchivedController' => 'controllers/admin/AdminAuctionsArchivedController.php', 'AdminAuctionsController' => 'controllers/admin/AdminAuctionsController.php', 'AdminAuctionsSettingsController' => 'controllers/admin/AdminAuctionsSettingsController.php', 'AdminAuctionsSubscriptionsController' => 'controllers/admin/AdminAuctionsSubscriptionsController.php', 'AdminAuctionsTabController' => 'controllers/admin/AdminAuctionsTabController.php', 'AdminAuctionsTemplatesController' => 'controllers/admin/AdminAuctionsTemplatesController.php', 'AdminAuctionsViewController' => 'controllers/admin/AdminAuctionsViewController.php', 'AdminAuctionsWinnersController' => 'controllers/admin/AdminAuctionsWinnersController.php', 'AuctionsAppearanceSettings' => 'classes/settings/tabs/auctionsappearancesettings.php', 'AuctionsBlocksSettings' => 'classes/settings/tabs/auctionsblockssettings.php', 'AuctionsCronSettings' => 'classes/settings/tabs/auctionscronsettings.php', 'AuctionsFeaturesSettings' => 'classes/settings/tabs/auctionsfeaturessettings.php', 'AuctionsListController' => 'classes/controllers/front/auctionslistcontroller.php', 'AuctionsMailingSettings' => 'classes/settings/tabs/auctionsmailingsettings.php', 'AuctionsMyAuctionsController' => 'classes/controllers/front/auctionsmyauctionscontroller.php', 'BackOfficeProductAuctionBuilder' => 'classes/builders/backofficeproductauctionbuilder.php', 'CoreModule' => 'classes/core/coremodule.php', 'CoreModuleAutoloader' => 'classes/core/coremoduleautoloader.php', 'CoreModuleColumnFormatter' => 'classes/core/list/coremodulecolumnformatter.php', 'CoreModuleController' => 'classes/core/coremodulecontroller.php', 'CoreModuleCronController' => 'classes/core/cron/coremodulecroncontroller.php', 'CoreModuleEventCallback' => 'classes/core/events/coremoduleeventcallback.php', 'CoreModuleEventDispatcher' => 'classes/core/events/coremoduleeventdispatcher.php', 'CoreModuleEventInterface' => 'classes/core/events/coremoduleeventinterface.php', 'CoreModuleEventListenerInterface' => 'classes/core/events/coremoduleeventlistenerinterface.php', 'CoreModuleHelperForm' => 'classes/core/form/coremodulehelperform.php', 'CoreModuleHelperFormDataModelInterface' => 'classes/core/interface/coremodulehelperformdatamodelinterface.php', 'CoreModuleLink' => 'classes/core/coremodulelink.php', 'CoreModuleObject' => 'classes/core/coremoduleobject.php', 'CoreModuleSettings' => 'classes/core/coremodulesettings.php', 'CoreModuleTools' => 'classes/core/coremoduletools.php', 'DirectorProductAuctionBuilder' => 'classes/builders/directorproductauctionbuilder.php', 'DummySettings' => 'classes/settings/dummysettings.php', 'EmailAliasAuctionsCustomerName' => 'classes/helpers/name/emailaliasauctionscustomername.php', 'EmailAuctionsCustomerName' => 'classes/helpers/name/emailauctionscustomername.php', 'FirstNameAuctionsCustomerName' => 'classes/helpers/name/firstnameauctionscustomername.php', 'FormattedAuctionsDateTime' => 'classes/helpers/datetime/formattedauctionsdatetime.php', 'FrontOfficeProductAuctionBuilder' => 'classes/builders/frontofficeproductauctionbuilder.php', 'FullNameAuctionsCustomerName' => 'classes/helpers/name/fullnameauctionscustomername.php', 'GrossAuctionsPriceCalculator' => 'classes/helpers/pricecalculator/grossauctionspricecalculator.php', 'HiddenAuctionsCustomerName' => 'classes/helpers/name/hiddenauctionscustomername.php', 'LastNameAuctionsCustomerName' => 'classes/helpers/name/lastnameauctionscustomername.php', 'NetAuctionsPriceCalculator' => 'classes/helpers/pricecalculator/netauctionspricecalculator.php', 'NickNameAuctionsCustomerName' => 'classes/helpers/name/nicknameauctionscustomername.php', 'NullAuctionsCustomerName' => 'classes/helpers/name/nullauctionscustomername.php', 'NullAuctionsDateTime' => 'classes/helpers/datetime/nullauctionsdatetime.php', 'NullAuctionsPriceCalculator' => 'classes/helpers/pricecalculator/nullauctionspricecalculator.php', 'ProductAuction' => 'classes/model/productauction.php', 'ProductAuctionArchive' => 'classes/model/productauctionarchive.php', 'ProductAuctionArchivedDataManager' => 'classes/model/data_manager/productauctionarchiveddatamanager.php', 'ProductAuctionBidEnglish' => 'classes/types/english/bid/productauctionbidenglish.php', 'ProductAuctionBidResultEnglish' => 'classes/types/english/bid/productauctionbidresultenglish.php', 'ProductAuctionCreateEnglish' => 'classes/types/english/create/productauctioncreateenglish.php', 'ProductAuctionDataManager' => 'classes/model/data_manager/productauctiondatamanager.php', 'ProductAuctionEventAcceptWinner' => 'classes/events/ProductAuctionEventAcceptWinner.php', 'ProductAuctionEventBid' => 'classes/events/ProductAuctionEventBid.php', 'ProductAuctionEventFinish' => 'classes/events/ProductAuctionEventFinish.php', 'ProductAuctionEventReject' => 'classes/events/ProductAuctionEventReject.php', 'ProductAuctionEventRemind' => 'classes/events/ProductAuctionEventRemind.php', 'ProductAuctionEventRestart' => 'classes/events/ProductAuctionEventRestart.php', 'ProductAuctionItemEnglish' => 'classes/types/english/productauctionitemenglish.php', 'ProductAuctionItemFactory' => 'classes/factories/productauctionitemfactory.php', 'ProductAuctionLoader' => 'classes/cache/productauctionloader.php', 'ProductAuctionMailing' => 'classes/model/productauctionmailing.php', 'ProductAuctionMailingDataManager' => 'classes/model/data_manager/productauctionmailingdatamanager.php', 'ProductAuctionMailingItemEnglish' => 'classes/types/english/productauctionmailingitemenglish.php', 'ProductAuctionMailingItemFactory' => 'classes/factories/productauctionmailingitemfactory.php', 'ProductAuctionMailingManagerEnglish' => 'classes/types/english/mailing/productauctionmailingmanagerenglish.php', 'ProductAuctionMailingRecipientEnglish' => 'classes/types/english/mailing/productauctionmailingrecipientenglish.php', 'ProductAuctionObjectModel' => 'classes/model/object_model/productauctionobjectmodel.php', 'ProductAuctionOffer' => 'classes/model/productauctionoffer.php', 'ProductAuctionOfferDataManager' => 'classes/model/data_manager/productauctionofferdatamanager.php', 'ProductAuctionOfferItemEnglish' => 'classes/types/english/productauctionofferitemenglish.php', 'ProductAuctionOfferItemFactory' => 'classes/factories/productauctionofferitemfactory.php', 'ProductAuctionPermissionsEnglish' => 'classes/types/english/permissions/productauctionpermissionsenglish.php', 'ProductAuctionSubscriptionDataManager' => 'classes/model/data_manager/productauctionsubscriptiondatamanager.php', 'ProductAuctionTemplate' => 'classes/model/productauctiontemplate.php', 'ProductAuctionTemplateDataManager' => 'classes/model/data_manager/productauctiontemplatedatamanager.php', 'ProductAuctionType' => 'classes/model/productauctiontype.php', 'ProductAuctionTypeEnglish' => 'classes/types/english/type/productauctiontypeenglish.php', 'ProductAuctionTypeFactory' => 'classes/factories/productauctiontypefactory.php', 'ProductAuctionValidatorEnglish' => 'classes/types/english/validator/productauctionvalidatorenglish.php', 'ProductAuctionsObjectTemplatesInterface' => 'classes/interface/productauctionsobjecttemplatesinterface.php', 'ProductDataManager' => 'classes/model/data_manager/productdatamanager.php', ); ?><file_sep>$(document).ready(function(){ // alert($('.flexslider').length); $('.flexslider').flexslider({ animation: "fade", animationLoop:1, slideshowSpeed: 3000, animationSpeed: 500, start: function(slider){ $('body').removeClass('loading'); } }); })<file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_12641546686fe11aaeb3b3c43a18c1b3'] = 'Il tuo Carrello'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_7fc68677a16caa0f02826182468617e6'] = 'Carrello:'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_f5bf48aa40cad7891eb709fcf1fde128'] = 'prodotto'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_86024cad1e83101d97359d7351051156'] = 'prodotti'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(Vuoto)'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_a0623b78a5f2cfe415d9dbbd4428ea40'] = 'Il tuo Account'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_83218ac34c1834c26781fe4bde918ee4'] = 'Benvenuto'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4b877ba8588b19f1b278510bf2b57ebb'] = 'Esci in'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4394c8d8e63c470de62ced3ae85de5ae'] = 'Esci'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_bffe9a3c9a7e00ba00a11749e022d911'] = 'Log in'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author Presta<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); require_once (_PS_MODULE_DIR_.'auctions/classes/core/coremodule.php'); class Auctions extends CoreModule { /** * * @var string */ protected $file_path = __FILE__; /** * * @var ProductAuction */ protected $product_auction; /** * * @var ProductAuctionItem */ protected $product_auction_item; public function __construct() { $this->bootstrap = true; $this->author = '<EMAIL>'; $this->version = '3.0.2'; $this->name = 'auctions'; $this->tab = 'front_office_features'; $this->module_key = '0546d00224d2e9b94d70af26f595fa3d'; $this->supported_versions = array( self::MOD_PS16, ); parent::__construct(); $this->displayName = $this->l('Auctions'); $this->description = $this->l('Add auction functionality to your prestashop'); $this->context->smarty->assign(array( '_auctions_module' => $this )); $this->context->smarty->assign(array( 'product_auction_list_path' => $this->getTemplatePath('product-auction-list.tpl') )); $this->context->smarty->assign(array( 'currencySign' => isset($this->context->currency) ? $this->context->currency->sign : null, 'currencyRate' => isset($this->context->currency) ? $this->context->currency->conversion_rate : null, 'currencyFormat' => isset($this->context->currency) ? $this->context->currency->format : null, 'currencyBlank' => isset($this->context->currency) ? $this->context->currency->blank : null )); } protected function initTabsDefinition() { $this->tabs = array( 'AdminAuctionsTab' => array( 'parent' => null, 'active' => 1, 'title' => array( Language::getIdByIso('en') => 'Auctions', Language::getIdByIso('pl') => 'Aukcje', ) ), 'AdminAuctions' => array( 'parent' => 'AdminAuctionsTab', 'active' => 1, 'title' => array( Language::getIdByIso('en') => 'Auctions', Language::getIdByIso('pl') => 'Aukcje', ) ), 'AdminAuctionsView' => array( 'parent' => 'AdminAuctions', 'active' => 1, 'title' => array( Language::getIdByIso('en') => 'Auction', Language::getIdByIso('pl') => 'Aukcja', ) ), 'AdminAuctionsWinners' => array( 'parent' => 'AdminAuctionsTab', 'active' => 1, 'title' => array( Language::getIdByIso('en') => 'Winners', Language::getIdByIso('pl') => 'Zwycięzcy', ) ), 'AdminAuctionsTemplates' => array( 'parent' => 'AdminAuctionsTab', 'active' => 1, 'title' => array( Language::getIdByIso('en') => 'Templates', Language::getIdByIso('pl') => 'Szablony', ) ), 'AdminAuctionsArchived' => array( 'parent' => 'AdminAuctionsTab', 'active' => 0, 'title' => array( Language::getIdByIso('en') => 'Archived auctions', Language::getIdByIso('pl') => 'Archiwalne aukcje', ) ), 'AdminAuctionsSubscriptions' => array( 'parent' => 'AdminAuctionsTab', 'active' => 0, 'title' => array( Language::getIdByIso('en') => 'Watching list', Language::getIdByIso('pl') => 'Subskrypcje', ) ), ); } protected function initSettingsDefinition() { $this->settings = array( 'AuctionsFeaturesSettings', 'AuctionsAppearanceSettings', 'AuctionsBlocksSettings', 'AuctionsMailingSettings', 'AuctionsCronSettings' ); } protected function initHooksDefinition() { $this->hooks = array( /* backoffice header */ 'displayBackOfficeHeader', /* auction tab */ 'displayAdminProductsExtra', /* auction validation */ 'actionAdminProductsCheckProduct', /* new auction */ 'actionObjectProductAddAfter', 'actionObjectProductAddBefore', /* update auction */ 'actionObjectProductUpdateAfter', 'actionObjectProductUpdateBefore', /* save cart */ 'actionCartSave', /* validate order */ 'actionValidateOrder', /* frontoffice header */ 'displayHeader', /* frontoffice footer */ 'displayFooter', /* product details */ 'displayRightColumnProduct', 'displayLeftColumnProduct', /* product details tab */ 'displayProductTab', /* product details tab content */ 'displayProductTabContent', /* shop home/left/right blocks */ 'displayRightColumn', 'displayLeftColumn', 'displayHome', /* product list */ 'actionProductListModifier', 'displayProductPriceBlock', 'displayProductDeliveryTime', 'displayProductListFunctionalButtons', /* my account */ 'displayCustomerAccount', 'displayMyAccountBlock', 'displayMyAccountBlockfooter', ); } protected function initAuction(&$params) { $product_auction_item = null; $product_auction_loader = ProductAuctionLoader::getInstance($this); if ($this->context->controller instanceof ProductControllerCore) { $product = $this->context->controller->getProduct(); $product_auction_item = $product_auction_loader->getProductAuctionItem($product->id); if (!$product_auction_item) return false; $type = AbstractProductAuctionPermissions::TYPE_DETAILS; if ($product_auction_item->canCheckOut($this->context->customer)) { $product->available_now = false; $product->specificPrice = false; $this->context->smarty->assign('allow_oosp', true); $this->context->smarty->assign('display_qties', false); } else $product->available_for_order = false; $product_auction = $this->convertProductAuctionItemToArray($product_auction_item, $type); $this->context->smarty->assign(array( 'permission_type' => $type, 'auction' => $product_auction, )); } else { $product_auction_item = $product_auction_loader->getProductAuctionItem($params['product']['id_product']); if (!$product_auction_item) return false; $type = AbstractProductAuctionPermissions::TYPE_LIST; $product_auctions_subscriptions = array(); if ($this->context->customer) $product_auctions_subscriptions = $product_auction_loader->getSubscribedAuctionIds($this->context->customer); if ($product_auction_item->canCheckOut($this->context->customer)) { $params['product']['available_now'] = null; $params['product']['specific_prices'] = null; } else $params['product']['available_for_order'] = false; $product_auction = $this->convertProductAuctionItemToArray($product_auction_item, $type); $product_auction['is_watched'] = in_array($product_auction_item->getId(), $product_auctions_subscriptions); $this->context->smarty->assign(array( 'permission_type' => $type, 'auction' => $product_auction, )); } return $product_auction_item; } protected function initByProductId($product_id, $create_empty_instance = false, $with_disabled = false) { if (!ValidateCore::isLoadedObject($this->product_auction) || $this->product_auction->id_product != $product_id) $this->product_auction = ProductAuctionDataManager::getByProductId($product_id, $this->context->language->id, $this->context->shop->id, !$with_disabled); if ($create_empty_instance && !Validate::isLoadedObject($this->product_auction)) $this->product_auction = new ProductAuction(null, true, $this->context->language->id, $this->context->shop->id); } protected function initByProduct(Product $product, $create_empty_instance = false, $with_disabled = false) { if (!ValidateCore::isLoadedObject($this->product_auction) || $this->product_auction->id_product != $product->id) $this->product_auction = ProductAuctionDataManager::getByProduct($product, $this->context->language->id, $this->context->shop->id, !$with_disabled); if ($create_empty_instance && !Validate::isLoadedObject($this->product_auction)) $this->product_auction = new ProductAuction(null, true, $this->context->language->id, $this->context->shop->id); } protected function checkWarnings() { parent::checkWarnings(); if (!function_exists('curl_init')) $this->warning .= ' '.$this->l('cURL extension must be enabled on your server to use this module.'); } /* Hooks */ public function hookDisplayBackOfficeHeader() { $this->context->controller->addCSS(array( $this->getPathUri().'css/admin-auctions.css' ), 'all'); $this->context->controller->addJs(array( $this->getPathUri().'js/admin-auctions.js' )); } public function hookDisplayAdminProductsExtra() { $product_id = (int)Tools::getValue(Product::$definition['primary']); $product = new Product($product_id, null); $tab_id = Tab::getIdFromClassName('AdminAuctions'); $tab_access = Profile::getProfileAccess($this->context->employee->id_profile, $tab_id); if (Validate::isLoadedObject($product)) { if ($tab_access['edit']) { $this->initByProduct($product, false, true); $initialize_from_template = Tools::isSubmit(ProductAuctionTemplate::$definition['primary']); if (!Validate::isLoadedObject($this->product_auction)) { $this->product_auction = new ProductAuction(null, true, $this->context->language->id, $this->context->shop->id); $initialize_from_template = true; } if ($initialize_from_template) $this->product_auction->initializeFromTemplate($this->getProductAuctionTemplate()); $product_auction_create = $this->product_auction->getProductAuctionType()->getProductAuctionCreate(); $product_auction_create->initialize($this); $auctions_helper_form = new CoreModuleHelperForm($this, $product_auction_create); $auctions_helper_form->setTemplate('product-form.tpl'); return $auctions_helper_form->generateFromObject($this->product_auction); } else $this->displayControllerWarning($this->l('You do not have access to edit auction details.')); } else { if (!$tab_access['add']) $this->displayControllerWarning($this->l('You do not have access to add auction details.')); else $this->displayControllerWarning($this->l('You must save this product before adding auction details.')); } } public function hookActionAdminProductsCheckProduct() { if ($this->isTabSubmitted(AbstractProductAuctionCreate::MODULE_TAB_NAME)) { $this->initByProductId((int)Tools::getValue(Product::$definition['primary']), true, true); $this->copyFromPost($this->product_auction); $product_auction_create = $this->product_auction->getProductAuctionType()->getProductAuctionCreate(); $product_auction_create->initialize($this); $product_auction_create->doFieldsValidation($this->product_auction, $this->context->controller->errors); } } public function hookActionObjectProductUpdateBefore($params) { if ($this->isTabSubmitted(AbstractProductAuctionCreate::MODULE_TAB_NAME) && Tools::getValue('enable_auction') == 1) { $product = &$params['object']; $this->initByProduct($product, true, true); $product_auction_create = $this->getProductAuctionTemplate()->getProductAuctionType()->getProductAuctionCreate(); $product_auction_create->initialize($this); $product_auction_create->setProductDefaults($product); } } public function hookActionObjectProductUpdateAfter($params) { if ($this->isTabSubmitted(AbstractProductAuctionCreate::MODULE_TAB_NAME)) { $this->initByProduct($params['object'], true, true); $this->copyFromPost($this->product_auction); $product_auction_create = $this->product_auction->getProductAuctionType()->getProductAuctionCreate(); $product_auction_create->initialize($this); $product_auction_create->doFieldsSave($this->product_auction, $this->context->controller->errors); } } public function hookDisplayHeader() { $this->context->controller->addCSS(array( $this->getPathUri().'css/auctions.css', $this->getPathUri().'css/auctions_side_block.css' ), 'all'); $this->context->controller->addJS(array( $this->getPathUri().'js/countdown/jquery.plugin.min.js', $this->getPathUri().'js/countdown/jquery.countdown.min.js', )); $iso_lang = $this->getContext()->language->iso_code; if (file_exists($this->getLocalPath()."js/countdown/locale/jquery.countdown-{$iso_lang}.js")) $this->context->controller->addJS(array( $this->getPathUri()."js/countdown/locale/jquery.countdown-{$iso_lang}.js", )); $this->context->controller->addJS(array( $this->getPathUri().'js/auctions-functions.js', $this->getPathUri().'js/auctions-init.js', )); if ($this->context->controller instanceof CategoryControllerCore) $this->context->controller->addCSS(array( $this->getPathUri().'css/auctions_list.css' ), 'all'); if ($this->context->controller instanceof ProductControllerCore) $this->context->controller->addCSS(array( $this->getPathUri().'css/auctions_details.css' ), 'all'); } public function hookDisplayRightColumnProduct($params) { $product_auction_item = $this->initAuction($params); if (!$product_auction_item) return; $this->context->smarty->assign(array( 'bids_url' => $this->context->link->getModuleLink('auctions', 'bids', array( 'token' => Tools::getToken(false) )), 'bid_url' => $this->context->link->getModuleLink('auctions', 'bid'), 'buy_url' => $this->context->link->getModuleLink('auctions', 'buy'), 'login_url' => $this->context->link->getPageLink('authentication', true, $this->context->language->id, array( 'back' => $product_auction_item->getProductLink() )) )); return $this->display(__FILE__, 'product-auction-details.tpl'); } public function hookDisplayLeftColumnProduct($params) { if (!$this->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_WATCH_AUCTION)) return; if (!$this->context->customer->isLogged() || !$this->context->customer->id) return; $product_auction_item = $this->initAuction($params); if (!$product_auction_item) return; $params_add = array(); $params_add[ProductAuction::ADD] = 1; $params_remove = array(); $params_remove[ProductAuction::REMOVE] = 1; $is_subscribed = ProductAuctionSubscriptionDataManager::isSubscribed($this->context->customer->id, $product_auction_item->getId()); if ($token = Tools::getToken(false)) { $params_add['token'] = $token; $params_remove['token'] = $token; } $this->context->smarty->assign(array( 'add_link' => $this->context->link->getModuleLink($this->name, 'watch', $params_add), 'remove_link' => $this->context->link->getModuleLink($this->name, 'watch', $params_remove), 'is_watched' => $is_subscribed, 'id_product_auction' => $product_auction_item->getId(), )); return $this->display(__FILE__, 'product-auction-details-subscription.tpl'); } public function hookDisplayProductTab($params) { $auctions_appearance_settings = $this->getSettings('AuctionsAppearanceSettings'); if ($auctions_appearance_settings->getValue(AuctionsAppearanceSettings::DETAILS_SHOW_BIDS_LIST) != AuctionsAppearanceSettings::BID_LIST_TAB) return; if (!$this->initAuction($params)) return; return $this->display(__FILE__, 'product-auction-tab.tpl'); } public function hookDisplayProductTabContent($params) { $auctions_appearance_settings = $this->getSettings('AuctionsAppearanceSettings'); if ($auctions_appearance_settings->getValue(AuctionsAppearanceSettings::DETAILS_SHOW_BIDS_LIST) != AuctionsAppearanceSettings::BID_LIST_TAB) return; $product_auction_item = $this->initAuction($params); if (!$product_auction_item) return; $product_auction = $product_auction_item->getObjectModel(); $product_auction_type = $product_auction->getProductAuctionType(); $pao_status = array( ProductAuctionOffer::STATUS_VALID, ProductAuctionOffer::STATUS_WINNER ); $lang_id = $this->context->language->id; $shop_id = $this->context->shop->id; $pao_collection = ProductAuctionOfferDataManager::getCollectionByProductAuction($product_auction, $pao_status, $lang_id, $shop_id); $pao_items = ProductAuctionOfferItemFactory::getInstance($this)->makeFrontOfficeItems($pao_collection, $product_auction_type); $product_auction_offers = array(); foreach ($pao_items as $pao_item) $product_auction_offers[] = array( 'customer_name' => $pao_item->getCustomerName(), 'customer_name_full' => $pao_item->getCustomerNameFull(), 'customer_bid' => $pao_item->getCustomerBid(), 'date_add' => $pao_item->getOfferDate() ); unset($pao_collection); unset($pao_items); $this->context->smarty->assign(array( 'offers' => $product_auction_offers )); return $this->display(__FILE__, 'product-auction-tab-content.tpl'); } public function hookDisplayRightColumn() { return $this->showColumnBlock(AuctionsBlocksSettings::BLOCK_RIGHT); } public function hookDisplayLeftColumn() { return $this->showColumnBlock(AuctionsBlocksSettings::BLOCK_LEFT); } public function hookDisplayHome() { $auctions_block_settings = $this->getSettings('AuctionsBlocksSettings'); $latest_auctions = null; $ending_auctions = null; $popular_auctions = null; $featured_auctions = null; $page_number = 1; $language_id = $this->context->language->id; if ($auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_LATEST_AUCTIONS_HOME)) { $threshold = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_LATEST_AUCTIONS_TIME); $limit = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_LATEST_AUCTIONS_HOME_COUNT); $latest_auctions = ProductDataManager::getCollectionByAuctionStartingTime($threshold, $language_id, $page_number, $limit, 'from', 'DESC', false); foreach ($latest_auctions as &$latest_auction) { $latest_auction['available_for_order'] = false; $latest_auction['specific_prices'] = null; } } if ($auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_ENDING_AUCTIONS_HOME)) { $threshold = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_ENDING_AUCTIONS_TIME); $limit = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_ENDING_AUCTIONS_HOME_COUNT); $ending_auctions = ProductDataManager::getCollectionByAuctionEndingTime($threshold, $language_id, $page_number, $limit, 'to', 'ASC', false); foreach ($ending_auctions as &$ending_auction) { $ending_auction['available_for_order'] = false; $ending_auction['specific_prices'] = null; } } if ($auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_POPULAR_AUCTIONS_HOME)) { $threshold = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_POPULAR_AUCTIONS_TIME); $limit = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_POPULAR_AUCTIONS_HOME_COUNT); $popular_auctions = ProductDataManager::getCollectionByAuctionPopularity($threshold, $language_id, $page_number, $limit, 'offers', 'DESC', false); foreach ($popular_auctions as &$popular_auction) { $popular_auction['available_for_order'] = false; $popular_auction['specific_prices'] = null; } } if ($auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_FEATURED_AUCTIONS_HOME)) { $category = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_FEATURED_AUCTIONS_CATEGORY); $limit = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_FEATURED_AUCTIONS_HOME_COUNT); $featured_auctions = ProductDataManager::getCollectionByAuctionCategory($category, $language_id, $page_number, $limit, 'to', 'ASC', false); foreach ($featured_auctions as &$featured_auction) { $featured_auction['available_for_order'] = false; $featured_auction['specific_prices'] = null; } } $image_type = CoreModuleTools::getImageTypeFormatedName('home'); $this->context->smarty->assign(array( 'homeAuctions' => array( 'latest' => $latest_auctions, 'ending' => $ending_auctions, 'popular' => $popular_auctions, 'featured' => $featured_auctions ), 'homeLabels' => array( 'latest' => array( 'title' => $this->l('Latest auctions'), 'empty' => $this->l('No latest auctions at this time'), 'all' => $this->l('All latest'), 'more' => $this->l('More'), 'view' => $this->l('View') ), 'ending' => array( 'title' => $this->l('Ending auctions'), 'empty' => $this->l('No ending auctions at this time'), 'all' => $this->l('All ending'), 'more' => $this->l('More'), 'view' => $this->l('View') ), 'popular' => array( 'title' => $this->l('Popular auctions'), 'empty' => $this->l('No popular auctions at this time'), 'all' => $this->l('All popular'), 'more' => $this->l('More'), 'view' => $this->l('View') ), 'featured' => array( 'title' => $this->l('Featured auctions'), 'empty' => $this->l('No featured auctions at this time'), 'all' => $this->l('All featured'), 'more' => $this->l('More'), 'view' => $this->l('View') ) ), 'homeSizeName' => $image_type, 'homeSize' => Image::getSize($image_type) )); return $this->display(__FILE__, 'product-auction-home-block.tpl'); } public function hookDisplayCustomerAccount() { $this->smarty->assign('in_footer', false); return $this->display(__FILE__, 'product-auction-my-account.tpl'); } public function hookDisplayMyAccountBlock() { $this->smarty->assign('in_footer', true); return $this->display(__FILE__, 'product-auction-my-account.tpl'); } public function hookDisplayMyAccountBlockfooter() { $this->smarty->assign('in_footer', true); return $this->display(__FILE__, 'product-auction-my-account.tpl'); } public function hookDisplayProductListFunctionalButtons($params) { if (!$this->initAuction($params)) return; $params_add = array(); $params_add[ProductAuction::ADD] = 1; $params_remove = array(); $params_remove[ProductAuction::REMOVE] = 1; $params_bids = array(); if ($token = Tools::getToken(false)) { $params_add['token'] = $token; $params_remove['token'] = $token; $params_bids['token'] = $token; } $this->context->smarty->assign(array( 'add_link' => $this->context->link->getModuleLink($this->name, 'watch', $params_add), 'remove_link' => $this->context->link->getModuleLink($this->name, 'watch', $params_remove), 'bids_url' => $this->context->link->getModuleLink('auctions', 'bids', $params_bids), )); return $this->display(__FILE__, 'product-auction-list-functional-buttons.tpl'); } public function hookDisplayProductPriceBlock($params) { if ($params['type'] != 'price') return; if (!$this->initAuction($params)) return; return $this->display(__FILE__, 'product-auction-list-price-block.tpl'); } public function hookDisplayProductDeliveryTime($params) { if (!$this->initAuction($params)) return; return $this->display(__FILE__, 'product-auction-list-delivery-time.tpl'); } public function hookActionProductListModifier($params) { $product_auction_loader = ProductAuctionLoader::getInstance($this); foreach ($params['cat_products'] as $product) $product_auction_loader->addProductId($product['id_product']); $product_auction_loader->fetchAuctions(); foreach ($params['cat_products'] as &$product) { $product_id = $product['id_product']; if ($product_auction_loader->hasProductAuctionItem($product_id)) { $product_auction_item = $product_auction_loader->getProductAuctionItem($product_id); $product['specific_prices'] = null; if (!$product_auction_item->canCheckOut($this->context->customer)) $product['available_for_order'] = false; } } } public function hookActionCartSave() { $product_id = (int)Tools::getValue('id_product'); if (($this->context->cart instanceof Cart) && ($product_id > 0)) { $product_auction_item = ProductAuctionLoader::getInstance($this)->getProductAuctionItem($product_id); if (!$product_auction_item) return; $product_attribute_id = (int)Tools::getValue('ipa'); $product_attribute_id = $product_attribute_id > 0 ? (int)$product_attribute_id : null; $customization_id = (int)Tools::getValue('id_customization'); $delivery_address_id = (int)Tools::getValue('id_address_delivery'); $customer_id = (int)$this->context->customer->id; $cart_id = (int)$this->context->cart->id; $shop_id = (int)$this->context->shop->id; $add = Tools::getIsset('add') ? 1 : 0; $delete = Tools::getIsset('delete') ? 1 : 0; if ($add) { $products = $this->context->cart->getProducts(true, $product_id); $in_cart = $this->context->cart->containsProduct($product_id) || count($products); if (!$in_cart) return; $can_checkout = $product_auction_item->canCheckOut($this->context->customer); $can_buy_now = $product_auction_item->canBuyNow($this->context->customer); if ($can_checkout) { SpecificPrice::deleteByIdCart($cart_id, $product_id, $product_attribute_id); Product::flushPriceCache(); } else if ($can_buy_now) { $specific_price = SpecificPrice::getByProductId($product_id, $product_attribute_id, $cart_id); $specific_price_id = !empty($specific_price['id_specific_price']) ? $specific_price['id_specific_price'] : 0; $specific_price = new SpecificPrice($specific_price_id, null, $this->context->shop->id); $specific_price->id_product = $product_id; $specific_price->price = $product_auction_item->getObjectModel()->buynow_price; $specific_price->id_shop = $shop_id; $specific_price->id_product_attribute = $product_attribute_id; $specific_price->id_currency = 0; $specific_price->id_country = 0; $specific_price->id_group = 0; $specific_price->id_customer = $customer_id; $specific_price->id_cart = $cart_id; $specific_price->from_quantity = 1; $specific_price->reduction = 0; $specific_price->reduction_type = 'amount'; $specific_price->from = '0000-00-00 00:00:00'; $specific_price->to = '0000-00-00 00:00:00'; if ($specific_price->save(true)) { Product::flushPriceCache(); // Set cache of feature detachable to true Configuration::updateGlobalValue('PS_SPECIFIC_PRICE_FEATURE_ACTIVE', '1'); } } else { if ($this->context->cart->deleteProduct($product_id, $product_attribute_id, $customization_id, $delivery_address_id)) { if (!Cart::getNbProducts($cart_id)) { $this->context->cart->setDeliveryOption(null); $this->context->cart->gift = 0; $this->context->cart->gift_message = ''; $this->context->cart->update(); } } CartRule::autoAddToCart(); $this->context->controller->errors[] = $this->l('Cannot add this auction to the cart.'); } } if ($delete) SpecificPrice::deleteByIdCart($cart_id, $product_id, $product_attribute_id); } } public function hookActionValidateOrder($params) { $products_to_close_ids = array(); $products_to_finish_ids = array(); foreach ($params['cart']->getProducts() as $product) { $products_to_close_ids[] = (int)$product['id_product']; if ($product['quantity_available'] - $product['cart_quantity'] < 1) $products_to_finish_ids[] = (int)$product['id_product']; } ProductAuctionDataManager::closeProductAuctionsWithProductIds(array_unique($products_to_close_ids)); ProductAuctionDataManager::finishProductAuctionsWithProductIds(array_unique($products_to_finish_ids)); } /* Helpers */ /** * * @param string $tab_name * @return boolean */ public function isTabSubmitted($tab_name) { if (in_array($tab_name, Tools::getValue('submitted_tabs', array()))) return true; return false; } public function displayControllerWarning($message) { $this->context->controller->warnings[] = $message; } public function copyFromPost(ObjectModelCore $object) { $definition = ObjectModel::getDefinition($object); $fields = array_keys($definition['fields']); /* Classical fields */ foreach ($fields as $key) if (key_exists($key, $object) && CoreModuleTools::postIsset($key) && $key != 'id_'.$definition['table']) { $value = Tools::getValue($key); /* Do not take care of password field if empty */ if ($key == 'passwd' && Tools::getValue('id_'.$definition['table']) && empty($value)) continue; /* Automatically encrypt password in MD5 */ if ($key == 'passwd' && !empty($value)) $value = Tools::encrypt($value); $object->{$key} = $value; } /* Multilingual fields */ $rules = call_user_func(array( get_class($object), 'getValidationRules' ), get_class($object)); if (count($rules['validateLang'])) { $languages = Language::getLanguages(false); foreach ($languages as $language) foreach (array_keys($rules['validateLang']) as $field) if (CoreModuleTools::postIsset($field.'_'.(int)$language['id_lang'])) $object->{$field}[(int)$language['id_lang']] = Tools::getValue($field.'_'.(int)$language['id_lang']); } /* Array fields */ foreach ($fields as $field) { $key = "{$field}_array"; if (isset($object->{$key}) && CoreModuleTools::postIsset($key) && $key != 'id_'.$definition['table']) $object->{$key} = Tools::getValue($key); } return $object; } /** * * @param ProductAuctionItem[] $product_auction_item_collection * @return array */ public function convertProductAuctionItemCollectionToArray(array $product_auction_item_collection, $type, $full = false) { $product_auction_items = array(); if (!empty($product_auction_item_collection)) foreach ($product_auction_item_collection as $product_auction_item) $product_auction_items[] = $this->convertProductAuctionItemToArray($product_auction_item, $type, $full); return $product_auction_items; } /** * * @param AbstractProductAuctionItem $product_auction_item * @param integer $type * @param string $full * @return array */ public function convertProductAuctionItemToArray(AbstractProductAuctionItem $product_auction_item, $type, $full = false) { $auction_data = $this->prepareProductAuctionItemData($product_auction_item, $type); if ($full) $auction_data['product'] = $this->prepareProductItemData($product_auction_item); return $auction_data; } /* Additional */ protected function showColumnBlock($side) { $auctions_block_settings = $this->getSettings('AuctionsBlocksSettings'); $latest_auctions = null; $ending_auctions = null; $popular_auctions = null; $featured_auctions = null; $lang_id = $this->context->language->id; $shop_id = $this->context->shop->id; $type = AbstractProductAuctionPermissions::TYPE_SIDE; if ($side == $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_LATEST_AUCTIONS_SIDE)) { $threshold = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_LATEST_AUCTIONS_TIME); $limit = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_LATEST_AUCTIONS_SIDE_COUNT); $latest_auctions_collection = ProductAuctionDataManager::getCollectionByStartingTime($threshold, $limit, $lang_id, $shop_id); $latest_auctions_item = ProductAuctionItemFactory::getInstance($this)->makeFrontOfficeItems($latest_auctions_collection); $latest_auctions = $this->convertProductAuctionItemCollectionToArray($latest_auctions_item, $type, true); } if ($side == $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_ENDING_AUCTIONS_SIDE)) { $threshold = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_ENDING_AUCTIONS_TIME); $limit = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_ENDING_AUCTIONS_SIDE_COUNT); $ending_auctions_collection = ProductAuctionDataManager::getCollectionByEndingTime($threshold, $limit, $lang_id, $shop_id); $ending_auctions_item = ProductAuctionItemFactory::getInstance($this)->makeFrontOfficeItems($ending_auctions_collection); $ending_auctions = $this->convertProductAuctionItemCollectionToArray($ending_auctions_item, $type, true); } if ($side == $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_POPULAR_AUCTIONS_SIDE)) { $threshold = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_POPULAR_AUCTIONS_TIME); $limit = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT); $popular_auctions_collection = ProductAuctionDataManager::getCollectionByPopularity($threshold, $limit, $lang_id, $shop_id); $popular_auctions_item = ProductAuctionItemFactory::getInstance($this)->makeFrontOfficeItems($popular_auctions_collection); $popular_auctions = $this->convertProductAuctionItemCollectionToArray($popular_auctions_item, $type, true); } if ($side == $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_FEATURED_AUCTIONS_SIDE)) { $category = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_FEATURED_AUCTIONS_CATEGORY); $limit = $auctions_block_settings->getValue(AuctionsBlocksSettings::BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT); $featured_auctions_collection = ProductAuctionDataManager::getCollectionByCategory($category, $limit, $lang_id, $shop_id); $featured_auctions_item = ProductAuctionItemFactory::getInstance($this)->makeFrontOfficeItems($featured_auctions_collection); $featured_auctions = $this->convertProductAuctionItemCollectionToArray($featured_auctions_item, $type, true); } $image_type = CoreModuleTools::getImageTypeFormatedName('small'); $this->context->smarty->assign(array( 'blockAuctions' => array( 'latest' => $latest_auctions, 'ending' => $ending_auctions, 'popular' => $popular_auctions, 'featured' => $featured_auctions ), 'blockLabels' => array( 'latest' => array( 'title' => $this->l('Latest auctions'), 'empty' => $this->l('No latest auctions at this time'), 'all' => $this->l('All latest') ), 'ending' => array( 'title' => $this->l('Ending auctions'), 'empty' => $this->l('No ending auctions at this time'), 'all' => $this->l('All ending') ), 'popular' => array( 'title' => $this->l('Popular auctions'), 'empty' => $this->l('No popular auctions at this time'), 'all' => $this->l('All popular') ), 'featured' => array( 'title' => $this->l('Featured auctions'), 'empty' => $this->l('No featured auctions at this time'), 'all' => $this->l('All featured') ) ), 'smallSizeName' => $image_type, 'smallSize' => Image::getSize($image_type), 'bids_url' => $this->context->link->getModuleLink('auctions', 'bids', array( 'token' => Tools::getToken(false) )) )); return $this->display(__FILE__, 'product-auction-side-block.tpl'); } /** * * @param AbstractProductAuctionItem $product_auction_item * @return array */ protected function prepareProductItemData(AbstractProductAuctionItem $product_auction_item) { return array( 'link' => $product_auction_item->getProductLink(), 'link_rewrite' => $product_auction_item->getProductLinkRewrite(), 'name' => $product_auction_item->getProductName(), 'short_description' => $product_auction_item->getProductShortDescription(), 'cover' => $product_auction_item->getProductCoverImage($this->getLanguageId()) ); } /** * * @param AbstractProductAuctionItem $product_auction_item * @return array */ protected function prepareProductAuctionItemData(AbstractProductAuctionItem $product_auction_item, $type) { $full_data_in = array( AbstractProductAuctionPermissions::TYPE_DETAILS, AbstractProductAuctionPermissions::TYPE_ADMIN, AbstractProductAuctionPermissions::TYPE_MY_AUCTIONS, ); return array( 'permissions' => array( 'show_current_price' => $product_auction_item->getPermissions($type)->showCurrentPrice(), 'show_start_time' => $product_auction_item->getPermissions($type)->showStartTime(), 'show_close_time' => $product_auction_item->getPermissions($type)->showCloseTime(), 'show_duration' => $product_auction_item->getPermissions($type)->showDuration(), 'show_bids' => $product_auction_item->getPermissions($type)->showBids(), 'show_bids_list' => $product_auction_item->getPermissions($type)->showBidsList(), 'show_winner' => $product_auction_item->getPermissions($type)->showWinner(), 'show_starting_price' => $product_auction_item->getPermissions($type)->showStartingPrice(), 'show_countdown' => $product_auction_item->getPermissions($type)->showCountdown() ), 'id_product_auction' => $product_auction_item->getId(), 'id_product' => $product_auction_item->getProductId(), 'current_price' => $product_auction_item->getCurrentPrice(), 'initial_price' => $product_auction_item->getInitialPrice(), 'buynow_price' => $product_auction_item->getBuyNowPrice(), 'minimal_price' => $product_auction_item->getMinimalPrice(), 'my_price' => $product_auction_item->getCustomerHighestPrice(), 'bid_price' => $product_auction_item->getBidPrice(), 'start_date' => $product_auction_item->getStartDate(), 'end_date' => $product_auction_item->getEndDate(), 'duration' => $product_auction_item->getDuration(), 'time_to_start' => $product_auction_item->getTimeToStart(), 'time_to_finish' => $product_auction_item->getTimeToFinish(), 'status' => array( 'is_started' => $product_auction_item->isStarted(), 'is_finished' => $product_auction_item->isFinished(), 'is_processed' => $product_auction_item->isProcessed(), 'is_checked_out' => $product_auction_item->isCheckedOut(), 'can_bid' => in_array($type, $full_data_in) ? $product_auction_item->canBid($this->context->customer) : null, 'can_checkout' => in_array($type, $full_data_in) ? $product_auction_item->canCheckOut($this->context->customer) : null, 'id' => $product_auction_item->getStatus(), 'name' => $product_auction_item->getStatusName($this) ), 'reserve' => array( 'has_reserve' => $product_auction_item->hasMinimalPrice(), 'reached' => $product_auction_item->isMinimalPriceReached() ), 'buynow' => array( 'after_bid' => in_array($type, $full_data_in) ? $product_auction_item->isBuyNowAfterBid() : null, 'can_buynow' => in_array($type, $full_data_in) ? $product_auction_item->canBuyNow($this->context->customer) : null, ), 'offers' => array( 'has_offers' => $product_auction_item->hasOffers(), 'has_winner' => $product_auction_item->hasWinner(), 'count' => $product_auction_item->getOffersCount(), 'winner' => array( 'id' => $product_auction_item->getWinnerId(), 'name' => $product_auction_item->getWinnerName(), 'name_full' => $product_auction_item->getWinnerNameFull(), 'status' => $product_auction_item->getWinnerStatus() ), 'my' => array( 'status' => in_array($type, $full_data_in) ? $product_auction_item->getCustomerHighestOfferStatus() : null, ) ), 'countdown' => array( 'type' => $product_auction_item->getPermissions($type)->showCountdown(), 'format' => $product_auction_item->getPermissions($type)->getCounterFormat(), 'start' => array( 'value' => $product_auction_item->getTimeToStart(true), 'timestamp' => $product_auction_item->getStartTimestamp(), 'label' => $this->l('Not started') ), 'finish' => array( 'threshold' => 600, 'value' => $product_auction_item->getTimeToFinish(true), 'timestamp' => $product_auction_item->getEndTimestamp(), 'label' => $this->l('Finished') ) ) ); } /** * * @return ProductAuctionTemplate */ protected function getProductAuctionTemplate() { $product_auction_template_id = (int)Tools::getValue(ProductAuctionTemplate::$definition['primary'], null); $lang_id = $this->context->language->id; $shop_id = $this->context->shop->id; if ($product_auction_template_id > 0) $product_auction_template = ProductAuctionTemplateDataManager::getById($product_auction_template_id, $lang_id, $shop_id); else if ($product_auction_template_id == -1) $product_auction_template = new ProductAuctionTemplate(); else { $product_auction_template = ProductAuctionTemplateDataManager::getLatestDefault($lang_id, $shop_id); $_POST['id_product_auction_template'] = $product_auction_template->id; } return $product_auction_template; } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcontactinfos}touchmenot1.0.3>blockcontactinfos_02d4482d332e1aef3437cd61c9bcc624'] = 'Contactez-nous'; $_MODULE['<{blockcontactinfos}touchmenot1.0.3>blockcontactinfos_d0398e90769ea6ed2823a3857bcc19ea'] = 'Tel:'; $_MODULE['<{blockcontactinfos}touchmenot1.0.3>blockcontactinfos_6a1e265f92087bb6dd18194833fe946b'] = 'Email:'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionMailingRecipientEnglish', false)) return; class ProductAuctionMailingRecipientEnglish extends AbstractProductAuctionMailingRecipient { /** * * @param ProductAuctionEventBid $event */ public function onProductAuctionBidPlaced(ProductAuctionEventBid $event) { $product_auction_bid_result = $event->product_auction_bid_result; $product_auction = $product_auction_bid_result->getProductAuction(); switch ($product_auction_bid_result->getResult()) { case AbstractProductAuctionBidResult::LEADER: case AbstractProductAuctionBidResult::LEADER_MIN_NOT_REACHED: if ($this->isParticipant()) if ($this->getCustomerId() == $product_auction_bid_result->getCurrentProductAuctionOffer()->id_customer) if ($this->getSetting(AuctionsMailingSettings::AUCTION_CUSTOMER_LEAD)) $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_LEAD, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_LEADER, $product_auction, $this); else $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_OFFER, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NEW_OFFER, $product_auction, $this); else if ($this->getCustomerId() == $product_auction_bid_result->getPreviousProductAuctionOffer()->id_customer) if ($this->getSetting(AuctionsMailingSettings::AUCTION_CUSTOMER_OUTBID)) $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_OUTBID, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_OUTBID, $product_auction, $this); else $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_OFFER, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NEW_OFFER, $product_auction, $this); else $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_OFFER, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NEW_OFFER, $product_auction, $this); if ($this->isSubscriber()) $this->addRecord(AuctionsMailingSettings::AUCTION_SUBSCRIBER_OFFER, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NEW_OFFER, $product_auction, $this); if ($this->isEmployee()) $this->addRecord(AuctionsMailingSettings::AUCTION_BACKOFFICE_OFFER, ProductAuctionMailing::TEMPLATE_BACKOFFICE_NEW_OFFER, $product_auction, $this); break; case AbstractProductAuctionBidResult::VALID_TOO_LOW: case AbstractProductAuctionBidResult::VALID_ALREADY_EXIST: if ($this->isParticipant()) if ($this->getCustomerId() == $product_auction_bid_result->getCustomer()->id) $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_OFFER, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NEW_OFFER, $product_auction, $this); if ($this->isEmployee()) $this->addRecord(AuctionsMailingSettings::AUCTION_BACKOFFICE_OFFER, ProductAuctionMailing::TEMPLATE_BACKOFFICE_NEW_OFFER, $product_auction, $this); break; } } /** * * @param ProductAuctionEventFinish $event */ public function onProductAuctionFinished(ProductAuctionEventFinish $event) { $product_auction = $event->product_auction; if ($this->isParticipant()) { $product_auction_offer = $product_auction->getProductAuctionOffer(); if ($product_auction_offer && $product_auction_offer->status == ProductAuctionOffer::STATUS_WINNER) if ($this->getCustomerId() == $product_auction_offer->id_customer) if ($this->getSetting(AuctionsMailingSettings::AUCTION_CUSTOMER_WON)) $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_WON, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_WON, $product_auction, $this); else $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_FINISHED, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_FINISHED, $product_auction, $this); else if ($this->getSetting(AuctionsMailingSettings::AUCTION_CUSTOMER_NOT_WON)) $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_NOT_WON, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NOT_WON, $product_auction, $this); else $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_FINISHED, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_FINISHED, $product_auction, $this); else $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_FINISHED, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_FINISHED, $product_auction, $this); } if ($this->isSubscriber()) $this->addRecord(AuctionsMailingSettings::AUCTION_SUBSCRIBER_FINISHED, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_FINISHED, $product_auction, $this); if ($this->isEmployee()) $this->addRecord(AuctionsMailingSettings::AUCTION_BACKOFFICE_FINISHED, ProductAuctionMailing::TEMPLATE_BACKOFFICE_FINISHED, $product_auction, $this); } /** * * @param ProductAuctionEventAcceptWinner $event */ public function onProductAuctionAccept(ProductAuctionEventAcceptWinner $event) { $product_auction = $event->product_auction; if ($this->isParticipant()) if ($product_auction->getProductAuctionOffer() && $this->getCustomerId() == $product_auction->getProductAuctionOffer()->id_customer) $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_ACCEPT, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_ACCEPT, $product_auction, $this); } /** * * @param ProductAuctionEventRestart $event */ public function onProductAuctionRestart(ProductAuctionEventRestart $event) { $product_auction = $event->product_auction; if ($this->isParticipant()) $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_RESTART, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_RESTART, $product_auction, $this); if ($this->isSubscriber()) $this->addRecord(AuctionsMailingSettings::AUCTION_SUBSCRIBER_RESTART, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_RESTART, $product_auction, $this); } /** * * @param ProductAuctionEventRemind $event */ public function onProductAuctionRemind(ProductAuctionEventRemind $event) { $product_auction = $event->product_auction; if ($this->isParticipant()) if ($product_auction->getProductAuctionOffer() && $this->getCustomerId() == $product_auction->getProductAuctionOffer()->id_customer) $this->addRecord(AuctionsMailingSettings::AUCTION_CUSTOMER_REMIND, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_REMIND, $product_auction, $this); } /** * * @param ProductAuctionEventReject $event */ public function onProductAuctionReject(ProductAuctionEventReject $event) { } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionMailing', false)) return; class ProductAuctionMailing extends ProductAuctionObjectModel { const STATUS_NOT_SENT = 1; const STATUS_SENT = 2; const TEMPLATE_FRONTOFFICE_NEW_OFFER = 1; const TEMPLATE_FRONTOFFICE_LEADER = 2; const TEMPLATE_FRONTOFFICE_OUTBID = 3; const TEMPLATE_FRONTOFFICE_FINISHED = 4; const TEMPLATE_FRONTOFFICE_WON = 5; const TEMPLATE_FRONTOFFICE_NOT_WON = 6; const TEMPLATE_FRONTOFFICE_ACCEPT = 7; const TEMPLATE_FRONTOFFICE_REMIND = 8; const TEMPLATE_FRONTOFFICE_RESTART = 9; const TEMPLATE_BACKOFFICE_NEW_OFFER = 10; const TEMPLATE_BACKOFFICE_FINISHED = 11; /** * @var integer ProductAuctionMailing id_product_auction_mailing */ public $id_product_auction_mailing; /** * @var integer ProductAuctionMailing id_product_auction */ public $id_product_auction; /** * @var integer ProductAuctionType id */ public $id_product_auction_type; /** * @var integer ProductAuctionMailing id */ public $id_product; /** * @var integer ProductAuctionMailing id */ public $id_customer; /** * @var integer ProductAuctionMailing id */ public $id_employee; /** * @var integer ProductAuctionMailing id */ public $id_lang; /** * @var integer ProductAuctionMailing id */ public $id_shop; /** * @var integer ProductAuctionMailing id */ public $id_cart; /** * @var integer ProductAuctionMailing id */ public $id_currency; /** * @var integer ProductAuctionMailing id */ public $id_process; /** * @var integer ProductAuctionMailing id */ public $sent_at; /** * @var integer ProductAuctionMailing id */ public $send_at; /** * @var integer ProductAuctionMailing id */ public $send_error; /** * @var integer ProductAuctionMailing id */ public $data_current_price; /** * @var integer ProductAuctionMailing id */ public $data_initial_price; /** * @var integer ProductAuctionMailing id */ public $data_minimal_price; /** * @var integer ProductAuctionMailing id */ public $data_buynow_price; /** * @var boolean ProductAuction show buy now price after any offer was placed */ public $data_buynow_after_bid; /** * @var boolean ProductAuction show buy now price */ public $data_buynow_visible; /** * @var string Bidding increment rules */ public $data_bidding_increment; /** * @var boolean Auction proxy biddind */ public $data_proxy_bidding; /** * @var string Auction extend time threshold */ public $data_extend_threshold; /** * @var string Auction extend time step */ public $data_extend_by; /** * @var integer ProductAuctionMailing id */ public $data_from; /** * @var integer ProductAuctionMailing id */ public $data_to; /** * @var integer ProductAuctionMailing data_offers */ public $data_offers; /** * @var integer ProductAuctionMailing data_offers */ public $data_status; /** * @var integer ProductAuctionMailing data_winner_id_customer */ public $data_winner_id_customer; /** * @var integer ProductAuctionMailing data_winner_id_customer */ public $data_winner_price; /** * @var integer ProductAuctionMailing data_winner_id_customer */ public $data_winner_status; /** * @var string ProductAuctionMailing sender_email */ public $sender_email; /** * @var string ProductAuctionMailing sender_name */ public $sender_name; /** * @var string ProductAuctionMailing recipient_email */ public $recipient_email; /** * @var string ProductAuctionMailing recipient_name */ public $recipient_name; /** * @var boolean ProductAuctionMailing status */ public $template; /** * @var string ProductAuctionMailing creation date */ public $date_add; /** * @var string ProductAuctionMailing last modification date */ public $date_upd; /** * * @var ProductAuction */ public $product_auction; /** * * @var Product */ public $product; /** * * @var Customer */ public $winner; /** * * @var Customer */ public $customer; /** * * @var Employee */ public $employee; /** * * @var Language */ public $language; /** * * @var Shop */ public $shop; /** * * @var Cart */ public $cart; /** * * @var Currency */ public $currency; public static $definition = array( 'table' => 'product_auction_mailing', 'primary' => 'id_product_auction_mailing', 'multilang' => false, 'multilang_shop' => false, 'fields' => array( 'id_product_auction' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true ), 'id_product_auction_type' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true ), 'id_product' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true ), 'id_customer' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isUnsignedId' ), 'id_employee' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isUnsignedId' ), 'id_lang' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true ), 'id_shop' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true ), 'id_cart' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isUnsignedId' ), 'id_currency' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isUnsignedId' ), 'id_process' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isMd5', 'size' => 32 ), 'sent_at' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isUnsignedId' ), 'send_at' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isUnsignedId' ), 'send_error' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isString' ), 'send_ignore' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isInt' ), 'data_current_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'data_initial_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'data_minimal_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'data_buynow_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'data_buynow_after_bid' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'data_buynow_visible' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'data_bidding_increment' => array( 'type' => self::TYPE_STRING, 'validate' => 'isString' ), 'data_proxy_bidding' => array( 'type' => self::TYPE_BOOL, 'validate' => 'isBool' ), 'data_extend_threshold' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'data_extend_by' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'data_from' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ), 'data_to' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ), 'data_offers' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'data_status' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'data_winner_id_customer' => array( 'type' => self::TYPE_NOTHING, 'validate' => 'isUnsignedId' ), 'data_winner_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'data_winner_status' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'sender_email' => array( 'type' => self::TYPE_STRING, 'validate' => 'isEmail', 'required' => true, 'size' => 128 ), 'sender_name' => array( 'type' => self::TYPE_STRING, 'validate' => 'isMailName', 'required' => true, 'size' => 255 ), 'recipient_email' => array( 'type' => self::TYPE_STRING, 'validate' => 'isEmail', 'required' => true, 'size' => 128 ), 'recipient_name' => array( 'type' => self::TYPE_STRING, 'validate' => 'isMailName', 'required' => true, 'size' => 255 ), 'template' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt', 'required' => true ), 'date_add' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ), 'date_upd' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ) ) ); } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_12641546686fe11aaeb3b3c43a18c1b3'] = 'Tu Carrito de Compras'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_7fc68677a16caa0f02826182468617e6'] = 'Carrito:'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_f5bf48aa40cad7891eb709fcf1fde128'] = 'producto'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_86024cad1e83101d97359d7351051156'] = 'productos'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(Vacío)'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_a0623b78a5f2cfe415d9dbbd4428ea40'] = 'Su cuenta'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_83218ac34c1834c26781fe4bde918ee4'] = 'Bienvenido'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4b877ba8588b19f1b278510bf2b57ebb'] = 'Cerrar mi sesión'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_4394c8d8e63c470de62ced3ae85de5ae'] = 'Finalizar la sesión'; $_MODULE['<{blockuserinfo}touchmenot1.0.3>blockuserinfo_bffe9a3c9a7e00ba00a11749e022d911'] = 'Iniciar la sesión'; <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_2377be3c2ad9b435ba277a73f0f1ca76'] = 'Produttori'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_49fa2426b7903b3d4c89e2c1874d9346'] = 'Maggiori informazioni su'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_bf24faeb13210b5a703f3ccef792b000'] = 'Tutti i produttori'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_1c407c118b89fa6feaae6b0af5fc0970'] = 'Nessun produttore'; <file_sep><?php define('_MEDIA_SERVER_1_', ''); define('_MEDIA_SERVER_2_', ''); define('_MEDIA_SERVER_3_', ''); define('_PS_CACHING_SYSTEM_', 'CacheFs'); define('_PS_CACHE_ENABLED_', '0'); define('_DB_NAME_', 'f11smith_pres963'); define('_MYSQL_ENGINE_', 'InnoDB'); define('_DB_SERVER_', 'localhost'); define('_DB_USER_', 'f11smith_pres963'); define('_DB_PREFIX_', 'dv1_'); define('_DB_PASSWD_', <PASSWORD>#'); define('_COOKIE_KEY_', '<KEY>'); define('_COOKIE_IV_', 'ezuet9om'); define('_PS_CREATION_DATE_', '2014-03-23'); define('_RIJNDAEL_KEY_', '<KEY>'); define('_RIJNDAEL_IV_', 'Rd6cWUlKrx2vvhX34wlcxg=='); define('_PS_VERSION_', '1.6.0.5'); <file_sep><?php /** * An Ad description */ class AdResult { protected $adName = ""; protected $pictureUrl = ""; protected $clickUrl = ""; protected $clickId = ""; protected $properties = array(); /** * Returns the ad name, primarily intended for debugging purpose * @return string */ public function getAdName() { return $this->adName; } public function setAdName($adName) { $this->adName = $adName; } /** * The URL of the picture * @return string */ public function getPictureUrl() { return $this->pictureUrl; } public function setPictureUrl($pictureUrl) { $this->pictureUrl = $pictureUrl; } /** * The url linked by this ad * @return string */ public function getClickUrl() { return $this->clickUrl; } public function setClickUrl($clickUrl) { $this->clickUrl = $clickUrl; } public function setClickId($clickId) { $this->clickId = $clickId; } /** * This ad identifier * @return string */ public function getClickId() { return $this->clickId; } /** * Key value pairs of user defined properties * @return array an associative array */ public function getProperties() { return $this->properties; } public function addProperty($key, $value) { return $this->properties[$key] = $value; } } <file_sep>SET foreign_key_checks = 0; DROP TABLE IF EXISTS `PREFIX_product_auction_archive_lang`, `PREFIX_product_auction_archive`, `PREFIX_product_auction_mailing`, `PREFIX_product_auction_subscriptions`, `PREFIX_product_auction_template_lang`, `PREFIX_product_auction_template`, `PREFIX_product_auction_offer`, `PREFIX_product_auction`; SET foreign_key_checks = 1; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (!class_exists('CoreModuleHelperForm', false)) { class CoreModuleHelperForm extends HelperForm { /** * * @var CoreModuleHelperFormDataModelInterface */ protected $data_model; public function __construct(Module $module, CoreModuleHelperFormDataModelInterface $data_model) { $this->module = $module; $this->data_model = $data_model; $this->data_model->initialize($module); parent::__construct(); $this->setHelperDisplay(); } protected function setHelperDisplay() { $cookie = $this->context->cookie; $controller = $this->context->controller; $this->token = $controller->token; $this->allow_employee_form_lang = (int)Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG'); if ($this->allow_employee_form_lang && !$cookie->employee_form_lang) $cookie->employee_form_lang = (int)Configuration::get('PS_LANG_DEFAULT'); $lang_exists = false; $this->languages = Language::getLanguages(false); foreach ($this->languages as $lang) if (isset($cookie->employee_form_lang) && $cookie->employee_form_lang == $lang['id_lang']) $lang_exists = true; $this->default_form_language = $lang_exists ? (int)$cookie->employee_form_lang : (int)Configuration::get('PS_LANG_DEFAULT'); foreach ($this->languages as $k => $language) $this->languages[$k]['is_default'] = (int)$language['id_lang'] == $this->default_form_language; $this->tpl_vars['show_hints'] = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::SHOW_FORM_HINTS); } public function setTemplate($template, $folder = 'helpers/form/') { $this->base_folder = $folder; $this->base_tpl = $template; } public function generateFromObject(ObjectModelCore $object) { $this->fields_form = $this->data_model->getFieldsForm(); $this->fields_value = $this->data_model->getFieldsValues($object); return $this->generate(); } public static function copyArraysFromPost(&$object, $table) { Tools::safePostVars(); /* Array fields */ foreach ($_POST as $key => $value) if (isset($object->{$key}) && $key != 'id_'.$table) $object->{$key} = $value; } } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsConfirmModuleFrontController', false)) return; class AuctionsConfirmModuleFrontController extends CoreModuleController { public function process() { // Check page token if (!$this->isTokenValid()) die(Tools::displayError('Invalid token.')); parent::process(); if (empty($this->errors)) { $product_auction_ids = (array)Tools::getValue('products', array()); $checkout_all = (boolean)Tools::isSubmit('confirmAll'); $customer = $this->context->customer; $cart = $this->context->cart; $cookie = $this->context->cookie; if (!isset($cart->id) || !$cart->id) { $cart->add(true); if ($cart->id) $cookie->id_cart = (int)$cart->id; } if ($this->context->customer->isLogged() && $this->context->customer->id > 0) { $product_auction_items = $this->getProductAuctionItems($product_auction_ids, $checkout_all); foreach ($product_auction_items as $product_auction_item) if ($product_auction_item->canCheckOut($customer)) $cart->updateQty(1, $product_auction_item->getProductId(), $product_auction_item->getProduct()->getDefaultIdProductAttribute()); Tools::redirect('order.php?back='.urlencode('modules/auctions/myauctions.php')); } } } /** * * @param array $product_auction_ids * @param string $checkout_all * @return AbstractProductAuctionItem[] */ public function getProductAuctionItems(array $product_auction_ids, $checkout_all = false) { $product_auctions_collection = ProductAuctionDataManager::getWonAuctionsCollectionByCustomer($this->context->customer->id, null, null, $this->context->language->id, $this->context->shop->id); $output_product_auction_collection = array(); if (!$checkout_all) { if (empty($product_auction_ids)) return array(); foreach ($product_auctions_collection as $product_auction) if (in_array($product_auction->id, $product_auction_ids)) $output_product_auction_collection[] = $product_auction; } else $output_product_auction_collection = $product_auctions_collection; return ProductAuctionItemFactory::getInstance($this->module)->makeFrontOfficeItems($output_product_auction_collection); } } <file_sep>SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; CREATE TABLE IF NOT EXISTS `PREFIX_product_auction_template` ( `id_product_auction_template` int(10) unsigned NOT null AUTO_INCREMENT, `id_product_auction_type` int(10) unsigned NOT null, `enable_auction` tinyint(1) unsigned NOT null DEFAULT 0, `initial_price` decimal(20,6) null, `minimal_price` decimal(20,6) null, `buynow_price` decimal(20,6) null, `buynow_after_bid` tinyint(1) unsigned NOT null DEFAULT 1, `buynow_visible` tinyint(1) unsigned NOT null DEFAULT 0, `bidding_increment` TEXT null, `proxy_bidding` tinyint(1) unsigned NOT null DEFAULT 1, `extend_threshold` int(10) unsigned NOT null DEFAULT 0, `extend_by` int(10) unsigned NOT null DEFAULT 0, `from_fixed` datetime null, `to_fixed` datetime null, `from_offset` int(10) null, `to_offset` int(10) null, `default` tinyint(1) unsigned NOT null DEFAULT 0, `active` tinyint(1) unsigned NOT null DEFAULT 1, `date_add` datetime NOT null, `date_upd` datetime NOT null, PRIMARY KEY (`id_product_auction_template`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `PREFIX_product_auction_template_lang` ( `id_product_auction_template` int(10) unsigned NOT null, `id_lang` int(10) unsigned NOT null, `name` text, PRIMARY KEY (`id_product_auction_template`,`id_lang`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `PREFIX_product_auction` ( `id_product_auction` int(10) unsigned NOT null AUTO_INCREMENT, `id_product_auction_type` int(10) unsigned NOT null, `id_product_auction_offer` int(10) unsigned null, `id_specific_price` int(10) unsigned null, `id_product` int(10) unsigned NOT null, `initial_price` decimal(20,6) NOT null, `minimal_price` decimal(20,6) NOT null, `buynow_price` decimal(20,6) NOT null, `buynow_after_bid` tinyint(1) unsigned NOT null DEFAULT 1, `buynow_visible` tinyint(1) unsigned NOT null DEFAULT 1, `bidding_increment` text, `proxy_bidding` tinyint(1) unsigned NOT null DEFAULT 1, `extend_threshold` int(10) unsigned NOT null DEFAULT 0, `extend_by` int(10) unsigned NOT null DEFAULT 0, `from` datetime NOT null, `to` datetime NOT null, `offers` int(10) unsigned NOT null DEFAULT 0, `status` tinyint(2) unsigned NOT null, `enable_auction` tinyint(1) unsigned NOT null, `date_add` datetime NOT null, `date_upd` datetime NOT null, PRIMARY KEY (`id_product_auction`), KEY `idx_product_auction_status` (`status`), KEY `idx_product_auction_from` (`from`), KEY `idx_product_auction_to` (`to`), KEY `fk_PREFIX_product_auction_specific_price` (`id_specific_price`), UNIQUE KEY `fk_PREFIX_product_auction_product` (`id_product`), CONSTRAINT `fk_PREFIX_product_auction_product` FOREIGN KEY (`id_product`) REFERENCES `PREFIX_product` (`id_product`) ON DELETE CASCADE, CONSTRAINT `fk_PREFIX_product_auction_specific_price` FOREIGN KEY (`id_specific_price`) REFERENCES `PREFIX_specific_price` (`id_specific_price`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `PREFIX_product_auction_offer` ( `id_product_auction_offer` int(10) unsigned NOT null AUTO_INCREMENT, `id_product_auction` int(10) unsigned NOT null, `id_customer` int(10) unsigned NOT null, `customer_price` decimal(20,6) unsigned NOT null, `previous_price` decimal(20,6) unsigned NOT null, `status` tinyint(2) unsigned NOT null, `date_add` datetime NOT null, `date_upd` datetime NOT null, PRIMARY KEY (`id_product_auction_offer`), KEY `idx_product_auction_offer_customer_price` (`customer_price`), KEY `idx_product_auction_offer_previous_price` (`previous_price`), KEY `idx_product_auction_offer_status` (`status`), KEY `fk_PREFIX_product_auction_offer_product_auction` (`id_product_auction`), KEY `fk_PREFIX_product_auction_offer_customer` (`id_customer`), CONSTRAINT `fk_PREFIX_product_auction_offer_product_auction` FOREIGN KEY (`id_product_auction`) REFERENCES `PREFIX_product_auction` (`id_product_auction`) ON DELETE CASCADE, CONSTRAINT `fk_PREFIX_product_auction_offer_customer` FOREIGN KEY (`id_customer`) REFERENCES `PREFIX_customer` (`id_customer`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `PREFIX_product_auction_subscriptions` ( `id_product_auction` int(10) unsigned NOT null, `id_customer` int(10) unsigned NOT null, `date_add` datetime NOT null, `date_upd` datetime NOT null, PRIMARY KEY (`id_product_auction`,`id_customer`), KEY `fk_PREFIX_product_auction_subscriptions_product_auction` (`id_product_auction`), KEY `fk_PREFIX_product_auction_subscriptions_customer` (`id_customer`), CONSTRAINT `fk_PREFIX_product_auction_subscriptions_product_auction` FOREIGN KEY (`id_product_auction`) REFERENCES `PREFIX_product_auction` (`id_product_auction`) ON DELETE CASCADE, CONSTRAINT `fk_PREFIX_product_auction_subscriptions_customer` FOREIGN KEY (`id_customer`) REFERENCES `PREFIX_customer` (`id_customer`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `PREFIX_product_auction_archive` ( `id_product_auction_archive` int(10) unsigned NOT null AUTO_INCREMENT, `id_product` int(10) unsigned NOT null, `initial_price` decimal(20,6) NOT null, `buynow_price` decimal(20,6) NOT null, `minimal_price` decimal(20,6) NOT null, `final_price` decimal(20,6) DEFAULT null, `firstname` varchar(32) DEFAULT null, `lastname` varchar(32) DEFAULT null, `email` varchar(128) DEFAULT null, `offers` int(10) NOT null, `bid_step` decimal(20,6) unsigned NOT null, `from` datetime NOT null, `to` datetime NOT null, `status` tinyint(2) unsigned NOT null, `date_add` datetime NOT null, `date_upd` datetime NOT null, PRIMARY KEY (`id_product_auction_archive`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `PREFIX_product_auction_archive_lang` ( `id_product_auction_archive` int(10) unsigned NOT null, `id_lang` int(10) unsigned NOT null, `name` text, PRIMARY KEY (`id_product_auction_archive`,`id_lang`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `PREFIX_product_auction_mailing` ( `id_product_auction_mailing` int(10) unsigned NOT null AUTO_INCREMENT, `id_product_auction` int(10) unsigned null, `id_product_auction_type` int(10) unsigned NOT null, `id_product` int(10) unsigned null, `id_customer` int(10) unsigned null, `id_employee` int(10) unsigned null, `id_lang` int(10) unsigned null, `id_shop` int(10) unsigned null, `id_cart` int(10) unsigned null, `id_currency` int(10) unsigned null, `id_process` varchar(32) null, `sent_at` int(10) unsigned DEFAULT null, `send_at` int(10) unsigned DEFAULT null, `send_error` varchar(255) DEFAULT null, `send_ignore` varchar(255) DEFAULT null, `sender_email` varchar(128) DEFAULT null, `sender_name` varchar(255) DEFAULT null, `recipient_email` varchar(128) DEFAULT null, `recipient_name` varchar(255) DEFAULT null, `template` tinyint(1) unsigned DEFAULT null, `data_current_price` decimal(20,6) DEFAULT null, `data_initial_price` decimal(20,6) DEFAULT null, `data_minimal_price` decimal(20,6) DEFAULT null, `data_buynow_price` decimal(20,6) DEFAULT null, `data_buynow_after_bid` tinyint(1) unsigned DEFAULT null, `data_buynow_visible` tinyint(1) unsigned DEFAULT null, `data_bidding_increment` text DEFAULT null, `data_proxy_bidding` tinyint(1) unsigned DEFAULT null, `data_extend_threshold` int(10) unsigned DEFAULT null, `data_extend_by` int(10) unsigned DEFAULT null, `data_from` datetime DEFAULT null, `data_to` datetime DEFAULT null, `data_offers` int(10) unsigned DEFAULT null, `data_status` tinyint(2) unsigned DEFAULT null, `data_winner_id_customer` int(10) unsigned null, `data_winner_price` decimal(20,6) DEFAULT null, `data_winner_status` tinyint(2) unsigned DEFAULT null, `date_add` datetime NOT null, `date_upd` datetime NOT null, PRIMARY KEY (`id_product_auction_mailing`), KEY `idx_product_auction_mailing_id_process` (`id_process`), KEY `fk_PREFIX_product_auction_mailing_product_auction` (`id_product_auction`), KEY `fk_PREFIX_product_auction_mailing_product` (`id_product`), KEY `fk_PREFIX_product_auction_mailing_customer` (`id_customer`), KEY `fk_PREFIX_product_auction_mailing_employee` (`id_employee`), KEY `fk_PREFIX_product_auction_mailing_winner` (`data_winner_id_customer`), KEY `fk_PREFIX_product_auction_mailing_shop` (`id_shop`), KEY `fk_PREFIX_product_auction_mailing_cart` (`id_cart`), KEY `fk_PREFIX_product_auction_mailing_currency` (`id_currency`), CONSTRAINT `fk_PREFIX_product_auction_mailing_product_auction` FOREIGN KEY (`id_product_auction`) REFERENCES `PREFIX_product_auction` (`id_product_auction`) ON DELETE CASCADE, CONSTRAINT `fk_PREFIX_product_auction_mailing_product` FOREIGN KEY (`id_product`) REFERENCES `PREFIX_product` (`id_product`) ON DELETE CASCADE, CONSTRAINT `fk_PREFIX_product_auction_mailing_customer` FOREIGN KEY (`id_customer`) REFERENCES `PREFIX_customer` (`id_customer`) ON DELETE CASCADE, CONSTRAINT `fk_PREFIX_product_auction_mailing_employee` FOREIGN KEY (`id_employee`) REFERENCES `PREFIX_employee` (`id_employee`) ON DELETE CASCADE, CONSTRAINT `fk_PREFIX_product_auction_mailing_winner` FOREIGN KEY (`data_winner_id_customer`) REFERENCES `PREFIX_customer` (`id_customer`) ON DELETE CASCADE, CONSTRAINT `fk_PREFIX_product_auction_mailing_shop` FOREIGN KEY (`id_shop`) REFERENCES `PREFIX_shop` (`id_shop`) ON DELETE SET null, CONSTRAINT `fk_PREFIX_product_auction_mailing_cart` FOREIGN KEY (`id_cart`) REFERENCES `PREFIX_cart` (`id_cart`) ON DELETE SET null, CONSTRAINT `fk_PREFIX_product_auction_mailing_currency` FOREIGN KEY (`id_currency`) REFERENCES `PREFIX_currency` (`id_currency`) ON DELETE SET null ) ENGINE=InnoDB DEFAULT CHARSET=utf8; <file_sep><?php /** * install.conf.php file defines all needed constants and variables used in installation of module */ /** include common conf **/ require_once(dirname(__FILE__) . '/common.conf.php'); /** defines install library path uses => to include class files **/ define('_FPC_PATH_LIB_INSTALL', _FPC_PATH_LIB . 'install/'); /** defines installation sql file uses => only with DB install action **/ define('_FPC_INSTALL_SQL_FILE', 'install.sql'); // comment if not use SQL /** defines uninstallation sql file uses => only with DB uninstall action **/ define('_FPC_UNINSTALL_SQL_FILE', 'uninstall.sql'); // comment if not use SQL /** defines constant for plug SQL install/uninstall debug uses => set "true" only in debug mode - exceeds install sql execution **/ define('_FPC_LOG_JAM_SQL', false); // comment if not use SQL /** defines constant for plug CONFIG install/uninstall debug uses => set "true" only in debug mode - exceeds uninstall sql execution **/ define('_FPC_LOG_JAM_CONFIG', false);<file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) { exit; } class Powatag extends PaymentModule { const EAN = 1; const UPC = 2; const PRODUCT_ID = 3; const REFERENCE = 4; /** * Constructor of module. */ public function __construct() { $this->name = 'powatag'; $this->tab = 'mobile'; $this->version = '1.1.0'; $this->author = 'POWA'; parent::__construct(); $this->includeFiles(); $this->displayName = $this->l('PowaTag'); $this->description = $this->l('PowaTag, the one touch payment solution that increases your online & mobile conversions'); if (self::isInstalled($this->name) && self::isEnabled($this->name)) { $this->upgrade(); } } private function includeFiles() { $path = $this->getLocalPath().'classes/'; foreach (scandir($path) as $class) { if (is_file($path.$class)) { $class_name = Tools::substr($class, 0, -4); //Check if class_name is an existing Class or not if (!class_exists($class_name, false) && $class_name != 'index') { require_once $path.$class_name.'.php'; } } } $path .= 'helper/'; foreach (scandir($path) as $class) { if (is_file($path.$class)) { $class_name = Tools::substr($class, 0, -4); //Check if class_name is an existing Class or not if (!class_exists($class_name, false) && $class_name != 'index') { require_once $path.$class_name.'.php'; } } } } /** * Module install. * * @return bool if install was successfull */ public function install() { // Install default if (!parent::install()) { return false; } // Uninstall DataBase if (!$this->installSQL()) { return false; } // Install tabs if (!$this->installTabs()) { return false; } // Registration hook if (!$this->registrationHook()) { return false; } //Install default configs $configs = array( 'POWATAG_SKU' => self::PRODUCT_ID, ); foreach ($configs as $config => $value) { Configuration::updateValue($config, $value); } return true; } /** * Upgrade if necessary. */ public function upgrade() { $cfgName = Tools::strtoupper($this->name.'_version'); $version = Configuration::get($cfgName); if ($version === false || version_compare($version, $this->version, '<')) { Configuration::updateValue($cfgName, $this->version); } } /** * Module uninstall. * * @return bool if uninstall was successfull */ public function uninstall() { // Uninstall DataBase if (!$this->uninstallSQL()) { return false; } // Uninstall Tabs $moduleTabs = Tab::getCollectionFromModule($this->name); if (!empty($moduleTabs)) { foreach ($moduleTabs as $moduleTab) { $moduleTab->delete(); } } //Delete configuration $configs = array( 'POWATAG_API_LOG', 'POWATAG_REQUEST_LOG', 'POWATAG_SKU', 'POWATAG_QR_POS', 'POWATAG_QR', 'POWATAG_IMG_TYPE', 'POWATAG_SUCCESS_MSG', 'POWATAG_SHIPPING', 'POWATAG_CSS_URL', 'POWATAG_JS_URL', 'POWATAG_GENERATOR_URL', 'POWATAG_HMAC_KEY', 'POWATAG_API_KEY', 'POWATAG_REDIRECT', 'POWATAG_OFFER', 'POWATAG_LANG', 'POWATAG_TYPE', 'POWATAG_STYLE', 'POWATAG_COLORSCHEME', 'POWATAG_DISPLAY', 'POWATAG_VIDEO', 'POWATAG_DEBUG', ); foreach ($configs as $config) { Configuration::deleteByName($config); } // Uninstall default if (!parent::uninstall()) { return false; } return true; } /** * Initialisation to install / uninstall. */ private function installTabs() { $menu_id = -1; $controllers = scandir(dirname(__FILE__).'/controllers/admin'); foreach ($controllers as $controller) { if (is_file(dirname(__FILE__).'/controllers/admin/'.$controller) && $controller != 'index.php') { require_once dirname(__FILE__).'/controllers/admin/'.$controller; $controller_name = Tools::substr($controller, 0, -4); if (class_exists($controller_name)) { if (method_exists($controller_name, 'install')) { call_user_func(array($controller_name, 'install'), $menu_id, $this->name, $this->context->language->id, $this); } } } } return true; } public function initToolbar() { $toolbar_btn = array(); $toolbar_btn['configuration'] = array( 'href' => $this->context->link->getAdminLink('AdminPowaTagConfiguration'), 'desc' => $this->l('Configuration'), 'imgclass' => 'edit', ); $toolbar_btn['logs'] = array( 'href' => $this->context->link->getAdminLink('AdminPowaTagLogs'), 'desc' => $this->l('Logs'), 'imgclass' => 'preview', ); return $toolbar_btn; } /** * Install DataBase table. * * @return bool if install was successfull */ private function installSQL() { $classes = scandir(dirname(__FILE__).'/classes'); foreach ($classes as $class) { if (is_file(dirname(__FILE__).'/classes/'.$class)) { $class_name = Tools::substr($class, 0, -4); if (class_exists($class_name)) { if (method_exists($class_name, 'install')) { call_user_func(array($class_name, 'install')); } } } } return true; } /** * Uninstall DataBase table. * * @return bool if install was successfull */ private function uninstallSQL() { $classes = scandir(dirname(__FILE__).'/classes'); foreach ($classes as $class) { if (is_file(dirname(__FILE__).'/classes/'.$class)) { $class_name = Tools::substr($class, 0, -4); if (class_exists($class_name)) { if (method_exists($class_name, 'uninstall')) { call_user_func(array($class_name, 'uninstall')); } } } } return true; } /** * [registrationHook description]. * * @return [type] [description] */ private function registrationHook() { if (!$this->registerHook('displayHeader') || !$this->registerHook('displayRightColumnProduct') || !$this->registerHook('displayLeftColumnProduct') || !$this->registerHook('displayFooterProduct') || !$this->registerHook('displayProductButtons') || !$this->registerHook('actionCarrierUpdate') || !$this->registerHook('displayMobileAddToCartTop') || !$this->registerHook('displayMobileHeader') ) { return false; } return true; } public function hookdisplayMobileHeader() { return $this->hookDisplayHeader(); } public function hookDisplayHeader() { if ($this->context->smarty->getTemplateVars('page_name') == 'product') { $product = new Product((int) Tools::getValue('id_product'), true, (int) $this->context->language->id); if (PowaTagProductHelper::getProductSKU($product)) { $this->context->controller->addJS(Configuration::get('POWATAG_JS_URL')); $this->context->smarty->assign(array( 'powatag_css_url' => Configuration::get('POWATAG_CSS_URL'), )); return $this->display(__FILE__, 'powatag_header.tpl'); } } } public function hookDisplayProductButtons() { if (!Configuration::get('POWATAG_QR') || Configuration::get('POWATAG_QR_POS') != 'displayProductButtons') { return false; } if (!version_compare(_PS_VERSION_, 1.6, '<')) { $this->context->controller->addCSS($this->getPathUri().'views/css/powatag.css'); } return $this->generateTag(); } public function hookdisplayRightColumnProduct() { if (!Configuration::get('POWATAG_QR') || Configuration::get('POWATAG_QR_POS') != 'displayRightColumnProduct') { return false; } return $this->generateTag(); } public function hookDisplayMobileAddToCartTop() { if (!Configuration::get('POWATAG_QR')) { return false; } return $this->generateTag(); } public function hookdisplayLeftColumnProduct() { if (!Configuration::get('POWATAG_QR') || Configuration::get('POWATAG_QR_POS') != 'displayLeftColumnProduct') { return false; } return $this->generateTag(); } public function hookdisplayFooterProduct() { if (!Configuration::get('POWATAG_QR') || Configuration::get('POWATAG_QR_POS') != 'displayFooterProduct') { return false; } return $this->generateTag(); } public function hookactionCarrierUpdate($params) { if ($params['carrier'] instanceof Carrier && Validate::isLoadedObject($params['carrier'])) { if (Configuration::get('POWATAG_SHIPPING') == $params['id_carrier']) { Configuration::updateValue('POWATAG_SHIPPING', $params['carrier']->id); } } } private function generateTag() { $product = new Product((int) Tools::getValue('id_product'), true, (int) $this->context->language->id); if (PowaTagProductHelper::getProductSKU($product)) { $lang = Configuration::get('POWATAG_LANG'); if ($lang == 'site') { // convert "en-us" to "en_US" $lang = $this->context->language->language_code; $lang = str_replace('-', '_', $lang); $alang = explode('_', $lang); if (count($alang) == 2) { $lang = Tools::strtolower($alang[0]).'_'.Tools::strtoupper($alang[1]); } } $datas = array( 'powatagApi' => Configuration::get('POWATAG_API_KEY'), 'productSku' => PowaTagProductHelper::getProductSKU($product), 'powatagGeneratorURL' => Configuration::get('POWATAG_GENERATOR_URL'), 'powatagRedirect' => Configuration::get('POWATAG_REDIRECT'), 'powatagOffer' => Configuration::get('POWATAG_OFFER'), 'powatagLang' => $lang, 'powatagType' => Configuration::get('POWATAG_TYPE'), 'powatagStyle' => Configuration::get('POWATAG_STYLE'), 'powatagColorscheme' => Configuration::get('POWATAG_COLORSCHEME'), 'powatagDisplay' => Configuration::get('POWATAG_DISPLAY'), 'powatagVideo' => Configuration::get('POWATAG_VIDEO') ? 'true' : 'false', 'powatagDebug' => Configuration::get('POWATAG_DEBUG') ? 'true' : 'false', ); $this->context->smarty->assign($datas); return $this->display(__FILE__, 'product.tpl'); } } /** * Admin display. * * @return String Display admin content */ public function getContent() { Tools::redirectAdmin($this->context->link->getAdminLink('AdminPowaTagConfiguration')); } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_20351b3328c35ab617549920f5cb4939'] = 'Personalização #'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ed6e9a09a111035684bb23682561e12d'] = 'retire o produto do meu carrinho'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_c6995d6cc084c192bc2e742f052a5c74'] = 'Remessa grátis!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_e7a6ca4e744870d455a57b644f696457'] = 'Grátis!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f2a6c498fb90ee345d997f888fce3b18'] = 'Excluir'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_a85eba4c6c699122b2bb1387ea4813ad'] = 'Carrinho'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_86024cad1e83101d97359d7351051156'] = 'Produtos'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f5bf48aa40cad7891eb709fcf1fde128'] = 'Produto'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(vazio)'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b7d496eedb665d0b5f589f2f874e7cb'] = 'Detalhe do produto'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_3d9e3bae9905a12dae384918ed117a26'] = 'Personalização #%d'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_09dc02ecbb078868a3a86dded030076d'] = 'Não há produtos'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ea9cf7e47ff33b2be14e6dd07cbcefc6'] = 'Remessa'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ba794350deb07c0c96fe73bd12239059'] = 'Envoltório'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b78ac8eb158840e9638a3aeb26c4a9d'] = 'Imposto'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_96b0141273eabab320119c467cdcaf17'] = 'Total'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_0d11c2b75cf03522c8d97938490466b2'] = 'Os preços são impostos incluídos'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_41202aa6b8cf7ae885644717dab1e8b4'] = 'Preços sem IVA'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_377e99e7404b414341a9621f7fb3f906'] = 'Confira'; <file_sep><?php require_once "AdBlock.php"; require_once "AdResult.php"; require_once "GetAdvertisementResult.php"; require_once "DefaultResultHandler.php"; /** * XML content handler for getAdvertisement documents. * * @package prediggo4php * @subpackage xmlhandlers * * @author Stef */ class GetAdvertisementResultHandler extends DefaultResultHandler { /** * Handles the current node in the xml reading loop. * @param DOMNode $node The current xml node * @param GetAdvertisementResult $resultObj The object which will be returned to the end-user * @return boolean True if the node was handled */ protected function handleXmlReaderCurrentNode(DOMNode $node, $resultObj) { if( parent::handleXmlReaderCurrentNode($node, $resultObj )) return true; switch ($node->nodeName) { //items list case "page": $this->readPageResult($node, $resultObj); return true; } return false; } /** * Read and parse a profileResult * @param DOMNode $pageNode the "<page>" node * @param GetAdvertisementResult $resultObj the object to fill */ protected function readPageResult(DOMNode $pageNode, GetAdvertisementResult $resultObj) { //read profile attributes foreach ( $pageNode->attributes as $attribute ) { switch ($attribute->name) { case "ID": $resultObj->setPageId( intval( $attribute->value ) ); break; case "name": $resultObj->setPageName( $attribute->value ); break; } } //read suggestion blocks foreach ( $pageNode->childNodes as $blockNode ) { switch ($blockNode->nodeName) { case "block": //parse product element $block = new AdBlock(); $this->readBlock( $blockNode, $block); $resultObj->addBlock( $block ); break; } } } /** * Reads a word element. * @param DOMNode $blockNode an xml element representing a block * @param AdBlock $block the block object to fill. */ protected function readBlock(DOMNode $blockNode, AdBlock $block) { //read attributes foreach ( $blockNode->attributes as $attribute ) { switch ($attribute->name) { case "ID": $block->setBlockId( intval( $attribute->value ) ); break; case "name": $block->setBlockName( $attribute->value ); break; } } //read blocks foreach ( $blockNode->childNodes as $adNode ) { switch ($adNode->nodeName) { case "ad": //parse ad element $ad = new AdResult(); $this->readAd( $adNode, $ad); $block->addAd( $ad ); break; } } } /** * Reads a AD element. * @param DOMNode $adNode an xml element representing a product * @param AdResult $ad the advertisement object to fill. */ protected function readAd(DOMNode $adNode, AdResult $ad) { //read attributes foreach ( $adNode->attributes as $attribute ) { switch ($attribute->name) { case "name": $ad->setAdName( $attribute->value ); break; case "pictureUrl": $ad->setPictureUrl($attribute->value ); break; case "clickUrl" : $ad->setClickUrl($attribute->value); break; case "clickID" : $ad->setClickId($attribute->value); break; } } //read blocks foreach ( $adNode->childNodes as $propertiesNode ) { switch ($propertiesNode->nodeName) { case "properties": //parse properties element $this->readProperties( $propertiesNode, $ad); //$block->addAd( $ad ); break; } } } protected function readProperties(DOMNode $propertiesNode, AdResult $ad) { //read props foreach ( $propertiesNode->childNodes as $propertyNode ) { switch ($propertyNode->nodeName) { case "property": $key = ''; $value = ''; foreach ( $propertyNode->attributes as $attribute ) { switch ($attribute->name) { case "name": $key = $attribute->value ; break; case "value": $value = $attribute->value; break; } } if( !empty( $key) ) { $ad->addProperty($key, $value); } break; } } } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsMyBidsModuleFrontController', false)) return; class AuctionsMyBidsModuleFrontController extends AuctionsMyAuctionsController { public $display_column_left = false; public $display_column_right = false; public function __construct() { parent::__construct(); $this->display_column_left = false; $this->display_column_right = false; } public function process() { parent::process(); $product_auction_offer_status = array( ProductAuctionOffer::STATUS_VALID, ProductAuctionOffer::STATUS_RETIRED, ProductAuctionOffer::STATUS_WINNER ); if ($this->context->customer->isLogged() && $this->context->customer->id > 0) { $this->pagination($this->mybids_count); $product_auction_collection = ProductAuctionDataManager::getCurrentAuctionsCollectionByCustomer($this->context->customer->id, $this->n, $this->p, $this->context->language->id, $this->context->shop->id); $product_auction_customer_offers_collection = ProductAuctionOfferDataManager::getCollectionByProductAuctionsAndCustomer($product_auction_collection, $product_auction_offer_status, $this->context->customer->id, $this->context->language->id, $this->context->shop->id); foreach ($product_auction_collection as $product_auction) { if (isset($product_auction_customer_offers_collection[$product_auction->id])) { $product_auction->current_customer_offer = $product_auction_customer_offers_collection[$product_auction->id]; $product_auction->current_customer_offer->setProductAuction($product_auction); } } $product_auction_item_collection = ProductAuctionItemFactory::getInstance($this->module)->makeFrontOfficeItems($product_auction_collection); $this->context->smarty->assign(array( 'items' => $this->module->convertProductAuctionItemCollectionToArray($product_auction_item_collection, AbstractProductAuctionPermissions::TYPE_MY_AUCTIONS, true), )); } } public function initContent() { parent::initContent(); if (!$this->context->customer->isLogged()) Tools::redirect('index.php?controller=auth&redirect=module&module=auctions&action=mybids'); $this->context->smarty->assign(array( 'id_customer' => $this->context->customer->id, 'mod_path' => $this->module->getPathUri(), 'mod_dir' => pathinfo($this->getTemplatePath('product-auction-my-bids.tpl'), PATHINFO_DIRNAME).DIRECTORY_SEPARATOR )); $this->setTemplate('product-auction-my-bids.tpl'); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AdminAuctionsTemplatesController', false)) return; class AdminAuctionsTemplatesController extends ModuleAdminController { public function __construct() { $this->bootstrap = true; $this->identifier = 'id_product_auction_template'; $this->table = 'product_auction_template'; $this->className = 'ProductAuctionTemplate'; $this->lang = true; $this->list_no_link = !$this->tabAccess['edit']; $this->allow_export = true; parent::__construct(); $this->_defaultOrderBy = $this->identifier; $this->fields_list = array( 'id_product_auction_template' => array( 'title' => $this->l('ID'), 'align' => 'center', 'width' => 10 ), 'default' => array( 'title' => $this->l('Default'), 'align' => 'center', 'type' => 'bool', 'icon' => array(0 => array('class' => 'icon-2x icon-red icon-times-circle'), 1 => array('class' => 'icon-2x icon-green icon-check-circle')), ), 'name' => array( 'title' => $this->l('Name'), ), 'initial_price' => array( 'title' => $this->l('Starting price'), 'type' => 'price', 'align' => 'right' ), 'minimal_price' => array( 'title' => $this->l('Reserve price'), 'type' => 'price', 'align' => 'right' ), 'buynow_price' => array( 'title' => $this->l('Buy now price'), 'type' => 'price', 'align' => 'right' ), 'buynow_after_bid' => array( 'title' => $this->l('Buy now after bid'), 'align' => 'center', 'type' => 'bool', 'icon' => array(0 => array('class' => 'icon-2x icon-red icon-times-circle'), 1 => array('class' => 'icon-2x icon-green icon-check-circle')), ), 'from' => array( 'title' => $this->l('Start Date'), 'align' => 'right', 'callback_object' => $this, 'callback' => 'formatTemplateFromDate' ), 'to' => array( 'title' => $this->l('Finish Date'), 'align' => 'right', 'callback_object' => $this, 'callback' => 'formatTemplateToDate' ), 'duration' => array( 'title' => $this->l('Duration'), 'align' => 'center', 'callback_object' => 'CoreModuleColumnFormatter', 'callback' => 'formatTemplateDuration' ), 'proxy_bidding' => array( 'title' => $this->l('Proxy bidding'), 'align' => 'center', 'type' => 'bool', 'icon' => array(0 => array('class' => 'icon-2x icon-red icon-times-circle'), 1 => array('class' => 'icon-2x icon-green icon-check-circle')), ), 'extend_threshold' => array( 'title' => $this->l('Extend within'), 'align' => 'center', 'callback_object' => 'CoreModuleColumnFormatter', 'callback' => 'formatCountDown' ), 'extend_by' => array( 'title' => $this->l('Extend by'), 'align' => 'center', 'callback_object' => 'CoreModuleColumnFormatter', 'callback' => 'formatCountDown' ), 'active' => array( 'title' => $this->l('Template active'), 'active' => 'status', 'align' => 'center', 'type' => 'bool' ), 'date_add' => array( 'title' => $this->l('Created'), 'type' => 'datetime', 'align' => 'right' ), 'date_upd' => array( 'title' => $this->l('Modified'), 'type' => 'datetime', 'align' => 'right' ) ); $this->_join .= 'LEFT JOIN ( SELECT id_product_auction_template, IF(from_fixed IS NOT null AND from_fixed != "0000-00-00 00:00:00", from_fixed, from_offset) AS `from`, IF(to_fixed IS NOT null AND to_fixed != "0000-00-00 00:00:00", to_fixed, to_offset) AS `to` FROM '._DB_PREFIX_.'product_auction_template ) pad ON (a.id_product_auction_template = pad.id_product_auction_template)'; $this->_select .= 'pad.from, pad.to, COALESCE(pad.from, pad.to) AS `duration`'; } public function initPageHeaderToolbar() { parent::initPageHeaderToolbar(); if ($this->tabAccess['add']) { switch ($this->display) { case 'add': case 'edit': case 'view': break; default: $this->page_header_toolbar_btn['new'] = array( 'href' => self::$currentIndex.'&add'.$this->table.'&token='.$this->token, 'desc' => $this->l('Add new') ); } } else { unset($this->page_header_toolbar_btn['new']); unset($this->page_header_toolbar_btn['import']); unset($this->page_header_toolbar_btn['export']); } } public function initToolbar() { parent::initToolbar(); unset($this->toolbar_btn['new']); } public function renderList() { if ($this->tabAccess['edit']) $this->addRowAction('edit'); return parent::renderList(); } public function renderForm() { $this->initToolbar(); $this->loadObject(true); $currency = $this->context->currency; $show_hints = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::SHOW_FORM_HINTS); $this->multiple_fieldsets = true; $this->fields_form = array( array( 'form' => array( 'legend' => array( 'title' => $this->l('Settings') ), 'input' => array( array( 'type' => 'text', 'label' => $this->l('Name:'), 'name' => 'name', 'lang' => true, 'size' => 50, 'required' => true, 'desc' => $this->l('The name of the template') ), array( 'type' => 'switch', 'label' => $this->l('Default template:'), 'name' => 'default', 'required' => true, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'default_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'default_off', 'value' => 0, 'label' => $this->l('No') ), ), 'desc' => $this->l('Check the checkbox to set this template as a default') ) ) ) ), array( 'form' => array( 'legend' => array( 'title' => $this->l('Dates') ), 'input' => array( array( 'type' => 'auctions_datetime', 'range' => true, 'label' => $this->l('Starts at:'), 'desc' => $this->l('Date when the auction starts'), 'id' => 'from', 'name' => 'from_fixed', 'autocomplete' => false, 'size' => 24 ), array( 'type' => 'auctions_datetime', 'range' => true, 'label' => $this->l('Ends at:'), 'desc' => $this->l('Date when the auction ends'), 'id' => 'to', 'name' => 'to_fixed', 'shortcuts' => array( array( 'value' => 1, 'label' => $this->l('1d') ), array( 'value' => 2, 'label' => $this->l('2d') ), array( 'value' => 5, 'label' => $this->l('5d') ), array( 'value' => 7, 'label' => $this->l('7d') ), array( 'value' => 10, 'label' => $this->l('10d') ), array( 'value' => 14, 'label' => $this->l('14d') ), array( 'value' => 30, 'label' => $this->l('30d') ) ), 'autocomplete' => false, 'size' => 24 ), array( 'type' => 'text', 'label' => $this->l('Starts at offset:'), 'desc' => $this->l('Time offset when the auction starts'), 'name' => 'from_offset', 'suffix' => $this->l('seconds'), 'size' => 24 ), array( 'type' => 'text', 'label' => $this->l('Ends at offset:'), 'desc' => $this->l('Time offset when the auction ends'), 'name' => 'to_offset', 'suffix' => $this->l('seconds'), 'size' => 24 ) ) ) ), array( 'form' => array( 'legend' => array( 'title' => $this->l('Prices') ), 'description' => $show_hints ? $this->l('All prices should be pre-tax. Tax will be calculated automatically based on the tax defined in "prices" tab and shop settings.') : null, 'input' => array( array( 'type' => 'text', 'label' => $this->l('Starting price:'), 'name' => 'initial_price', 'size' => 10, 'price' => true, 'prefix' => $currency->getSign('left'), 'suffix' => $currency->getSign('right'), 'desc' => $this->l('Initial price at which the auction will start'), 'string_format' => '%.2f', ), array( 'type' => 'text', 'label' => $this->l('Reserve price:'), 'desc' => $this->l('Minimal price at which you are able to sell the product'), 'name' => 'minimal_price', 'size' => 10, 'price' => true, 'prefix' => $currency->getSign('left'), 'suffix' => $currency->getSign('right'), 'string_format' => '%.2f', ), array( 'type' => 'text', 'label' => $this->l('Buy now price:'), 'name' => 'buynow_price', 'size' => 10, 'price' => true, 'prefix' => $currency->getSign('left'), 'suffix' => $currency->getSign('right'), 'desc' => $this->l('Buy now price at which you are able to sell the product without auction'), 'string_format' => '%.2f', ), array( 'type' => 'switch', 'label' => $this->l('Buy now after first bid'), 'name' => 'buynow_after_bid', 'required' => true, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'default_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'default_off', 'value' => 0, 'label' => $this->l('No') ), ), 'desc' => $this->l('Define if you want "Buy now" option to be still available after the first bid is placed'), ), ), ), ), array( 'form' => array( 'legend' => array( 'title' => $this->l('Bidding Increment Rules'), ), 'description' => $show_hints ? $this->l('Set the minimum amount by which the bid will be raised. You can create a number of bidding ranges (increment rules.)') : null, 'input' => array( array( 'type' => 'bid_range', 'label' => $this->l('Bidding range:'), 'desc' => $this->l('Define ranges of prices and belonging to them bid increments that will be considered as valid bids. If "To Price" is 0.00 is set whole range is covered.'), 'name' => 'bidding_increment_array', 'size' => 15, 'price' => true, 'prefix' => $currency->getSign('left'), 'suffix' => $currency->getSign('right'), 'string_format' => '%.2f' ) ) ) ), array( 'form' => array( 'legend' => array( 'title' => $this->l('Proxy bidding') ), 'description' => $show_hints ? $this->l('Proxy bidding enables the customer to place the maximum amount he/she is willing to pay for the item. That price is not visible for other users and the customer\'s bid is automatically raised when someone places higher offer until the maximum amount defined by the customer is reached. The customer can get the product for less than his/her actual bid.') : null, 'input' => array( array( 'type' => 'switch', 'label' => $this->l('Activate proxy bidding'), 'name' => 'proxy_bidding', 'required' => true, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'default_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'default_off', 'value' => 0, 'label' => $this->l('No') ), ), 'desc' => $this->l('Enable automatic bidding on the current auction'), ) ) ) ), array( 'form' => array( 'legend' => array( 'title' => $this->l('Popcorn bidding') ), 'description' => $show_hints ? $this->l('Popcorn Bidding gives all bidders an equal chance of winning an auction by extending the end time of the auction if a last minute bid is placed. It is used to simulate a live auction and prevents other bidders from "sniping" an auction at the last second without giving all interested bidders a chance to win.') : null, 'input' => array( array( 'type' => 'text', 'label' => $this->l('Extend the bid deadline within:'), 'desc' => $this->l('Extend the bid deadline when bid is made within given amount of seconds before the auction ends'), 'name' => 'extend_threshold', 'suffix' => $this->l('seconds'), 'size' => 24 ), array( 'type' => 'text', 'range' => true, 'label' => $this->l('Extend the bid deadline by:'), 'desc' => $this->l('Extend the bid deadline by given amount of seconds'), 'name' => 'extend_by', 'suffix' => $this->l('seconds'), 'size' => 24 ) ), 'submit' => array( 'title' => $this->l('Save'), ) ) ) ); return parent::renderForm(); } public function postProcess() { if (!$this->redirect_after) parent::postProcess(); if ($this->display == 'edit' || $this->display == 'add') { $this->addJqueryUI(array( 'ui.core', 'ui.widget', 'ui.slider', 'ui.datepicker' )); $this->addjQueryPlugin(array( 'autocomplete', 'date' )); $this->addJS(array( _PS_JS_DIR_.'productTabsManager.js', _PS_JS_DIR_.'jquery/plugins/timepicker/jquery-ui-timepicker-addon.js' )); $this->addCSS(array( _PS_JS_DIR_.'jquery/plugins/timepicker/jquery-ui-timepicker-addon.css' )); } } public function setHelperDisplay(Helper $helper) { parent::setHelperDisplay($helper); $helper->override_folder = null; $helper->module = $this->module; } protected function copyFromPost(&$object, $table) { parent::copyFromPost($object, $table); $this->module->copyFromPost($object); } public function formatTemplateFromDate($value, $row) { return CoreModuleColumnFormatter::formatTemplateFromDate($value, $row, $this->module); } public function formatTemplateToDate($value, $row) { return CoreModuleColumnFormatter::formatTemplateToDate($value, $row, $this->module); } } <file_sep>/** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ var auctions = { subscription: function() { $.ajax({ type: "POST", dataType: "json", url: $(this).attr('href'), data: { products: [$(this).attr('data-id')], ajax: true }, success: function(result) { if (result.success) { for(var key in result.id_product_auction) { switch (result.action) { case 'add': $('#add_auction_item_'+result.id_product_auction[key]).fadeOut(function() { $('#remove_auction_item_'+result.id_product_auction[key]).fadeIn("slow"); }); break; case 'remove': $('#remove_auction_item_'+result.id_product_auction[key]).fadeOut(function() { $('#add_auction_item_'+result.id_product_auction[key]).fadeIn("slow"); }); break; } } } } }); return false; }, bids: function() { $.ajax({ type: "POST", cache: false, url: this.href, data: { id_product_auction: $(this).attr('data-id'), ajax: true }, success: function (data) { $.fancybox(data, { padding: [15, 30, 0, 30], fitToView: true, minWidth: 439, maxWidth: 980 }); } }); return false; }, highlightCountdown: function(periods) { var threshold = $(this).attr('data-threshold'); var periods_sec = $.countdown.periodsToSeconds(periods); if (threshold && periods_sec > 0 && periods_sec <= threshold) { $(this).parent().addClass('highlight'); } }, finishedCountdown: function(periods) { $(this).parent().removeClass('highlight'); }, countdown: function() { var inst = $(this).data(); if (typeof inst.countdown == 'object') return; var dataFormat = inst.format; var dataExpiry = inst.expiry; var dataUntil = parseInt(inst.finish); var dataCompact = parseInt(inst.compact); var dataType = parseInt(inst.type); $(this).removeClass('is-countdown').countdown({ until: dataUntil > 0 ? dataUntil : 0, compact: dataCompact > 0, format: dataFormat ? dataFormat : 'DHMS', alwaysExpire: true, expiryText: dataExpiry ? dataExpiry : '', onExpiry: auctions.finishedCountdown, onTick: auctions.highlightCountdown }); if (dataType == 2) { $(this).countdown('pause'); } } };<file_sep><?php require_once("AdResult.php"); /** * A block description containing Ads, a block usually correspond to an Ad slot on a web page */ class AdBlock { protected $blockId; protected $blockName; protected $ads = array(); /** * Gets the identifier of the block, defined by prediggo * @return */ public function getBlockId() { return $this->blockId; } public function setBlockId($blockId) { $this->blockId = $blockId; } /** * Get the name of the block, mostly for debugging purpose * @return */ public function getBlockName() { return $this->blockName; } public function setBlockName($blockName) { $this->blockName = $blockName; } /** * Returns the list of ads for this block, can be empty, never null * @return array[AdResult] a list of ads */ public function getAds() { return $this->ads; } public function setAds($ads) { $this->ads = $ads; } public function addAd(AdResult $ad) { $this->ads[] = $ad; } } <file_sep><?php header("Pragma: no-cache"); header("Expires: 0"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Content-type: application/xml"); //http://127.0.0.1/prestashop1-4-3/modules/yourstock_gp/ajax/add_stk.php?id_product=10&qty=500&PS_ROOT_DIR=c:\wamp\www\prestashop1-4-3&COOKIE_EMP=1&id_reason=1&id_product_attribute=NULL $PS_ROOT_DIR=$_POST['PS_ROOT_DIR']; //$PS_ROOT_DIR='c:\wamp\www\prestashop1-4-4'; //$prefix_ean=$_POST['prefix_ean']; require($PS_ROOT_DIR.'/config/config.inc.php'); //rajout des produits nouvellement créé succeptible de pouvoir recevoir un barcode /* $sql='insert into '._DB_PREFIX_.'yourbarcode_gp (select '._DB_PREFIX_.'product.id_product, '._DB_PREFIX_.'product_attribute.id_product_attribute, NULL from '._DB_PREFIX_.'product LEFT OUTER JOIN '._DB_PREFIX_.'product_attribute ON ('._DB_PREFIX_.'product_attribute.id_product='._DB_PREFIX_.'product.id_product) where concat('._DB_PREFIX_.'product.id_product,concat(\'|\',if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),\'0\','._DB_PREFIX_.'product_attribute.id_product_attribute))) not in (select concat('._DB_PREFIX_.'yourbarcode_gp.id_product,concat(\'|\','._DB_PREFIX_.'yourbarcode_gp.id_product_attribute)) from '._DB_PREFIX_.'yourbarcode_gp ) )'; //concat('._DB_PREFIX_.'product.id_product,concat(\'|\','._DB_PREFIX_.'product_attribute.id_product_attribute)) //echo $sql; Db::getInstance()->Execute($sql); */ //recuperation du code ean le plus grand avec le prefix configuré $sql='select prefix_cd from '._DB_PREFIX_.'yourbarcodeconf'; $resultat=Db::getInstance()->ExecuteS($sql); foreach ($resultat as $row) { $prefix_ean=$row['prefix_cd']; } //$prefix_ean=200; if ($_POST['prefix_fo']==$prefix_ean){ //$query='select id_product,id_product_attribute from '._DB_PREFIX_.'yourbarcode_gp where barcode IS NULL'; $query='select id_product,id_product_attribute from (select '._DB_PREFIX_.'product.id_product, if (ISNULL('._DB_PREFIX_.'product_attribute.id_product_attribute),0,'._DB_PREFIX_.'product_attribute.id_product_attribute) as id_product_attribute, if(ISNULL('._DB_PREFIX_.'product_attribute.id_product_attribute), '._DB_PREFIX_.'product.ean13, '._DB_PREFIX_.'product_attribute.ean13) as barcode from '._DB_PREFIX_.'product LEFT OUTER JOIN '._DB_PREFIX_.'product_attribute ON ( '._DB_PREFIX_.'product.id_product='._DB_PREFIX_.'product_attribute.id_product) ) tb_temp where barcode IS NULL or barcode=\'\' or barcode=\'0\''; $result = Db::getInstance()->ExecuteS($query); //retrouver le plus grand code ean13 attribue par rapport au prefixe //$code_depart=200000000010; /* $sql='SELECT max(LEFT(barcode,12)) as code_depart FROM '._DB_PREFIX_.'yourbarcode_gp where barcode like \''.$prefix_ean.'%\'';*/ //---recuperation du code ean13 le plus grande $sql='select max(ean13) as code_depart from ( select '._DB_PREFIX_.'product.id_product, if (ISNULL('._DB_PREFIX_.'product_attribute.id_product_attribute),0,'._DB_PREFIX_.'product_attribute.id_product_attribute) as id_product_attribute, if(ISNULL('._DB_PREFIX_.'product_attribute.id_product_attribute), '._DB_PREFIX_.'product.ean13, '._DB_PREFIX_.'product_attribute.ean13) as ean13 from '._DB_PREFIX_.'product LEFT OUTER JOIN '._DB_PREFIX_.'product_attribute ON ( '._DB_PREFIX_.'product.id_product='._DB_PREFIX_.'product_attribute.id_product) ) tb_temp where ean13 like \''.$prefix_ean.'%\''; //echo $sql; $resultat=Db::getInstance()->ExecuteS($sql); foreach ($resultat as $row) { $code_depart=$row['code_depart']; } if (!isset($code_depart) or $code_depart==0 or $code_depart=='' ) { $code_depart=$prefix_ean*pow(10,(12-strlen($prefix_ean))); //$code_depart=$prefix_ean*1000000000; } else { //2000000000015 $code_depart=substr($code_depart,0,-1); //echo $code_depart.'<BR>'; } /* if (!isset($code_depart) or $code_depart==0 or $code_depart=='' ) { $code_depart=$prefix_ean*1000000000; } else { //2000000000015 $code_depart=substr($code_depart,0,-1); //echo $code_depart.'<BR>'; }*/ //generation de tous les codes ean pour la base produits foreach ($result as $row){ $code_depart=$code_depart+1; $code_ean=$code_depart; while(strlen($code_ean)<12){ $code_ean="0".$code_ean; } $bit_ctrl=calc_bit_ctrl($code_ean); $code_ean=$code_ean.$bit_ctrl; //echo '<BR>'.$code_ean.'<BR>'; if($row['id_product_attribute']<>'0') { $query='UPDATE '._DB_PREFIX_.'product_attribute SET ean13 = \''.$code_ean.'\' WHERE '._DB_PREFIX_.'product_attribute.id_product ='.$row['id_product'].' AND '._DB_PREFIX_.'product_attribute.id_product_attribute ='.$row['id_product_attribute']; } else { $query='UPDATE '._DB_PREFIX_.'product SET ean13 = \''.$code_ean.'\' WHERE '._DB_PREFIX_.'product.id_product ='.$row['id_product'].' AND '._DB_PREFIX_.'product.id_product ='.$row['id_product']; } //$query='UPDATE '._DB_PREFIX_.'yourbarcode_gp SET barcode = \''.$code_ean.'\' WHERE '._DB_PREFIX_.'yourbarcode_gp.id_product ='.$row['id_product'].' AND '._DB_PREFIX_.'yourbarcode_gp.id_product_attribute ='.$row['id_product_attribute']; Db::getInstance()->Execute($query); //echo '<img src="EAN13.php?numero='.$code_ean.'&dimension=1"><BR>'; } echo 'ok'; } else { echo 'non_ok'; } //function permettant de calculer la clef de controle du code barre ean function calc_bit_ctrl($code_ean) { $ctrl_key=0; $len_ch= strlen($code_ean); $i=0; while($i<$len_ch) { $etape = $len_ch - $i; $tab[$i] = substr($code_ean, -$etape,1); $i++; } foreach ($tab as $key => $value){ if (($key+1)%2==0){ $ctrl_key=$ctrl_key+$value*3; } else { $ctrl_key=$ctrl_key+$value; } } $ctrl_key=$ctrl_key%10; //echo '<BR>'.$ctrl_key.'<BR>'; if ($ctrl_key==0) { return $ctrl_key; } else { return 10-$ctrl_key; } } ?><file_sep>{ //rajouter par <NAME>**************************************************** public static $classInModule = array(); public static function getModuleNameFromClass($currentClass) { global $cookie; // Module can now define AdminTab keeping the module translations method, // i.e. in modules/[module name]/[iso_code].php if (!isset(self::$classInModule[$currentClass])) { global $_MODULES; $_MODULE = array(); $reflectionClass = new ReflectionClass($currentClass); $filePath = realpath($reflectionClass->getFileName()); $realpathModuleDir = realpath(_PS_MODULE_DIR_); if (substr(realpath($filePath), 0, strlen($realpathModuleDir)) == $realpathModuleDir) { self::$classInModule[$currentClass] = substr(dirname($filePath), strlen($realpathModuleDir)+1); $id_lang = (!isset($cookie) OR !is_object($cookie)) ? (int)(Configuration::get('PS_LANG_DEFAULT')) : (int)($cookie->id_lang); $file = _PS_MODULE_DIR_.self::$classInModule[$currentClass].'/'.Language::getIsoById($id_lang).'.php'; if (Tools::file_exists_cache($file) AND include_once($file)) $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE; } else self::$classInModule[$currentClass] = false; } // return name of the module, or false return self::$classInModule[$currentClass]; } //fin de rajout par G.PREVEAUX<file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsBidModuleFrontController', false)) return; class AuctionsBidModuleFrontController extends CoreModuleController { public $display_column_left = false; public $display_column_right = true; /** * * @var Customer */ protected $customer; /** * * @var ProductAuction */ protected $product_auction; /** * * @var AbstractProductAuctionItem */ protected $product_auction_item; public function __construct() { parent::__construct(); $this->display_column_left = false; $this->display_column_right = true; } public function setMedia() { parent::setMedia(); $this->context->controller->addCSS(array( $this->module->getPathUri().'css/auctions_details.css' ), 'all'); } public function process() { // Check page token if (!$this->isTokenValid()) die(Tools::displayError('Invalid token.')); parent::process(); if ($this->loadObjects()) { $product_auction_bid_price = $this->getBidPrice(false); $product_auction_bid_price_plain = $this->getBidPrice(true); if ($this->validate($product_auction_bid_price)) { $step = (int)Tools::getValue('step', -1); switch ($step) { case 1: $this->step1($product_auction_bid_price); break; case 2: $this->step2($product_auction_bid_price); break; } } self::$smarty->assign(array( 'bid_price' => $product_auction_bid_price, 'bid_price_plain' => $product_auction_bid_price_plain, 'auction' => $this->module->convertProductAuctionItemToArray($this->product_auction_item, AbstractProductAuctionPermissions::TYPE_DETAILS, true) )); self::$smarty->assign(array( 'path' => Tools::getPath((int)$this->product_auction->product->id_category_default, $this->product_auction->product->name, true), 'back' => Tools::getValue('back', $this->product_auction->product->getLink()), 'login_url' => $this->context->link->getPageLink('authentication', true, $this->context->language->id, array( 'back' => $this->product_auction->product->getLink() )), 'bid_url' => $this->context->link->getModuleLink('auctions', 'bid') )); } } public function initContent() { parent::initContent(); if (!empty($this->errors)) { self::$smarty->assign(array( 'errors' => array_unique($this->errors) )); $this->setTemplate('product-auction-bid-errors.tpl'); } } protected function step1($product_auction_bid_price) { $this->setTemplate('product-auction-bid-step1.tpl'); } protected function step2($product_auction_bid_price) { $result = $this->bid($product_auction_bid_price); self::$smarty->assign(array( 'bid_results' => AbstractProductAuctionBidResult::getSmartyResults(), 'bid_result' => $result )); $this->setTemplate('product-auction-bid-step2.tpl'); } protected function getBidPrice($plain = false) { $bid_price = CoreModuleTools::getPrice(Tools::getValue('bid_price')); $min_price = $this->product_auction_item->getBidPrice(); if ($plain) return $bid_price; $bid_price_decimals = Tools::strlen(Tools::substr(strrchr($bid_price, '.'), 1)); $min_price_decimals = Tools::strlen(Tools::substr(strrchr($min_price, '.'), 1)); if ($bid_price_decimals < 2) $bid_price_decimals = 2; if ($min_price_decimals > 2) $bid_price += $min_price - (float)sprintf("%01.{$bid_price_decimals}f", $min_price); return $bid_price; } protected function loadObjects() { $this->customer = $this->context->customer; if (!Validate::isLoadedObject($this->customer)) die(Tools::displayError($this->l('You have to be logged in to make offer', 'Bid'))); $this->product_auction = new ProductAuction((int)Tools::getValue('id_product_auction'), true, $this->context->language->id, $this->context->shop->id); if (!Validate::isLoadedObject($this->product_auction)) die(Tools::displayError($this->l('Auction cannot be found!', 'Bid'))); $this->product_auction_item = ProductAuctionItemFactory::getInstance($this->module)->makeFrontOfficeItem($this->product_auction); if (!$this->product_auction_item->canBid($this->customer)) die(Tools::displayError($this->l('Cannot place the offer!', 'Bid'))); return true; } protected function validate($product_auction_bid_price) { $product_auction_type = $this->getProductAuctionType(); $validator = $product_auction_type->getProductAuctionValidator(); $validator->setCustomer($this->customer); $validator->setProductAuctionItem($this->product_auction_item); if (!$validator->validate($product_auction_bid_price)) { $validator->fillErrors($this->errors); return false; } return true; } protected function bid($product_auction_bid_price) { $product_auction_bid_price = Tools::convertPrice($product_auction_bid_price, $this->context->currency, false); $product_auction_type = $this->getProductAuctionType(); $product_auction_bid = $product_auction_type->getProductAuctionBid($this->module); $product_auction_bid->setCustomer($this->customer); $product_auction_bid->setProductAuction($this->product_auction); $product_auction_bid->setBidPrice($product_auction_bid_price); $product_auction_mailing = $product_auction_type->getProductAuctionMailingManager($this->module); $product_auction_mailing->notifyParticipants(array( $this->customer )); $product_auction_mailing->notifyParticipants($this->getParticipantsToNotify($this->product_auction)); $product_auction_mailing->notifySubscribers($this->getSubscribersToNotify($this->product_auction)); $product_auction_mailing->notifyEmployees($this->getAdministratorsToNotify($this->product_auction)); $product_auction_type->notify($product_auction_mailing); $result = $product_auction_type->bid($product_auction_bid->calculate()); return $result; } /** * * @return ProductAuctionType */ protected function getProductAuctionType() { return $this->product_auction->getProductAuctionType(); } protected function getParticipantsToNotify(ProductAuction $product_auction) { $product_auction_participants = array(); $product_auction_customers_collection = ProductAuctionOfferDataManager::getParticipantsCustomersCollectionByProductAuction($product_auction); foreach ($product_auction_customers_collection as $product_auction_customer) if ($product_auction_customer->id != $this->customer->id) $product_auction_participants[] = $product_auction_customer; return $product_auction_participants; } protected function getSubscribersToNotify(ProductAuction $product_auction) { $product_auction_subscribers = array(); if ($this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_WATCH_AUCTION)) { $product_auction_customers_collection = ProductAuctionSubscriptionDataManager::getSubscribersCustomersCollectionByProductAuction($product_auction); foreach ($product_auction_customers_collection as $product_auction_customer) if ($product_auction_customer->id != $this->customer->id) $product_auction_subscribers[] = $product_auction_customer; } return $product_auction_subscribers; } protected function getAdministratorsToNotify(ProductAuction $product_auction) { $mailing_settings = $this->module->getSettings('AuctionsMailingSettings'); $employees = new Collection('Employee'); $employees->where('active', '=', 1); $employees->where('id_employee', 'IN', $mailing_settings->getValue(AuctionsMailingSettings::AUCTION_BACKOFFICE_EMPLOYEES)); return $employees->getResults(); } } <file_sep><?php header("Pragma: no-cache"); header("Expires: 0"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Content-type: application/xml"); $PS_ROOT_DIR=$_POST['PS_ROOT_DIR']; $prefix_cd=$_POST['prefix_cd']; $format_pg=$_POST['format_pg']; $format_spe_lg=$_POST['format_spe_lg']; $format_spe_ht=$_POST['format_spe_ht']; $orientation=$_POST['orientation']; $marge_haut=$_POST['marge_haut']; $marge_gauche=$_POST['marge_gauche']; $rotation=$_POST['rotation']; $largeur_cd=$_POST['largeur_cd']; $hauteur_cd=$_POST['hauteur_cd']; $nb_img_lg=$_POST['nb_img_lg']; $nb_lig=$_POST['nb_lig']; $esp_lg_lg=$_POST['esp_lg_lg']; $esp_cl_cl=$_POST['esp_cl_cl']; require($PS_ROOT_DIR.'/config/config.inc.php'); $sql= 'UPDATE '._DB_PREFIX_.'yourbarcodeconf SET prefix_cd = \''.$prefix_cd.'\', format_pg = \''.$format_pg.'\', format_spe_lg = \''.$format_spe_lg.'\', format_spe_ht = \''.$format_spe_ht.'\', orientation = \''.$orientation.'\', marge_haut = \''.$marge_haut.'\', marge_gauche = \''.$marge_gauche.'\', rotation = \''.$rotation.'\', largeur_cd = \''.$largeur_cd.'\', hauteur_cd = \''.$hauteur_cd.'\', nb_img_lg = \''.$nb_img_lg.'\', nb_lig = \''.$nb_lig.'\', esp_lg_lg = \''.$esp_lg_lg.'\', esp_cl_cl = \''.$esp_cl_cl.'\';'; $result = Db::getInstance()->Execute($sql); echo 'ok'; ?><file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_20351b3328c35ab617549920f5cb4939'] = 'Personalización #'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ed6e9a09a111035684bb23682561e12d'] = 'Sacar de mi cesta de compra'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_c6995d6cc084c192bc2e742f052a5c74'] = 'Gastos de envío gratis!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_e7a6ca4e744870d455a57b644f696457'] = 'Gratis!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f2a6c498fb90ee345d997f888fce3b18'] = 'Borrar'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_a85eba4c6c699122b2bb1387ea4813ad'] = 'Carro'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_86024cad1e83101d97359d7351051156'] = 'productos'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f5bf48aa40cad7891eb709fcf1fde128'] = 'producto'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(Vacío)'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b7d496eedb665d0b5f589f2f874e7cb'] = 'Detalle del producto'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_3d9e3bae9905a12dae384918ed117a26'] = 'Personalización #% d:'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_09dc02ecbb078868a3a86dded030076d'] = 'No hay productos'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ea9cf7e47ff33b2be14e6dd07cbcefc6'] = 'Envío'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ba794350deb07c0c96fe73bd12239059'] = 'Envío'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b78ac8eb158840e9638a3aeb26c4a9d'] = 'Impuesto'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_96b0141273eabab320119c467cdcaf17'] = 'Los precios se entienden IVA incluído'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_0d11c2b75cf03522c8d97938490466b2'] = 'Los precios se entienden IVA incluído'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_41202aa6b8cf7ae885644717dab1e8b4'] = 'Los precios son sin IVA'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_377e99e7404b414341a9621f7fb3f906'] = 'Echa un vistazo a'; <file_sep><?php require_once 'RequestParamBase.php'; require_once "Utils.php"; /** * Parameter class for get Advertisement queries.. * * @package prediggo4php * @subpackage types * * @author Stef */ class GetAdvertisementParam extends RequestParamBase { protected $userId = ""; protected $profileMapId = -1; protected $pageId = 0; protected $languageCode = ""; protected $conditions = array(); /** * Gets the 2 characters ISO 639-1 language code. * @return string the language code */ public function getLanguageCode() { return $this->languageCode; } /** * Sets the 2 characters ISO 639-1 language code of the current user. * @param string $languageCode the language code */ public function setLanguageCode($languageCode) { $this->languageCode = $languageCode; } /** * Gets the profile ID. * @return integer the profile identifier */ public function getProfileMapId() { return $this->profileMapId; } /** * Sets the profile ID. If your shop has many of them. * @param integer $profileId the profile identifier. */ public function setProfileMapId($profileId) { $this->profileMapId = $profileId; } /** * Gets the current user identifier * @return string the user identifier */ public function getUserId() { return $this->userId; } /** * Sets the user identifier (if he's logged in) * @param string $userId user identifier */ public function setUserId($userId) { $this->userId = $userId; } /** * Return the page identifier, defined in prediggo * @return int */ public function getPageId() { return $this->pageId; } /** * Sets the page identifier, ID musr be defined in prediggo backoffice * @param int $pageId */ public function setPageId($pageId) { $this->pageId = $pageId; } /** * Gets the list of restrictions. Should be considered read only. * Restrictions are made of Key/Value pairs representing the name of the restricted attribute and the desired matching value. * @return array A set of conditions (Pair of attribute name and value) */ public function getConditions() { return $this->conditions; } /** * Adds a new condition to the filter (attribute == value). * @param string $attributeName The name of the attribute which you want to filter. * @param string $matchingValue The desired matching value. */ public function addCondition( $attributeName, $matchingValue ) { Utils::addPairToUniqueArray($this->conditions, $attributeName, $matchingValue); } /** * Adds a range condition to the filter ( min <= value <= max). * @param string $attributeName The name of the attribute which you want to filter. * @param string $minValue The minimum value * @param string $maxValue The maximum value * @param boolean $minInclusive true if values that are equal to the min boundary are accepted * @param boolean $maxInclusive true if value that are equal to the max boundary are accepted */ public function addConditionRange( $attributeName, $minValue, $maxValue, $minInclusive = true, $maxInclusive = true ) { $filter = $minValue . ','. $maxValue; $filter = ($minInclusive ? '[' : '(') . $filter ; $filter = $filter . ($maxInclusive ? ']' : ')') ; Utils::addPairToUniqueArray($this->conditions, $attributeName, $filter); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AdminAuctionsArchivedController', false)) return; class AdminAuctionsArchivedController extends ModuleAdminController { protected $product_identifier; protected $product_table; protected $product_class_name; protected $id_product; public function __construct() { $this->bootstrap = true; $this->identifier = 'id_product_auction_archive'; $this->table = 'product_auction_archive'; $this->className = 'ProductAuctionArchive'; $this->product_identifier = 'id_product'; $this->product_table = 'product'; $this->product_class_name = 'Product'; $this->lang = true; $this->list_no_link = false; $this->allow_export = true; parent::__construct(); $this->_defaultOrderBy = $this->identifier; $this->fields_list = array( 'id_product_auction_archive' => array( 'title' => $this->l('ID'), 'align' => 'center', 'width' => 10 ), 'name' => array( 'title' => $this->l('Name'), 'align' => 'center' ), 'from' => array( 'title' => $this->l('Starts at'), 'type' => 'datetime', 'align' => 'right' ), 'to' => array( 'title' => $this->l('Ends at'), 'type' => 'datetime', 'align' => 'right' ), 'offers' => array( 'title' => $this->l('Offers'), 'align' => 'center', 'width' => 50 ), 'initial_price' => array( 'title' => $this->l('Starting price'), 'type' => 'price', 'align' => 'right' ), 'final_price' => array( 'title' => $this->l('Final price'), 'type' => 'price', 'align' => 'right' ), 'email' => array( 'title' => $this->l('Winner') ) ); $this->loadObject(true); if (Validate::isLoadedObject($this->object)) { $this->object->setDateTimeFormatter(new FormattedAuctionsDateTime($this->module)); $this->id_product = $this->object->id_product; } } public function initPageHeaderToolbar() { parent::initPageHeaderToolbar(); unset($this->page_header_toolbar_btn['new']); // Default cancel button - like old back link $back = Tools::safeOutput(Tools::getValue('back', '')); if (empty($back)) { if ($this->display == 'view') $back = $this->context->link->getAdminLink('AdminAuctionsArchived'); else $back = $this->context->link->getAdminLink('AdminAuctions'); } if (!Validate::isCleanHtml($back)) die(Tools::displayError()); $this->page_header_toolbar_btn['back'] = array( 'href' => $back, 'desc' => $this->l('Back to list') ); } public function initToolbar() { parent::initToolbar(); unset($this->toolbar_btn['new']); // Default cancel button - like old back link $back = Tools::safeOutput(Tools::getValue('back', '')); if (empty($back)) { if ($this->display == 'view') $back = $this->context->link->getAdminLink('AdminAuctionsArchived'); else $back = $this->context->link->getAdminLink('AdminAuctions'); } if (!Validate::isCleanHtml($back)) die(Tools::displayError()); $this->toolbar_btn['back'] = array( 'href' => $back, 'desc' => $this->l('Back to list') ); } public function renderList() { $this->addRowAction('view'); return parent::renderList(); } public function renderView() { if (Validate::isLoadedObject($this->object)) { $this->tpl_view_vars = array( 'auction' => $this->object ); } return parent::renderView(); } public function viewAccess($disable = false) { if (!Module::isInstalled('agilemultipleseller')) return parent::viewAccess($disable); $eaccess = AgileSellerManager::get_entity_access($this->product_table); if ($this->is_seller && $this->id_product) { $id_owner = AgileSellerManager::getObjectOwnerID($this->product_table, $this->id_product); if ($id_owner > 0 || $eaccess['is_exclusive']) if (!AgileSellerManager::hasOwnership($this->product_table, $this->id_product)) return false; } if ($disable) return true; if ($this->tabAccess['view'] === '1') return true; return false; } public function processSave() { if (!$this->can_edit()) { $this->errors[] = Tools::displayError('You do not have permission to access this data'); return false; } return parent::processSave(); } public function processDelete() { if (!$this->can_edit()) { $this->errors[] = Tools::displayError('You do not have permission to delete this data'); return false; } return parent::processDelete(); } private function can_edit() { if (!Module::isInstalled('agilemultipleseller')) return true; if (!$this->is_seller) return true; $eaccess = AgileSellerManager::get_entity_access($this->product_table); if (empty($eaccess['owner_xr_table'])) { if ($this->id_product < 1) return true; $has_ownership = AgileSellerManager::hasOwnership($this->product_table, $this->id_product); if ($this->id_product > 0) return $has_ownership; if (Tools::getIsset('submitAdd'.$this->product_table) && $this->id_product == 0) return true; return false; } else { $has_ownership = AgileSellerManager::hasOwnership($eaccess['owner_xr_table'], $this->id_product); return $has_ownership; } } protected function agilemultipleseller_list_override() { $table = $this->table; $this->table = $this->product_table; parent::agilemultipleseller_list_override(); $this->table = $table; } } <file_sep><?php require_once "GetAdvertisementClickUrlResult.php"; require_once "GetAdvertisementClickUrlResultHandler.php"; require_once "GetAdvertisementClickUrlParam.php"; require_once "RequestTemplate.php"; /** * GetAdvertisementClickUrl request handler * * @package prediggo4php * @subpackage requests * * @author Stef */ class GetAdvertisementClickUrlRequest extends RequestTemplate { /** * Constructs a new request * @param GetAdvertisementClickUrlParam $param this query parameter object */ function __construct( GetAdvertisementClickUrlParam $param ) { parent::__construct( $param); } /** * Creates a key value array of the parameters that need to be passed by url. * @return array A key value map. */ protected function getArgumentMap() { $argMap = parent::getArgumentMap(); //parameters $this->addParameterToMap($argMap, "clickID", $this->parameter->getClickID()); return $argMap; } /** * Creates a result object of appropriate type for this request. * @return GetAdvertisementClickUrlResult A result object. */ protected function createResponseObject() { return new GetAdvertisementClickUrlResult(); } /** * Gets an appropriate result handler for this request. * @return GetAdvertisementClickUrlResultHandler An appropriate result handler for this request. */ protected function getResultHandler() { return new GetAdvertisementClickUrlResultHandler(); } /** * Gets the name of the servlet which serves this kind of request on prediggo side. * @return string The name of the servlet */ protected function getServletName() { return "/mock/GetAdvertisementClickID"; } } <file_sep><?php /** * 2007-2014 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ require_once(_PS_MODULE_DIR_.'prediggo/classes/PrediggoConfig.php'); require_once(_PS_MODULE_DIR_.'prediggo/classes/PrediggoCall.php'); class PrediggoCallController { /** @var PrediggoConfig Object PrediggoConfig */ protected $oPrediggoConfig; /** @var array list of the page where prediggo will be displayed */ private $aPagesAccessible; /** @var string current page name */ protected $sPageName; /** @var PrediggoCall Object PrediggoCall */ private $oPrediggoCall; /** @var string path of the log repository */ private $sRepositoryPath; /** @var string current Hook name */ private $sHookName; /** * Initialise the object variables */ public function __construct() { $this->oPrediggoConfig = new PrediggoConfig(Context::getContext()); $this->sRepositoryPath = _PS_MODULE_DIR_.'prediggo/logs/'; $this->setPagesAccessible(); $this->setPageName(); } /** * Execute a notification to prediggo * * @param string $sType Type of the notification * @param array $params list of specific parameters * @return bool */ public function notifyPrediggo($sType, $params) { //echo '<br><br>ENTERING NOTIFY PRDIGGO OF CLICK<br><br>' ; if (!$this->oPrediggoConfig->web_site_id_checked) return false; //echo '<br><br>NOTIFY PRDIGGO OF CLICK<br><br>' ; $this->oPrediggoCall = new PrediggoCall($this->oPrediggoConfig->web_site_id, $this->oPrediggoConfig->server_url_recommendations); switch ($sType) { case 'user' : $this->oPrediggoCall->setUserRegistered($params); break; case 'product' : $this->oPrediggoCall->setProductNotification($params); break; default : break; } if ($this->oPrediggoConfig->logs_generation) $this->setNotificationsLogFile($sType, $this->oPrediggoCall->getLogs()); } /** * Make the home page recommendation ONLY if the hook matches */ public function homePageRecoIfHookMatch($sHookName, $params, $oPrediggoCall) { $aRecommendations = array(); if ((boolean)$this->oPrediggoConfig->home_0_activated && strcmp($this->oPrediggoConfig->home_0_hook_name, $sHookName) == 0) { //echo 'Home Page Block #0 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->home_0_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->home_0_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->home_0_variant_id; $params['template_name'] = $this->oPrediggoConfig->home_0_template_name; $reco_block0 = $oPrediggoCall->getHomePageRecommendation($params); $reco_block0['block_title'] = $params['block_title']; $reco_block0['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block0); } if ((boolean)$this->oPrediggoConfig->home_1_activated && strcmp($this->oPrediggoConfig->home_1_hook_name, $sHookName) == 0) { //echo 'Home Page Block #1 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->home_1_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->home_1_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->home_1_variant_id; $params['template_name'] = $this->oPrediggoConfig->home_1_template_name; $reco_block1 = $oPrediggoCall->getHomePageRecommendation($params); $reco_block1['block_title'] = $params['block_title']; $reco_block1['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block1); } return $aRecommendations; } /** * Make the all page recommendation ONLY if the hook matches */ public function allPageRecoIfHookMatch($sHookName, $params, $oPrediggoCall) { $aRecommendations = array(); if ((boolean)$this->oPrediggoConfig->allpage_0_activated && strcmp($this->oPrediggoConfig->allpage_0_hook_name, $sHookName) == 0) { //echo 'All Page Block #0 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->allpage_0_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->allpage_0_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->allpage_0_variant_id; $params['template_name'] = $this->oPrediggoConfig->allpage_0_template_name; $reco_block0 = $oPrediggoCall->getHomePageRecommendation($params); $reco_block0['block_title'] = $params['block_title']; $reco_block0['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block0); } if ((boolean)$this->oPrediggoConfig->allpage_1_activated && strcmp($this->oPrediggoConfig->allpage_1_hook_name, $sHookName) == 0) { //echo 'All Page Block #1 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->allpage_1_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->allpage_1_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->allpage_1_variant_id; $params['template_name'] = $this->oPrediggoConfig->allpage_1_template_name; $reco_block1 = $oPrediggoCall->getHomePageRecommendation($params); $reco_block1['block_title'] = $params['block_title']; $reco_block1['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block1); } if ((boolean)$this->oPrediggoConfig->allpage_2_activated && strcmp($this->oPrediggoConfig->allpage_2_hook_name, $sHookName) == 0) { //echo 'All Page Block #2 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->allpage_2_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->allpage_2_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->allpage_2_variant_id; $params['template_name'] = $this->oPrediggoConfig->allpage_2_template_name; $reco_block2 = $oPrediggoCall->getHomePageRecommendation($params); $reco_block2['block_title'] = $params['block_title']; $reco_block2['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block2); } return $aRecommendations; } /** * Make the Product page recommendation ONLY if the hook matches */ public function productPageRecoIfHookMatch($sHookName, $params, $oPrediggoCall) { $aRecommendations = array(); if ((boolean)$this->oPrediggoConfig->productpage_0_activated && strcmp($this->oPrediggoConfig->productpage_0_hook_name, $sHookName) == 0) { //echo 'Product Page Block #0 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->productpage_0_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->productpage_0_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->productpage_0_variant_id; $params['template_name'] = $this->oPrediggoConfig->productpage_0_template_name; $reco_block0 = $oPrediggoCall->getProductPageRecommendation($params); $reco_block0['block_title'] = $params['block_title']; $reco_block0['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block0); } if ((boolean)$this->oPrediggoConfig->productpage_1_activated && strcmp($this->oPrediggoConfig->productpage_1_hook_name, $sHookName) == 0) { //echo 'Product Page Block #1 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->productpage_1_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->productpage_1_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->productpage_1_variant_id; $params['template_name'] = $this->oPrediggoConfig->productpage_1_template_name; //echo 'Template name'.$params['template_name'].'<BR>'; $reco_block1 = $oPrediggoCall->getProductPageRecommendation($params); $reco_block1['block_title'] = $params['block_title']; $reco_block1['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block1); } if ((boolean)$this->oPrediggoConfig->productpage_2_activated && strcmp($this->oPrediggoConfig->productpage_2_hook_name, $sHookName) == 0) { //echo 'Product Page Block #2 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->productpage_2_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->productpage_2_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->productpage_2_variant_id; $params['template_name'] = $this->oPrediggoConfig->productpage_2_template_name; $reco_block2 = $oPrediggoCall->getProductPageRecommendation($params); $reco_block2['block_title'] = $params['block_title']; $reco_block2['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block2); } return $aRecommendations; } /** * Make the basket page recommendation ONLY if the hook matches */ public function basketPageRecoIfHookMatch($sHookName, $params, $oPrediggoCall) { $aRecommendations = array(); if ((boolean)$this->oPrediggoConfig->basket_0_activated && strcmp($this->oPrediggoConfig->basket_0_hook_name, $sHookName) == 0) { //echo 'Home Page Block #0 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->basket_0_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->basket_0_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->basket_0_variant_id; $params['template_name'] = $this->oPrediggoConfig->basket_0_template_name; $reco_block0 = $oPrediggoCall->getBasketPageRecommendation($params); $reco_block0['block_title'] = $params['block_title']; $reco_block0['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block0); } if ((boolean)$this->oPrediggoConfig->basket_1_activated && strcmp($this->oPrediggoConfig->basket_1_hook_name, $sHookName) == 0) { //echo 'Basket Page Block #1 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->basket_1_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->basket_1_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->basket_1_variant_id; $params['template_name'] = $this->oPrediggoConfig->basket_1_template_name; $reco_block1 = $oPrediggoCall->getBasketPageRecommendation($params); $reco_block1['block_title'] = $params['block_title']; $reco_block1['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block1); } if ((boolean)$this->oPrediggoConfig->basket_2_activated && strcmp($this->oPrediggoConfig->basket_2_hook_name, $sHookName) == 0) { //echo 'Home Page Block #2 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->basket_2_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->basket_2_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->basket_2_variant_id; $params['template_name'] = $this->oPrediggoConfig->basket_2_template_name; $reco_block2 = $oPrediggoCall->getBasketPageRecommendation($params); $reco_block2['block_title'] = $params['block_title']; $reco_block2['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block2); } if ((boolean)$this->oPrediggoConfig->basket_3_activated && strcmp($this->oPrediggoConfig->basket_3_hook_name, $sHookName) == 0) { //echo 'Basket Page Block #3 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->basket_3_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->basket_3_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->basket_3_variant_id; $params['template_name'] = $this->oPrediggoConfig->basket_3_template_name; $reco_block3 = $oPrediggoCall->getBasketPageRecommendation($params); $reco_block3['block_title'] = $params['block_title']; $reco_block3['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block3); } if ((boolean)$this->oPrediggoConfig->basket_4_activated && strcmp($this->oPrediggoConfig->basket_4_hook_name, $sHookName) == 0) { //echo 'Basket Page Block #4 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->basket_4_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->basket_4_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->basket_4_variant_id; $params['template_name'] = $this->oPrediggoConfig->basket_4_template_name; $reco_block4 = $oPrediggoCall->getBasketPageRecommendation($params); $reco_block4['block_title'] = $params['block_title']; $reco_block4['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block4); } if ((boolean)$this->oPrediggoConfig->basket_5_activated && strcmp($this->oPrediggoConfig->basket_5_hook_name, $sHookName) == 0) { //echo 'Basket Page Block #4 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->basket_5_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->basket_5_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->basket_5_variant_id; $params['template_name'] = $this->oPrediggoConfig->basket_5_template_name; $reco_block4 = $oPrediggoCall->getBasketPageRecommendation($params); $reco_block4['block_title'] = $params['block_title']; $reco_block4['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block4); } return $aRecommendations; } /** * create the add condition for a category page or manufacturer page * return an array of two dimension [0] att name [1] value */ public function createAddCondition($params) { $res = array(); $value = null; if ($this->sPageName == $this->oPrediggoConfig->categoryPageName) { $value = new Category((int)Tools::getValue('id_category'), (int)$params['cookie']->id_lang); array_push($res, $this->oPrediggoConfig->attNameCategory); array_push($res, $value->getName((int)$params['cookie']->id_lang)); } else if ($this->sPageName == $this->oPrediggoConfig->manufacturerPageName) { array_push($res, $this->oPrediggoConfig->attNameManufacturer); array_push($res, (int)Tools::getValue('id_manufacturer')); } return $res; } /** * Make the Category page recommendation ONLY if the hook matches */ public function categoryPageRecoIfHookMatch($sHookName, $params, $oPrediggoCall) { $aRecommendations = array(); if ((boolean)$this->oPrediggoConfig->category_0_activated && strcmp($this->oPrediggoConfig->category_0_hook_name, $sHookName) == 0) { //echo 'Category Page Block #0 is active => computing recommendation,nb reco:'.(int)$this->oPrediggoConfig->category_0_nb_items.'<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->category_0_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->category_0_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->category_0_variant_id; $params['template_name'] = $this->oPrediggoConfig->category_0_template_name; //add the condition of the category or manufacturer $params['condition'] = $this->createAddCondition($params); $reco_block0 = $oPrediggoCall->getCategoryPageRecommendation($params); $reco_block0['block_title'] = $params['block_title']; $reco_block0['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block0); } if ((boolean)$this->oPrediggoConfig->category_1_activated && strcmp($this->oPrediggoConfig->category_1_hook_name, $sHookName) == 0) { //echo 'Category Page Block #1 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->category_1_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->category_1_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->category_1_variant_id; $params['template_name'] = $this->oPrediggoConfig->category_1_template_name; //add the condition of the category or manufacturer $params['condition'] = $this->createAddCondition($params); $reco_block1 = $oPrediggoCall->getCategoryPageRecommendation($params); $reco_block1['block_title'] = $params['block_title']; $reco_block1['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block1); } if ((boolean)$this->oPrediggoConfig->category_2_activated && strcmp($this->oPrediggoConfig->category_2_hook_name, $sHookName) == 0) { //echo 'Category Page Block #2 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->category_2_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->category_2_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->category_2_variant_id; $params['template_name'] = $this->oPrediggoConfig->category_2_template_name; //add the condition of the category or manufacturer $params['condition'] = $this->createAddCondition($params); $reco_block2 = $oPrediggoCall->getCategoryPageRecommendation($params); $reco_block2['block_title'] = $params['block_title']; $reco_block2['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block2); } return $aRecommendations; } /** * Make the Category page recommendation ONLY if the hook matches */ public function customerPageRecoIfHookMatch($sHookName, $params, $oPrediggoCall) { $aRecommendations = array(); $this->oPrediggoConfig->customer_0_hook_name = 'displayCustomerAccount'; if ((boolean)$this->oPrediggoConfig->customer_0_activated && strcmp($this->oPrediggoConfig->customer_0_hook_name, $sHookName) == 0) { //echo 'Customer Page Block #0 is active => computing recommendation,nb reco:'.(int)$this->oPrediggoConfig->customer_0_nb_items.'<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->customer_0_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->customer_0_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->customer_0_variant_id; $params['template_name'] = $this->oPrediggoConfig->customer_0_template_name; //add the condition of the customer or manufacturer $params['condition'] = $this->createAddCondition($params); $reco_block0 = $oPrediggoCall->getCustomerPageRecommendation($params); $reco_block0['block_title'] = $params['block_title']; $reco_block0['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block0); } if ((boolean)$this->oPrediggoConfig->customer_1_activated && strcmp($this->oPrediggoConfig->customer_1_hook_name, $sHookName) == 0) { //echo 'Customer Page Block #1 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->customer_1_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->customer_1_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->customer_1_variant_id; $params['template_name'] = $this->oPrediggoConfig->customer_1_template_name; //add the condition of the customer or manufacturer $params['condition'] = $this->createAddCondition($params); $reco_block1 = $oPrediggoCall->getCustomerPageRecommendation($params); $reco_block1['block_title'] = $params['block_title']; $reco_block1['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block1); } if ((boolean)$this->oPrediggoConfig->customer_2_activated && strcmp($this->oPrediggoConfig->customer_2_hook_name, $sHookName) == 0) { //echo 'Customer Page Block #2 is active => computing recommendation<BR>'; $params['nb_items'] = (int)$this->oPrediggoConfig->customer_2_nb_items; $params['block_title'] = pSQL($this->oPrediggoConfig->customer_2_block_label[(int)$params['cookie']->id_lang]); $params['variant_id'] = (int)$this->oPrediggoConfig->customer_2_variant_id; $params['template_name'] = $this->oPrediggoConfig->customer_2_template_name; //add the condition of the customer or manufacturer $params['condition'] = $this->createAddCondition($params); $reco_block2 = $oPrediggoCall->getCustomerPageRecommendation($params); $reco_block2['block_title'] = $params['block_title']; $reco_block2['block_template'] = $params['template_name']; if ($this->oPrediggoConfig->logs_generation) $this->setRecommendationsLogFile($sHookName, $oPrediggoCall->getLogs()); array_push($aRecommendations, $reco_block2); } return $aRecommendations; } /** * Get the list of recommendations by hook * * @param string $sHookName Name of the hook * @param array $params list of specific parameters * @return array $aRecommendations list of products */ public function getListOfRecommendationsWithDynamicTemplate($sHookName, $params) { if (!$this->oPrediggoConfig->web_site_id_checked) //echo '<H1>Prediggo Module is not activated, please contact Prediggo</H1><br>'; return false; $this->oPrediggoCall = new PrediggoCall($this->oPrediggoConfig->web_site_id, $this->oPrediggoConfig->server_url_recommendations); $aRecommendations = false; //echo 'getListOfRecommendationsWithDynamicTemplate()- Page name:'.$this->sPageName.', hookName='.$sHookName.'<BR>'; if ($sHookName == 'displayHome' || $sHookName == 'displayOrderConfirmation') return $this->homePageRecoIfHookMatch($sHookName, $params, $this->oPrediggoCall); else if ($sHookName == 'displayRightColumn' || $sHookName == 'displayLeftColumn' || $sHookName == 'displayTop' || $sHookName == 'displayFooter') return $this->allPageRecoIfHookMatch($sHookName, $params, $this->oPrediggoCall); else if ($sHookName == 'displayLeftColumnProduct' || $sHookName == 'displayRightColumnProduct' || $sHookName == 'displayProductButtons' || $sHookName == 'actionProductOutOfStock' || $sHookName == 'displayFooterProduct' || $sHookName == 'displayProductTab' || $sHookName == 'displayProductTabContent') return $this->productPageRecoIfHookMatch($sHookName, $params, $this->oPrediggoCall); else if ($sHookName == 'displayShoppingCartFooter' || $sHookName == 'displayShoppingCart' || $sHookName == 'displayOrderDetail' || $sHookName == 'displayBeforeCarrier' || $sHookName == 'displayCarrierList') return $this->basketPageRecoIfHookMatch($sHookName, $params, $this->oPrediggoCall); else if ($sHookName == 'displayRightColumncategory' || $sHookName == 'displayLeftColumncategory' || $sHookName == 'displayTopcategory' || $sHookName == 'displayFootercategory' || $sHookName == 'displayRightColumnmanufacturer' || $sHookName == 'displayLeftColumnmanufacturer' || $sHookName == 'displayTopmanufacturer' || $sHookName == 'displayFootemanufacturer') return $this->categoryPageRecoIfHookMatch($sHookName, $params, $this->oPrediggoCall); else if ($sHookName == 'displayCustomerAccount' || $sHookName == 'displayMyAccountBlock' || $sHookName == 'displayMyAccountBlockfooter') return $this->customerPageRecoIfHookMatch($sHookName, $params, $this->oPrediggoCall); return $aRecommendations; } /** * Set the array $aPagesAccessible with the page accessible */ public function setPagesAccessible() { $this->aPagesAccessible = array(); if ($this->oPrediggoConfig->home_recommendations) $this->aPagesAccessible[] = 'index'; if ($this->oPrediggoConfig->error_recommendations) $this->aPagesAccessible[] = '404'; if ($this->oPrediggoConfig->product_recommendations) $this->aPagesAccessible[] = 'product'; if ($this->oPrediggoConfig->category_recommendations) $this->aPagesAccessible[] = 'category'; if ($this->oPrediggoConfig->customer_recommendations) { $this->aPagesAccessible[] = 'my-account'; $this->aPagesAccessible[] = 'addresses'; $this->aPagesAccessible[] = 'history'; $this->aPagesAccessible[] = 'order-return'; $this->aPagesAccessible[] = 'manufacturer'; } if ($this->oPrediggoConfig->cart_recommendations) { $this->aPagesAccessible[] = 'order'; $this->aPagesAccessible[] = 'order-opc'; } if ($this->oPrediggoConfig->best_sales_recommendations) $this->aPagesAccessible[] = 'best-sales'; if ($this->oPrediggoConfig->blocklayered_recommendations) $this->aPagesAccessible[] = 'blocklayered'; } /** * Set the current page name and store it to the object var $sPageName * You must update this function base on your URL rewrite policy (you must write it in the PrediggoCallControllerOverride) * The page name is then used to select which type of recommendation bloc to use (GetItemReco,...) */ public function setPageName() { $context = $this->oPrediggoConfig->getContext(); $controller = $context->controller->php_self; $this->sPageName = $controller; //echo 'controller:'.$this->sPageName; return true; } /** * Update the current $sPageName */ public function _setPageName($sPageName) { $this->sPageName = $sPageName; } /** * You must update this function base on your module of pop-in cart if you have one */ public function popInCart() { } public function variantId() { } /** * Check if the current page is accessible (prediggo blocks can be displayed ?) * @return bool is accessible or not */ public function isPageAccessible() { return in_array($this->sPageName, $this->aPagesAccessible); } /** * Add the new logs list to the recommendations log file * * @param string $sHookName Name of the hook * @param array $aLogs list of logs * @return bool */ private function setRecommendationsLogFile($sHookName, $aLogs) { if (!count($aLogs)) return false; $sEntityLogFileName = $this->sRepositoryPath.'log_fo-'.$this->sPageName.'.txt'; $aLogs[0] .= ' {'.$sHookName.'}'; if ($handle = fopen($sEntityLogFileName, 'a')) { foreach ($aLogs as $sLog) fwrite($handle, $sLog."\n"); fclose($handle); } } /** * Add the new logs list to the notifications log file * * @param $sName * @param array $aLogs list of logs * @internal param string $sHookName Name of the hook */ private function setNotificationsLogFile($sName, $aLogs) { $sEntityLogFileName = $this->sRepositoryPath.'log_notification-'.$sName.'.txt'; $aLogs[0] .= ' {'.$sName.'}'; if ($handle = fopen($sEntityLogFileName, 'a')) { foreach ($aLogs as $sLog) fwrite($handle, $sLog."\n"); fclose($handle); } } /** * Export the client Configuration * * @return Client export configuration file from Db */ public function export_client_config() { $sql = 'SELECT * FROM `'._DB_PREFIX_.'configuration`'.' WHERE `name` LIKE \'PREDIGGO_%\''; $sql2 = 'SELECT cl.* FROM `'._DB_PREFIX_.'configuration_lang` cl, `'._DB_PREFIX_.'configuration` c '.'WHERE c.`id_configuration` = cl.`id_configuration` and c.`name` LIKE \'PREDIGGO_%\' ORDER BY cl.`id_configuration` ASC'; $fp = fopen(_PS_MODULE_DIR_.'prediggo/xmlfiles/export_configuration.sql', 'w'); $fp2 = fopen(_PS_MODULE_DIR_.'prediggo/xmlfiles/export_configuration_lang.sql', 'w'); $aQueryResult = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql2); foreach ($aQueryResult as $row) { $row['value'] = (empty($row['value'])) ? 'NULL' : $row['value']; fputs($fp2, 'UPDATE `'._DB_PREFIX_.'configuration_lang` SET `id_configuration` = '.$row['id_configuration'].',`id_lang` = '.$row['id_lang'].',`value` = \''.$row['value'].'\''.',`date_upd` = \''.$row['date_upd'].'\''.' WHERE `'._DB_PREFIX_.'configuration_lang`.`id_configuration` = '.$row['id_configuration'].' AND `'. _DB_PREFIX_.'configuration_lang`.`id_lang` = '.$row['id_lang'].';'."\r"); } $aQueryResult = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql); foreach ($aQueryResult as $row) { $row['id_shop_group'] = (empty($row['id_shop_group'])) ? 'NULL' : $row['id_shop_group']; $row['id_shop'] = (empty($row['id_shop'])) ? 'NULL' : $row['id_shop']; $row['value'] = (empty($row['value'])) ? 'NULL' : $row['value']; fputs($fp, 'UPDATE `'._DB_PREFIX_.'configuration` SET `id_configuration` = '.$row['id_configuration'].',`id_shop_group` = '.$row['id_shop_group'].',`id_shop` = '.$row['id_shop'].',`name` = \''.$row['name'].'\''.',`value` = \''.$row['value'].'\',`date_add` = \''.$row['date_add'].'\',`date_upd` = \''.$row['date_upd'].'\''.' WHERE `'._DB_PREFIX_.'configuration`.`id_configuration` = '.$row['id_configuration'].';'."\r"); } fclose($fp); fclose($fp2); unset($aQueryResult); } /** * Import the client Configuration * * @param File For the Import * @return Client import configuration file from Db */ public function import_client_config() { //$sql = 'DELETE FROM `'._DB_PREFIX_.'configuration`'.' WHERE `name` LIKE \'PREDIGGO_%\''; //$aQueryResult = Db::getInstance(_PS_USE_SQL_SLAVE_)->execute($sql); //unset($aQueryResult); $fp = fopen(_PS_MODULE_DIR_.'prediggo/xmlfiles/import.sql', 'r'); //$fpr = ""; while (!feof($fp)) { $fpr = fgets($fp); if (Db::getInstance(_PS_USE_SQL_SLAVE_)->execute($fpr)); } } /** * Import the client Configuration * * @param File For the Import * @return Client import configuration file from Db */ public function import_client_config2() { //$sql2 = 'DELETE FROM `'._DB_PREFIX_.'configuration_lang`'.'WHERE `id_configuration` in (select `id_configuration` FROM `'._DB_PREFIX_.'configuration` WHERE `name` LIKE \'PREDIGGO_%\')'; //$aQueryResult2 = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql2); //unset($aQueryResult2); $fp2 = fopen(_PS_MODULE_DIR_.'prediggo/xmlfiles/import2.sql', 'r'); //$fpr2 = ""; while (!feof($fp2)) { $fpr2 = fgets($fp2); if (Db::getInstance(_PS_USE_SQL_SLAVE_)->execute($fpr2)); } } /** * Get the current page name */ public function getPageName() { return $this->sPageName; } /** * Check the client web site id */ public function checkWebSiteId() { // Check if default web_site_id if ($this->oPrediggoConfig->web_site_id == 'WineDemo_Fake_Shop_ID_123456789') return false; $this->oPrediggoConfig = new PrediggoConfig(Context::getContext()); $this->oPrediggoCall = new PrediggoCall($this->oPrediggoConfig->web_site_id, $this->oPrediggoConfig->server_url_recommendations); return $this->oPrediggoCall->checkWebSiteId(); } /** * Check the client web site id */ public function checkLicence() { $this->oPrediggoConfig = new PrediggoConfig(Context::getContext()); $this->oPrediggoCall = new PrediggoCall($this->oPrediggoConfig->shop_name, $this->oPrediggoConfig->token_id, $this->oPrediggoConfig->server_url_check); return $this->oPrediggoCall->checkLicence(); } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_20351b3328c35ab617549920f5cb4939'] = 'Personalizzazione #'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ed6e9a09a111035684bb23682561e12d'] = 'rimuovere questo prodotto dal mio carrello'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_c6995d6cc084c192bc2e742f052a5c74'] = 'Spedizione gratuita!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_e7a6ca4e744870d455a57b644f696457'] = 'Gratis!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f2a6c498fb90ee345d997f888fce3b18'] = 'Cancellare'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_a85eba4c6c699122b2bb1387ea4813ad'] = 'Carrello'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_86024cad1e83101d97359d7351051156'] = 'prodotti'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f5bf48aa40cad7891eb709fcf1fde128'] = 'prodotto'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(Vuoto)'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b7d496eedb665d0b5f589f2f874e7cb'] = 'Dettaglio prodotto'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_3d9e3bae9905a12dae384918ed117a26'] = 'Personalizzazione #% d:'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_09dc02ecbb078868a3a86dded030076d'] = 'Non ci sono prodotti'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ea9cf7e47ff33b2be14e6dd07cbcefc6'] = 'Spedizione'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ba794350deb07c0c96fe73bd12239059'] = 'Involucro'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b78ac8eb158840e9638a3aeb26c4a9d'] = 'Imposta'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_96b0141273eabab320119c467cdcaf17'] = 'Totale'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_0d11c2b75cf03522c8d97938490466b2'] = 'Totale'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_41202aa6b8cf7ae885644717dab1e8b4'] = 'I prezzi sono IVA esclusa'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_377e99e7404b414341a9621f7fb3f906'] = 'Scopri'; <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class AdminPowaTagConfigurationController extends ModuleAdminController { public function __construct() { $this->table = 'powatag_configuration'; $this->lang = false; $this->_select = null; //If needed you can add informations to select issued from other databases $this->_join = null; //Join the databases here parent::__construct(); $this->bootstrap = true; $this->fields_options = array( 'api_settings' => array( 'title' => $this->l('API Settings'), 'image' => '../img/admin/prefs.gif', 'fields' => array( 'POWATAG_API_KEY' => array( 'title' => $this->l('API Key'), 'validation' => 'isString', 'type' => 'text', 'size' => '80', 'visibility' => Shop::CONTEXT_SHOP, 'required' => true, ), 'POWATAG_HMAC_KEY' => array( 'title' => $this->l('HMAC Key'), 'validation' => 'isString', 'type' => 'text', 'visibility' => Shop::CONTEXT_SHOP, 'size' => 80, 'required' => true, ), 'POWATAG_GENERATOR_URL' => array( 'title' => $this->l('Powatag Endpoint URL'), 'validation' => 'isString', 'type' => 'text', 'size' => 80, ), 'POWATAG_JS_URL' => array( 'title' => $this->l('Head JavaScript URL'), 'validation' => 'isString', 'type' => 'text', 'size' => 80, ), 'POWATAG_CSS_URL' => array( 'title' => $this->l('Head CSS URL'), 'validation' => 'isString', 'type' => 'text', 'size' => 80, ), 'POWATAG_LEGACY_ERRORS' => array( 'title' => $this->l('Legacy error codes enabled'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', 'visibility' => Shop::CONTEXT_SHOP, ), ), 'submit' => array('title' => $this->l('Save')), ), 'other_settings' => array( 'title' => $this->l('Other Settings'), 'image' => '../img/admin/tab-tools.gif', 'fields' => array( 'POWATAG_SHIPPING' => array( 'title' => $this->l('Shipping Method'), 'validation' => 'isInt', 'type' => 'select', 'identifier' => 'id_carrier', 'desc' => $this->l('This will be used to calculate shipping costs'), 'list' => Carrier::getCarriers($this->context->language->id, false, false, false, null, Carrier::ALL_CARRIERS), 'visibility' => Shop::CONTEXT_SHOP, 'required' => true, ), 'POWATAG_SUCCESS_MSG' => array( 'title' => $this->l('Sucess message'), 'validation' => 'isString', 'type' => 'textLang', 'size' => '80', 'visibility' => Shop::CONTEXT_SHOP, ), 'POWATAG_IMG_TYPE' => array( 'title' => $this->l('Image type to send'), 'validation' => 'isInt', 'type' => 'select', 'identifier' => 'id_image_type', 'list' => ImageType::getImagesTypes(), 'visibility' => Shop::CONTEXT_SHOP, 'required' => true, ), ), 'submit' => array('title' => $this->l('Save')), ), 'product_settings' => array( 'title' => $this->l('Product Settings'), 'image' => $this->module->getPathUri().'views/img/qr_code.png', 'fields' => array( 'POWATAG_QR' => array( 'title' => $this->l('QR Code enabled'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', 'visibility' => Shop::CONTEXT_SHOP, ), 'POWATAG_QR_POS' => array( 'title' => $this->l('QR code Position'), 'validation' => 'isString', 'type' => 'select', 'identifier' => 'key', 'list' => array( array('key' => 'displayRightColumnProduct', 'name' => $this->l('displayRightColumnProduct')), array('key' => 'displayLeftColumnProduct', 'name' => $this->l('displayLeftColumnProduct')), array('key' => 'displayFooterProduct', 'name' => $this->l('displayFooterProduct')), array('key' => 'displayProductButtons', 'name' => $this->l('displayProductButtons')), ), 'visibility' => Shop::CONTEXT_SHOP, ), 'POWATAG_SKU' => array( 'title' => $this->l('Which SKU field to use '), 'validation' => 'isInt', 'type' => 'select', 'identifier' => 'key', 'list' => array( array('key' => Powatag::EAN, 'name' => $this->l('EAN13 or JAN')), array('key' => Powatag::UPC, 'name' => $this->l('UPC')), array('key' => Powatag::PRODUCT_ID, 'name' => $this->l('Product ID')), array('key' => Powatag::REFERENCE, 'name' => $this->l('REFERENCE')), ), ), 'POWATAG_REDIRECT' => array( 'title' => $this->l('URL Redirect'), 'validation' => 'isString', 'type' => 'text', 'size' => 250, ), 'POWATAG_OFFER' => array( 'title' => $this->l('Promotional area'), 'validation' => 'isString', 'type' => 'text', 'size' => 250, ), 'POWATAG_LANG' => array( 'title' => $this->l('Language'), 'validation' => 'isString', 'type' => 'select', 'identifier' => 'key', 'list' => array( array('key' => '', 'name' => $this->l('Default')), array('key' => 'site', 'name' => $this->l('Use site language')), array('key' => 'en_GB', 'name' => $this->l('en_GB')), array('key' => 'es_ES', 'name' => $this->l('es_ES')), array('key' => 'fr_FR', 'name' => $this->l('fr_FR')), array('key' => 'it_IT', 'name' => $this->l('it_IT')), ), ), 'POWATAG_TYPE' => array( 'title' => $this->l('Type'), 'validation' => 'isString', 'type' => 'select', 'identifier' => 'key', 'list' => array( array('key' => '', 'name' => $this->l('Default')), array('key' => 'bag', 'name' => $this->l('Bag')), array('key' => 'mobile-button', 'name' => $this->l('Mobile button')), array('key' => 'tablet-bag', 'name' => $this->l('Tablet bag')), ), ), 'POWATAG_STYLE' => array( 'title' => $this->l('Style'), 'validation' => 'isString', 'type' => 'select', 'identifier' => 'key', 'list' => array( array('key' => '', 'name' => $this->l('Default')), array('key' => 'act-left', 'name' => $this->l('act-left')), array('key' => 'act-right', 'name' => $this->l('act-right')), array('key' => 'buy-left', 'name' => $this->l('buy-left')), array('key' => 'buy-right', 'name' => $this->l('buy-right')), array('key' => 'give-left', 'name' => $this->l('give-left')), array('key' => 'give-right', 'name' => $this->l('give-right')), array('key' => 'bg-act-left', 'name' => $this->l('bg-act-left')), array('key' => 'bg-act-right', 'name' => $this->l('bg-act-right')), array('key' => 'bg-buy-left', 'name' => $this->l('bg-buy-left')), array('key' => 'bg-buy-right', 'name' => $this->l('bg-buy-right')), array('key' => 'bg-give-left', 'name' => $this->l('bg-give-left')), array('key' => 'bg-give-right', 'name' => $this->l('bg-give-right')), ), ), 'POWATAG_COLORSCHEME' => array( 'title' => $this->l('Color scheme'), 'validation' => 'isString', 'type' => 'select', 'identifier' => 'key', 'list' => array( array('key' => '', 'name' => $this->l('Default')), array('key' => 'light', 'name' => $this->l('Light')), array('key' => 'dark', 'name' => $this->l('Dark')), ), ), 'POWATAG_DISPLAY' => array( 'title' => $this->l('Desktop / mobile'), 'validation' => 'isString', 'type' => 'select', 'identifier' => 'key', 'list' => array( array('key' => '', 'name' => $this->l('Default')), array('key' => 'both', 'name' => $this->l('Both')), array('key' => 'desktop-only', 'name' => $this->l('Desktop only')), array('key' => 'mobile-only', 'name' => $this->l('Mobile only')), ), ), 'POWATAG_VIDEO' => array( 'title' => $this->l('Video'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', ), 'POWATAG_DEBUG' => array( 'title' => $this->l('Developer mode'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', ), ), 'submit' => array('title' => $this->l('Save')), ), 'logs' => array( 'title' => $this->l('Logs'), 'image' => '../img/t/AdminLogs.gif', 'fields' => array( 'POWATAG_API_LOG' => array( 'title' => $this->l('Enable applicative logging'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', 'visibility' => Shop::CONTEXT_SHOP, ), 'POWATAG_REQUEST_LOG' => array( 'title' => $this->l('Enable request logging'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', 'visibility' => Shop::CONTEXT_SHOP, ), ), 'submit' => array('title' => $this->l('Save')), ), ); } public function setMedia() { parent::setMedia(); $this->addCSS($this->module->getPathUri().'views/css/backoffice.css'); } public function initToolbar() { $this->toolbar_btn = $this->module->initToolbar(); parent::initToolbar(); } public function initPageHeaderToolbar() { $this->page_header_toolbar_btn = $this->module->initToolbar(); parent::initPageHeaderToolbar(); } public function renderOptions() { $this->context->smarty->assign(array( 'marketing' => !Configuration::get('POWATAG_HMAC_KEY') || !Configuration::get('POWATAG_API_KEY'), )); $before = $this->module->display(dirname(__FILE__).'/../../'.$this->module->name.'.php', 'powatag_configuration_before.tpl'); $form = parent::renderOptions(); $after = $this->module->display(dirname(__FILE__).'/../../'.$this->module->name.'.php', 'powatag_configuration_after.tpl'); return $before.$form.$after; } public static function install($menu_id, $module_name, $lang_id, $module) { $tab = new Tab(); $tab->name[$lang_id] = $module->l('Configuration'); $tab->class_name = 'AdminPowaTagConfiguration'; $tab->module = $module_name; $tab->id_parent = $menu_id; if(!$tab->save()) { return false; } return true; } } <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class PowaTagPayment extends PowaTagAbstract { /** * Transaction ID. * * @var string */ private $bankAuthorizationCode; /** * Prestashop Cart. * * @var Cart */ private $cart; /** * Cart ID. * * @var int */ private $idCart; public function __construct(stdClass $datas, $idCart) { parent::__construct($datas); $this->idCart = (int) $idCart; $this->cart = new Cart((int) $idCart); } public function setBantAuthorizationCode() { $this->bankAuthorizationCode = isset($this->datas->paymentResult->bankAuthorizationCode) ? $this->datas->paymentResult->bankAuthorizationCode : ''; } public function validateOrder($orderState, $id_cart, $amountPaid, $message = null) { if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create order', PowaTagLogs::IN_PROGRESS, 'Cart ID : '.$id_cart); } $module = Module::getInstanceByName('powatag'); $cart = new Cart($id_cart); $customer = new Customer($cart->id_customer); if ($module->validateOrder((int) $id_cart, (int) $orderState, $amountPaid, $module->name, $message.$this->error['message'], array('transaction_id' => $this->bankAuthorizationCode), null, false, $customer->secure_key)) { if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create order', PowaTagLogs::SUCCESS, 'Order ID : '.$module->currentOrder); } return $module->currentOrder; } else { if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create order', PowaTagLogs::ERROR, 'FAIL'); } return false; } } public function confirmPayment($twoSteps = false) { $orderState = Configuration::get('PS_OS_PAYMENT'); if (!$this->cartEnabled()) { $orderState = Configuration::get('PS_OS_ERROR'); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('confirmPayment', PowaTagLogs::ERROR, 'cart not enabled'); } } if (!$this->error) { if (!$this->compareCustomer()) { $orderState = Configuration::get('PS_OS_ERROR'); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('confirmPayment', PowaTagLogs::ERROR, 'compareCustomer problem'); } } } if (!$this->error) { if (!$this->ifCarrierDeliveryZone(Configuration::get('POWATAG_SHIPPING'), false, $this->datas->customer->shippingAddress->country->alpha2Code)) { $orderState = Configuration::get('PS_OS_ERROR'); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('confirmPayment', PowaTagLogs::ERROR, 'ifCarrierDeliveryZone problem'); } } } if (!$twoSteps) { if (!$idTransaction = $this->transactionExists()) { $orderState = Configuration::get('PS_OS_ERROR'); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('confirmPayment', PowaTagLogs::ERROR, 'transactionExists problem'); } } } $amountPaid = $this->datas->paymentResult->amountTotal->amount; if (!$this->error) { if (!$this->checkTotalToPaid($amountPaid, $this->datas->paymentResult->amountTotal->currency)) { $orderState = (int) Configuration::get('PS_OS_ERROR'); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('confirmPayment', PowaTagLogs::ERROR, 'checkTotalToPaid problem'); } } } if (!$this->bankAuthorizationCode) { $this->setBantAuthorizationCode(); } if (!$twoSteps) { $transaction = new PowaTagTransaction((int) $idTransaction); $transaction->orderState = $orderState; } $currentOrderId = $this->validateOrder($orderState, $this->idCart, $amountPaid); if (!$twoSteps) { $transaction->id_order = $currentOrderId; $transaction->save(); } return $currentOrderId; } private function cartEnabled() { if (!Validate::isLoadedObject($this->cart)) { $this->addError(sprintf($this->module->l('Cart not exists : %s'), $this->idCart), PowaTagErrorType::$INVALID_CARD); return false; } if ($this->cart->orderExists()) { $this->addError(sprintf($this->module->l('Cart has already associated with order : %s'), $this->idCart), PowaTagErrorType::$INTERNAL_ERROR); return false; } return true; } private function compareCustomer() { $customerDatas = $this->getCustomerByEmail($this->datas->customer->emailAddress); if (!Validate::isLoadedObject($customerDatas)) { $this->addError(sprintf($this->module->l('The customer does not exists : %s'), $this->datas->customer->emailAddress), PowaTagErrorType::$INTERNAL_ERROR); return false; } $cartCustomer = new Customer((int) $this->cart->id_customer); if ($customerDatas->id != $cartCustomer->id) { $this->addError(sprintf($this->module->l('The information sent in the request are not identical to the one saved : %s != %s'), $customerDatas->id, $cartCustomer->id), PowaTagErrorType::$INTERNAL_ERROR); return false; } return true; } private function transactionExists() { $transactions = PowaTagTransaction::getTransactions((int) $this->idCart); if (!$transactions || !count($transactions)) { $this->addError(sprintf($this->module->l('No transaction found for, Cart ID : %s, Device ID : %s & IP : %s'), $this->idCart, $this->datas->device->deviceID, $this->datas->device->ipAddress), PowaTagErrorType::$INTERNAL_ERROR); return false; } if (count($transactions) > 1) { $this->addError(sprintf($this->module->l('Too many transaction for, Cart ID : %s, Device ID : %s & IP : %s'), $this->idCart, $this->datas->device->deviceID, $this->datas->device->ipAddress), PowaTagErrorType::$INTERNAL_ERROR); return false; } $transaction = current($transactions); return (int) $transaction['id_powatag_transaction']; } private function checkTotalToPaid($amountPaid, $currency) { if (!$currency instanceof Currency) { if (Validate::isInt($currency)) { $currency = new Currency((int) $currency); } else { $currencyCode = $currency; if (!$currency = self::getCurrencyByIsoCode($currency)) { $currency = $currencyCode; } } } if (!PowaTagValidate::currencyEnable($currency)) { $this->addError(sprintf($this->module->l('Currency is not enable : %s'), (isset($currency->iso_code) ? $currency->iso_code : $currency)), PowaTagErrorType::$CURRENCY_NOT_SUPPORTED); return false; } //We change context currency to be sure that calculs are made with correct currency $context = Context::getContext(); $context->currency = $currency; $context->country = $this->getCountry($this->datas->customer->shippingAddress->country->alpha2Code); $price_cart = $this->cart->getOrderTotal(true, Cart::BOTH, null, Configuration::get('POWATAG_SHIPPING')); if (abs($price_cart - $amountPaid) >= 0.01) { $msg = 'Cart: '.$price_cart.' != Payment: '.$amountPaid; $this->addError($this->module->l('Amount paid is not same as the cart: '.$msg), PowaTagErrorType::$INTERNAL_ERROR); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Amount paid is not same as the cart', PowaTagLogs::ERROR, $msg); } return false; } return true; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsProcessModuleFrontController', false)) return; class AuctionsProcessModuleFrontController extends CoreModuleCronController { protected $file_path = __FILE__; public function init() { $process_limit = $this->module->getSettings('AuctionsCronSettings')->getValue(AuctionsCronSettings::CRON_PROCESSING_NUMBER_ITEMS, AuctionsCronSettings::DEFAULT_CRON_PROCESSING_NUMBER_ITEMS); $product_auction_collection = ProductAuctionDataManager::getAuctionsToProcessCollection($process_limit, null, $this->context->language->id, $this->context->shop->id); $product_auction_item_collection = ProductAuctionItemFactory::getInstance($this->module)->makeFrontOfficeItems($product_auction_collection); foreach ($product_auction_item_collection as $product_auction_item) { $product_auction = $product_auction_item->getObjectModel(); $product_auction_type = $product_auction->getProductAuctionType(); $product_auction_mailing = $product_auction_type->getProductAuctionMailingManager($this->module); $product_auction_mailing->notifyParticipants($this->getParticipantsToNotify($product_auction)); $product_auction_mailing->notifySubscribers($this->getSubscribersToNotify($product_auction)); $product_auction_mailing->notifyEmployees($this->getAdministratorsToNotify($product_auction)); $product_auction_type->notify($product_auction_mailing); $product_auction_type->process($product_auction_item); } exit('SUCCESS'); } protected function getParticipantsToNotify(ProductAuction $product_auction) { return ProductAuctionOfferDataManager::getParticipantsCustomersCollectionByProductAuction($product_auction); } protected function getSubscribersToNotify(ProductAuction $product_auction) { if ($this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_WATCH_AUCTION)) return ProductAuctionSubscriptionDataManager::getSubscribersCustomersCollectionByProductAuction($product_auction); return array(); } protected function getAdministratorsToNotify(ProductAuction $product_auction) { $mailing_settings = $this->module->getSettings('AuctionsMailingSettings'); $employees = new Collection('Employee'); $employees->where('active', '=', 1); $employees->where('id_employee', 'IN', $mailing_settings->getValue(AuctionsMailingSettings::AUCTION_BACKOFFICE_EMPLOYEES)); return $employees->getResults(); } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_20351b3328c35ab617549920f5cb4939'] = ' Customization #'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ed6e9a09a111035684bb23682561e12d'] = 'Entfernen Sie das Gerät von meinem Warenkorb'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_c6995d6cc084c192bc2e742f052a5c74'] = 'Kostenloser Versand!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_e7a6ca4e744870d455a57b644f696457'] = 'Kostenlos!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f2a6c498fb90ee345d997f888fce3b18'] = 'löschen'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_a85eba4c6c699122b2bb1387ea4813ad'] = 'Wagen'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_86024cad1e83101d97359d7351051156'] = 'Produkte'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f5bf48aa40cad7891eb709fcf1fde128'] = 'Produkt'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(leer)'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b7d496eedb665d0b5f589f2f874e7cb'] = 'Produktdetail'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_3d9e3bae9905a12dae384918ed117a26'] = ' Customization #'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_09dc02ecbb078868a3a86dded030076d'] = 'Keine Produkte'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ea9cf7e47ff33b2be14e6dd07cbcefc6'] = 'Versand'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ba794350deb07c0c96fe73bd12239059'] = 'Verpackung'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b78ac8eb158840e9638a3aeb26c4a9d'] = 'Steuer'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_96b0141273eabab320119c467cdcaf17'] = 'Gesamt'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_0d11c2b75cf03522c8d97938490466b2'] = 'Preise inklusive Steuer'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_41202aa6b8cf7ae885644717dab1e8b4'] = 'Preise ohne MwSt.'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_377e99e7404b414341a9621f7fb3f906'] = 'überprüfen'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductDataManager', false)) return; class ProductDataManager { /** * @param integer $id_lang * @param integer $p * @param integer $n * @param string $order_by * @param string $order_way * @param string $get_total * @param string $active * @param string $random * @param integer $random_number_products * @param Context $context * @return number boolean array */ public static function getAllProductsCollectionForFilter($id_lang, $p, $n, $order_by = null, $order_way = null, $get_total = false, $active = true, $random = false, $random_number_products = 1, Context $context = null) { if (!$context) $context = Context::getContext(); $front = true; if (!in_array($context->controller->controller_type, array( 'front', 'modulefront' ))) $front = false; if ($p < 1) $p = 1; if (empty($order_by)) $order_by = 'id_product_auction'; else /* Fix for all modules which are now using lowercase values for 'orderBy' parameter */ $order_by = Tools::strtolower($order_by); if (empty($order_way)) $order_way = 'ASC'; if (empty($order_by) || $order_by == 'ending') $order_by = 'to'; if ($order_by == 'id_product') $order_by_prefix = 'p'; elseif ($order_by == 'name') $order_by_prefix = 'pl'; elseif ($order_by == 'from' || $order_by == 'to' || $order_by == 'ending' || $order_by == 'date_add' || $order_by == 'date_upd') $order_by_prefix = 'pa'; if ($order_by == 'price') $order_by = 'orderprice'; if (!Validate::isBool($active) || !Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)) die(Tools::displayError()); $id_supplier = (int)Tools::getValue('id_supplier'); $current_datetime = date('Y-m-d H:i:s'); /* Return only the number of products */ if ($get_total) { $sql = 'SELECT COUNT(p.`id_product`) AS total FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) INNER JOIN ( SELECT `id_product_auction`, CASE WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE `status` END AS `status` FROM `'._DB_PREFIX_.'product_auction` ) st ON (pa.`id_product_auction` = st.`id_product_auction`) '.Shop::addSqlAssociation('product', 'p').' WHERE 1 AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' '.($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').($active ? ' AND product_shop.`active` = 1' : '').($id_supplier ? 'AND p.id_supplier = '.(int)$id_supplier : '').' AND st.status IN ('.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } $sql = 'SELECT p.*, product_shop.*, stock.out_of_stock, IFnull(stock.quantity, 0) as quantity, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(product_shop.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new, (product_shop.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice, TIMESTAMPDIFF(SECOND, \''.$current_datetime.'\', pa.`to`) AS ending, CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status`, IF(pa.status = '.ProductAuction::STATUS_FINISHED.', 1, 0) as finished FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) '.Shop::addSqlAssociation('product', 'p').' '.Product::sqlStock('p', 0, false, $context->shop).' LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('pl').') LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (product_shop.`id_tax_rules_group` = tr.`id_tax_rules_group` AND tr.`id_country` = '.(int)$context->country->id.' AND tr.`id_state` = 0 AND tr.`zipcode_from` = 0) LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`) LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` WHERE product_shop.`id_shop` = '.(int)$context->shop->id.' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' '.($active ? ' AND product_shop.`active` = 1' : '').($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').($id_supplier ? ' AND p.id_supplier = '.(int)$id_supplier : '').' HAVING auction_status IN ('.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; if ($random === true) { $sql .= ' ORDER BY RAND()'; $sql .= ' LIMIT 0, '.(int)$random_number_products; } else { if ($order_by == 'finished') { $sql .= ' ORDER BY IF(`auction_status` = '.ProductAuction::STATUS_FINISHED.', 1, 0) '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } else { $sql .= ' ORDER BY '.(isset($order_by_prefix) ? $order_by_prefix.'.' : '').'`'.pSQL($order_by).'` '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } } $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); if ($order_by == 'orderprice') Tools::orderbyPrice($result, $order_way); if (!$result) return array(); /* Modify SQL result */ return Product::getProductsProperties($id_lang, $result); } /** * @param integer $id_lang * @param integer $p * @param integer $n * @param string $order_by * @param string $order_way * @param string $get_total * @param string $active * @param string $random * @param integer $random_number_products * @param Context $context * @return number boolean array */ public static function getCollectionByAuctionCategory($category_id, $id_lang, $p, $n, $order_by = null, $order_way = null, $get_total = false, $active = true, $random = false, $random_number_products = 1, Context $context = null) { if (empty($category_id)) return array(); if (!$context) $context = Context::getContext(); $front = true; if (!in_array($context->controller->controller_type, array( 'front', 'modulefront' ))) $front = false; if ($p < 1) $p = 1; if (empty($order_by)) $order_by = 'id_product_auction'; else /* Fix for all modules which are now using lowercase values for 'orderBy' parameter */ $order_by = Tools::strtolower($order_by); if (empty($order_way)) $order_way = 'ASC'; if (empty($order_by) || $order_by == 'ending') $order_by = 'to'; if ($order_by == 'id_product') $order_by_prefix = 'p'; elseif ($order_by == 'name') $order_by_prefix = 'pl'; elseif ($order_by == 'position') $order_by_prefix = 'cp'; elseif ($order_by == 'from' || $order_by == 'to' || $order_by == 'ending' || $order_by == 'date_add' || $order_by == 'date_upd') $order_by_prefix = 'pa'; if ($order_by == 'price') $order_by = 'orderprice'; if (!Validate::isBool($active) || !Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)) die(Tools::displayError()); $current_datetime = date('Y-m-d H:i:s'); /* Return only the number of products */ if ($get_total) { $sql = 'SELECT COUNT(p.`id_product`) AS total FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) INNER JOIN ( SELECT `id_product_auction`, CASE WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE `status` END AS `status` FROM `'._DB_PREFIX_.'product_auction` ) st ON (pa.`id_product_auction` = st.`id_product_auction`) LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON pa.`id_product` = cp.`id_product` '.Shop::addSqlAssociation('product', 'p').' WHERE 1 AND cp.`id_category` = '.(int)$category_id.' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' '.($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').($active ? ' AND product_shop.`active` = 1' : '').' AND st.status IN ('.ProductAuction::STATUS_IDLE.', '.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } $sql = 'SELECT p.*, product_shop.*, stock.out_of_stock, IFnull(stock.quantity, 0) as quantity, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(product_shop.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new, (product_shop.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice, TIMESTAMPDIFF(SECOND, \''.$current_datetime.'\', pa.`to`) AS ending, CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status`, IF(pa.status = '.ProductAuction::STATUS_FINISHED.', 1, 0) as finished FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) '.Shop::addSqlAssociation('product', 'p').' '.Product::sqlStock('p', 0, false, $context->shop).' LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('pl').') LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (product_shop.`id_tax_rules_group` = tr.`id_tax_rules_group` AND tr.`id_country` = '.(int)$context->country->id.' AND tr.`id_state` = 0 AND tr.`zipcode_from` = 0) LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`) LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON pa.`id_product` = cp.`id_product` WHERE product_shop.`id_shop` = '.(int)$context->shop->id.' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND cp.`id_category` = '.(int)$category_id.' '.($active ? ' AND product_shop.`active` = 1' : '').($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').' HAVING auction_status IN ('.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; if ($random === true) { $sql .= ' ORDER BY RAND()'; $sql .= ' LIMIT 0, '.(int)$random_number_products; } else { if ($order_by == 'finished') { $sql .= ' ORDER BY IF(`auction_status` = '.ProductAuction::STATUS_FINISHED.', 1, 0) '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } else { $sql .= ' ORDER BY '.(isset($order_by_prefix) ? $order_by_prefix.'.' : '').'`'.pSQL($order_by).'` '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } } $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); if ($order_by == 'orderprice') Tools::orderbyPrice($result, $order_way); if (!$result) return array(); /* Modify SQL result */ return Product::getProductsProperties($id_lang, $result); } /** * @param integer $id_lang * @param integer $p * @param integer $n * @param string $order_by * @param string $order_way * @param string $get_total * @param string $active * @param string $random * @param integer $random_number_products * @param Context $context * @return number boolean array */ public static function getCollectionByAuctionStartingTime($threshold, $id_lang, $p, $n, $order_by = null, $order_way = null, $get_total = false, $active = true, $random = false, $random_number_products = 1, Context $context = null) { $current_datetime = date('Y-m-d H:i:s'); if ($threshold > 0) $threshold = date('Y-m-d H:i:s', time() - (int)$threshold); else $threshold = null; if (!$context) $context = Context::getContext(); $front = true; if (!in_array($context->controller->controller_type, array( 'front', 'modulefront' ))) $front = false; if ($p < 1) $p = 1; if (empty($order_by)) $order_by = 'id_product_auction'; else /* Fix for all modules which are now using lowercase values for 'orderBy' parameter */ $order_by = Tools::strtolower($order_by); if (empty($order_way)) $order_way = 'ASC'; if (empty($order_by) || $order_by == 'ending') $order_by = 'to'; if ($order_by == 'id_product') $order_by_prefix = 'p'; elseif ($order_by == 'name') $order_by_prefix = 'pl'; elseif ($order_by == 'from' || $order_by == 'to' || $order_by == 'ending' || $order_by == 'date_add' || $order_by == 'date_upd') $order_by_prefix = 'pa'; if ($order_by == 'price') $order_by = 'orderprice'; if (!Validate::isBool($active) || !Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)) die(Tools::displayError()); /* Return only the number of products */ if ($get_total) { $sql = 'SELECT COUNT(p.`id_product`) AS total FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) INNER JOIN ( SELECT `id_product_auction`, CASE WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE `status` END AS `status` FROM `'._DB_PREFIX_.'product_auction` ) st ON (pa.`id_product_auction` = st.`id_product_auction`) '.Shop::addSqlAssociation('product', 'p').' WHERE 1 AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND pa.`from` <= "'.$current_datetime.'" '.($threshold ? 'AND pa.`from` > "'.$threshold.'"' : null).' '.($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').($active ? ' AND product_shop.`active` = 1' : '').' AND st.status IN ('.ProductAuction::STATUS_IDLE.', '.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } $sql = 'SELECT p.*, product_shop.*, stock.out_of_stock, IFnull(stock.quantity, 0) as quantity, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(product_shop.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new, (product_shop.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice, TIMESTAMPDIFF(SECOND, \''.$current_datetime.'\', pa.`to`) AS ending, CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status`, IF(pa.status = '.ProductAuction::STATUS_FINISHED.', 1, 0) as finished FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) '.Shop::addSqlAssociation('product', 'p').' '.Product::sqlStock('p', 0, false, $context->shop).' LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('pl').') LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (product_shop.`id_tax_rules_group` = tr.`id_tax_rules_group` AND tr.`id_country` = '.(int)$context->country->id.' AND tr.`id_state` = 0 AND tr.`zipcode_from` = 0) LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`) LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` WHERE product_shop.`id_shop` = '.(int)$context->shop->id.' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND pa.`from` <= "'.$current_datetime.'" '.($threshold ? 'AND pa.`from` > "'.$threshold.'"' : null).' '.($active ? ' AND product_shop.`active` = 1' : '').($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').' HAVING auction_status IN ('.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; if ($random === true) { $sql .= ' ORDER BY RAND()'; $sql .= ' LIMIT 0, '.(int)$random_number_products; } else { if ($order_by == 'finished') { $sql .= ' ORDER BY IF(`auction_status` = '.ProductAuction::STATUS_FINISHED.', 1, 0) '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } else { $sql .= ' ORDER BY '.(isset($order_by_prefix) ? $order_by_prefix.'.' : '').'`'.pSQL($order_by).'` '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } } $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); if ($order_by == 'orderprice') Tools::orderbyPrice($result, $order_way); if (!$result) return array(); /* Modify SQL result */ return Product::getProductsProperties($id_lang, $result); } /** * @param integer $id_lang * @param integer $p * @param integer $n * @param string $order_by * @param string $order_way * @param string $get_total * @param string $active * @param string $random * @param integer $random_number_products * @param Context $context * @return number boolean array */ public static function getCollectionByAuctionEndingTime($threshold, $id_lang, $p, $n, $order_by = null, $order_way = null, $get_total = false, $active = true, $random = false, $random_number_products = 1, Context $context = null) { $current_datetime = date('Y-m-d H:i:s'); if ($threshold > 0) $threshold = date('Y-m-d H:i:s', time() + (int)$threshold); else $threshold = null; if (!$context) $context = Context::getContext(); $front = true; if (!in_array($context->controller->controller_type, array( 'front', 'modulefront' ))) $front = false; if ($p < 1) $p = 1; if (empty($order_by)) $order_by = 'id_product_auction'; else /* Fix for all modules which are now using lowercase values for 'orderBy' parameter */ $order_by = Tools::strtolower($order_by); if (empty($order_way)) $order_way = 'ASC'; if (empty($order_by) || $order_by == 'ending') $order_by = 'to'; if ($order_by == 'id_product') $order_by_prefix = 'p'; elseif ($order_by == 'name') $order_by_prefix = 'pl'; elseif ($order_by == 'from' || $order_by == 'to' || $order_by == 'ending' || $order_by == 'date_add' || $order_by == 'date_upd') $order_by_prefix = 'pa'; if ($order_by == 'price') $order_by = 'orderprice'; if (!Validate::isBool($active) || !Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)) die(Tools::displayError()); /* Return only the number of products */ if ($get_total) { $sql = 'SELECT COUNT(p.`id_product`) AS total FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) INNER JOIN ( SELECT `id_product_auction`, CASE WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE `status` END AS `status` FROM `'._DB_PREFIX_.'product_auction` ) st ON (pa.`id_product_auction` = st.`id_product_auction`) '.Shop::addSqlAssociation('product', 'p').' WHERE 1 AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND pa.`from` <= "'.$current_datetime.'" AND pa.`to` > "'.$current_datetime.'" '.($threshold ? 'AND pa.`to` <= "'.$threshold.'"' : null).' '.($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').($active ? ' AND product_shop.`active` = 1' : '').' AND st.status IN ('.ProductAuction::STATUS_IDLE.', '.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } $sql = 'SELECT p.*, product_shop.*, stock.out_of_stock, IFnull(stock.quantity, 0) as quantity, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(product_shop.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new, (product_shop.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice, TIMESTAMPDIFF(SECOND, \''.$current_datetime.'\', pa.`to`) AS ending, CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status`, IF(pa.status = '.ProductAuction::STATUS_FINISHED.', 1, 0) as finished FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) '.Shop::addSqlAssociation('product', 'p').' '.Product::sqlStock('p', 0, false, $context->shop).' LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('pl').') LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (product_shop.`id_tax_rules_group` = tr.`id_tax_rules_group` AND tr.`id_country` = '.(int)$context->country->id.' AND tr.`id_state` = 0 AND tr.`zipcode_from` = 0) LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`) LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` WHERE product_shop.`id_shop` = '.(int)$context->shop->id.' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND pa.`from` <= "'.$current_datetime.'" AND pa.`to` > "'.$current_datetime.'" '.($threshold ? 'AND pa.`to` <= "'.$threshold.'"' : null).' '.($active ? ' AND product_shop.`active` = 1' : '').($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').' HAVING auction_status IN ('.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; if ($random === true) { $sql .= ' ORDER BY RAND()'; $sql .= ' LIMIT 0, '.(int)$random_number_products; } else { if ($order_by == 'finished') { $sql .= ' ORDER BY IF(`auction_status` = '.ProductAuction::STATUS_FINISHED.', 1, 0) '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } else { $sql .= ' ORDER BY '.(isset($order_by_prefix) ? $order_by_prefix.'.' : '').'`'.pSQL($order_by).'` '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } } $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); if ($order_by == 'orderprice') Tools::orderbyPrice($result, $order_way); if (!$result) return array(); /* Modify SQL result */ return Product::getProductsProperties($id_lang, $result); } /** * @param integer $id_lang * @param integer $p * @param integer $n * @param string $order_by * @param string $order_way * @param string $get_total * @param string $active * @param string $random * @param integer $random_number_products * @param Context $context * @return number boolean array */ public static function getCollectionByAuctionPopularity($threshold, $id_lang, $p, $n, $order_by = null, $order_way = null, $get_total = false, $active = true, $random = false, $random_number_products = 1, Context $context = null) { $current_datetime = date('Y-m-d H:i:s'); $threshold = $threshold > 0 ? (int)$threshold : 0; if (!$context) $context = Context::getContext(); $front = true; if (!in_array($context->controller->controller_type, array( 'front', 'modulefront' ))) $front = false; if ($p < 1) $p = 1; if (empty($order_by)) $order_by = 'id_product_auction'; else /* Fix for all modules which are now using lowercase values for 'orderBy' parameter */ $order_by = Tools::strtolower($order_by); if (empty($order_way)) $order_way = 'ASC'; if (empty($order_by) || $order_by == 'ending') $order_by = 'to'; if ($order_by == 'id_product') $order_by_prefix = 'p'; elseif ($order_by == 'name') $order_by_prefix = 'pl'; elseif ($order_by == 'from' || $order_by == 'to' || $order_by == 'ending' || $order_by == 'offers' || $order_by == 'date_add' || $order_by == 'date_upd') $order_by_prefix = 'pa'; if ($order_by == 'price') $order_by = 'orderprice'; if (!Validate::isBool($active) || !Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)) die(Tools::displayError()); /* Return only the number of products */ if ($get_total) { $sql = 'SELECT COUNT(p.`id_product`) AS total FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) INNER JOIN ( SELECT `id_product_auction`, CASE WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN `status` = '.ProductAuction::STATUS_RUNNING.' AND `to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE `status` END AS `status` FROM `'._DB_PREFIX_.'product_auction` ) st ON (pa.`id_product_auction` = st.`id_product_auction`) '.Shop::addSqlAssociation('product', 'p').' WHERE 1 AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND pa.`from` <= "'.$current_datetime.'" AND pa.`to` > "'.$current_datetime.'" '.($threshold ? 'AND pa.`offers` > "'.$threshold.'"' : null).' '.($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').($active ? ' AND product_shop.`active` = 1' : '').' AND st.status IN ('.ProductAuction::STATUS_IDLE.', '.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } $sql = 'SELECT p.*, product_shop.*, stock.out_of_stock, IFnull(stock.quantity, 0) as quantity, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(product_shop.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new, (product_shop.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice, TIMESTAMPDIFF(SECOND, \''.$current_datetime.'\', pa.`to`) AS ending, CASE WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`from` > "'.$current_datetime.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN pa.`status` = '.ProductAuction::STATUS_RUNNING.' AND pa.`to` < "'.$current_datetime.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE pa.`status` END AS `auction_status`, IF(pa.status = '.ProductAuction::STATUS_FINISHED.', 1, 0) as finished FROM `'._DB_PREFIX_.'product` p INNER JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product = p.id_product) '.Shop::addSqlAssociation('product', 'p').' '.Product::sqlStock('p', 0, false, $context->shop).' LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('pl').') LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (product_shop.`id_tax_rules_group` = tr.`id_tax_rules_group` AND tr.`id_country` = '.(int)$context->country->id.' AND tr.`id_state` = 0 AND tr.`zipcode_from` = 0) LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`) LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` WHERE product_shop.`id_shop` = '.(int)$context->shop->id.' AND pa.enable_auction = '.ProductAuction::AUCTION_ENABLED.' AND pa.`from` <= "'.$current_datetime.'" AND pa.`to` > "'.$current_datetime.'" '.($threshold ? 'AND pa.`offers` > "'.$threshold.'"' : null).' '.($active ? ' AND product_shop.`active` = 1' : '').($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '').' HAVING auction_status IN ('.ProductAuction::STATUS_RUNNING.', '.ProductAuction::STATUS_PROCESSING.', '.ProductAuction::STATUS_FINISHED.')'; if ($random === true) { $sql .= ' ORDER BY RAND()'; $sql .= ' LIMIT 0, '.(int)$random_number_products; } else { if ($order_by == 'finished') { $sql .= ' ORDER BY IF(`auction_status` = '.ProductAuction::STATUS_FINISHED.', 1, 0) '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } else { $sql .= ' ORDER BY '.(isset($order_by_prefix) ? $order_by_prefix.'.' : '').'`'.pSQL($order_by).'` '.pSQL($order_way).' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; } } $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); if ($order_by == 'orderprice') Tools::orderbyPrice($result, $order_way); if (!$result) return array(); /* Modify SQL result */ return Product::getProductsProperties($id_lang, $result); } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_ca7d973c26c57b69e0857e7a0332d545'] = 'Les produits en vedette'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_03c2e7e41ffc181a4e84080b4710e81e'] = 'Nouveau'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_e0e572ae0d8489f8bf969e93d469e89c'] = 'Pas de produits phares'; <file_sep><?php Class Media extends MediaCore { public static function deferScript($matches) { if (!is_array($matches)) return false; $inline = ''; if (isset($matches[0])) $original = trim($matches[0]); if (isset($matches[1])) $inline = trim($matches[1]); /* This is an inline script, add its content to inline scripts stack then remove it from content */ if (!empty($inline) && preg_match('/<\s*script(?!.*data-keepinline)[^>]*>/ims', $original) !== 0 && Media::$inline_script[] = $inline) return ''; /* This is an external script, if it already belongs to js_files then remove it from content */ preg_match('/src\s*=\s*["\']?([^"\']*)[^>]/ims', $original, $results); if (isset($results[1]) && (in_array($results[1], Context::getContext()->controller->js_files) || in_array($results[1], Media::$inline_script_src))) return ''; /* return original string because no match was found */ return $original; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractProductAuctionCreate', false)) return; abstract class AbstractProductAuctionCreate implements CoreModuleHelperFormDataModelInterface { const MODULE_TAB_NAME = 'ModuleAuctions'; /** * * @var Module */ protected $module; /** * * @var Context */ protected $context; /** * * @var Currency */ protected $currency; /** * * @var Language */ protected $language; public function initialize(Module $module) { $this->module = $module; $this->context = $module->getContext(); $this->currency = $this->context->currency; $this->language = $this->context->language; return $this; } public function getFieldsValues(ObjectModelCore $object) { $fields_form = $this->getFieldsForm(); $fields_value = array(); $definition = ObjectModel::getDefinition($object); $languages = Language::getLanguages(false); foreach ($fields_form as $fieldset) { if (isset($fieldset['form']['input'])) { foreach ($fieldset['form']['input'] as $input) { if (!isset($fields_value[$input['name']])) { if (isset($input['type']) && $input['type'] == 'shop') { if ($object->id) { $result = Shop::getShopById((int)$object->id, $definition['primary'], $definition['table']); foreach ($result as $row) $fields_value['shop'][$row['id_'.$input['type']]][] = $row['id_shop']; } } elseif (isset($input['lang']) && $input['lang']) { foreach ($languages as $language) { $field_value = CoreModuleTools::getFieldValue($object, $input['name'], $language['id_lang']); if (empty($field_value)) if (isset($input['default_value']) && is_array($input['default_value']) && isset($input['default_value'][$language['id_lang']])) $field_value = $input['default_value'][$language['id_lang']]; elseif (isset($input['default_value'])) $field_value = $input['default_value']; $fields_value[$input['name']][$language['id_lang']] = $field_value; } } else { $field_value = CoreModuleTools::getFieldValue($object, $input['name']); if ($field_value === false && isset($input['default_value'])) $field_value = $input['default_value']; $fields_value[$input['name']] = $field_value; } } } } } return $fields_value; } public function doFieldsValidation(ObjectModelCore $object, &$errors) { $definition = ObjectModel::getDefinition($object); $class_name = get_class($object); $default_language = new Language((int)Configuration::get('PS_LANG_DEFAULT')); foreach ($definition['fields'] as $field => $def) { $skip = array(); if (in_array($field, array( 'passwd', 'no-picture' )) || (!$object->id && !$object->enable_auction)) $skip = array( 'required' ); if (isset($def['lang']) && $def['lang'] && isset($def['required']) && $def['required']) { $value = Tools::getValue($field.'_'.$default_language->id); $error = Tools::displayError('The field %1$s is required at least in %2$s.'); if (Tools::isEmpty($value)) $errors[$field.'_'.$default_language->id] = sprintf($error, $object->displayFieldName($field, $class_name), $default_language->name); foreach (Language::getLanguages(false) as $language) { $value = Tools::getValue($field.'_'.$language['id_lang']); if (!empty($value)) if (($error = $object->validateField($field, $value, $language['id_lang'], $skip, true)) !== true) $errors[$field.'_'.$language['id_lang']] = $error; } } else if (($error = $object->validateField($field, Tools::getValue($field), null, $skip, true)) !== true) $errors[$field] = $error; } $rules = call_user_func(array( $class_name, 'getValidationRules' ), $class_name); /* Checking for multilingual fields validity */ if (isset($rules['validateLang']) && is_array($rules['validateLang'])) { $languages = Language::getLanguages(false); foreach ($rules['validateLang'] as $field_lang => $function) { foreach ($languages as $language) { $value = Tools::getValue($field_lang.'_'.$language['id_lang']); if ($value !== false && !empty($value)) { if (Tools::strtolower($function) == 'iscleanhtml' && Configuration::get('PS_ALLOW_HTML_IFRAME')) $res = Validate::$function($value, true); else $res = Validate::$function($value); $error_msg = Tools::displayError('The %1$s field(%2$s) is invalid.'); if (!$res) $errors[$field_lang.'_'.$language['id_lang']] = sprintf($error_msg, call_user_func(array( $class_name, 'displayFieldName' ), $field_lang, $class_name), $language['name']); } } } } } public function doFieldsSave(ObjectModelCore $object, &$errors) { $this->doFieldsValidation($object, $errors); if (count($errors) < 1) { if (!$object->id && !$object->enable_auction) return true; if (!$object->save(true)) { $error = Db::getInstance()->getMsgError(); $errors[] = Tools::displayError('An error occurred while creating an object.').' <b>'.$object->table.' ('.$error.')</b>'; return false; } } return true; } protected function l($string, $specific = false) { return Translate::getModuleTranslation($this->module, $string, $specific ? $specific : get_class($this)); } } <file_sep><?PHP class Imagegp extends Image { protected $existing_path; public $image_format = 'jpg'; protected $folder; public function getExistingImgPath() { if (!$this->existing_path) { //Pour les version 1.4.0 a 1.4.3 creer la variable 'PS_LEGACY_IMAGES' if (Configuration::get('PS_LEGACY_IMAGES') && file_exists(_PS_PROD_IMG_DIR_.$this->id_product.'-'.$this->id.'.'.$this->image_format)) $this->existing_path = $this->id_product.'-'.$this->id; else $this->existing_path = $this->getImgPath(); } return $this->existing_path; } public function getImgPath() { $path = $this->getImgFolder().$this->id; return $path; } public function getImgFolder() { if (!$this->id) return false; if (!$this->folder) $this->folder = self::getImgFolderStatic($this->id); return $this->folder; } public static function getImgFolderStatic($id_image) { if (!is_numeric($id_image)) return false; $folders = str_split((string)$id_image); return implode('/', $folders).'/'; } } ?><file_sep><?php /** * 2007-2014 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit; require_once(dirname(__FILE__).'/classes/PrediggoConfig.php'); require_once(_PS_MODULE_DIR_.'prediggo/controllers/DataExtractorController.php'); require_once(_PS_MODULE_DIR_.'prediggo/controllers/PrediggoCallController.php'); require_once(_PS_MODULE_DIR_.'prediggo/custom/PrediggoCallControllerOverride.php'); class Prediggo extends Module { /** @var array list of errors */ public $_errors = array(); /** @var array list of confirmations */ public $_confirmations = array(); /** @var array list of warnings */ public $_warnings = array(); /** @var PrediggoConfig Object PrediggoConfig */ public $oPrediggoConfig; /** @var DataExtractorController Object DataExtractorController */ public $oDataExtractorController; /** @var PrediggoCallController Object PrediggoCallController */ public $oPrediggoCallController; /** @var array list of Products by hook */ public $aRecommendations; /** @var string Hook Name */ public $sHookName; /** @var int Variant ID */ public $iVariantId; /** * Constructor */ public function __construct() { $this->name = 'prediggo'; $this->tab = 'advertising_marketing'; $this->version = '1.5.1'; $this->author = 'PrestaShop'; $this->need_instance = 0; $this->_html = ''; $this->multishop_context = true; $this->sHookName = ''; parent::__construct(); $this->displayName = $this->l('Prediggo'); $this->description = $this->l('Offers interactive products recommendations in the front office'); $this->bootstrap = true; $this->_warnings = array(); $this->_confirmations = array(); $this->_errors = array(); /* Set the Configuration Object */ $this->oPrediggoConfig = new PrediggoConfig($this->context); /* Set the main controllers */ $this->oDataExtractorController = new DataExtractorController($this); $this->oPrediggoCallController = new PrediggoCallControllerOverride(); $this->aRecommendations = array(); } /** * Install Procedure * La liste des hooks se trouve en http://doc.prestashop.com/display/PS15/Hooks+in+PrestaShop+1.5 */ public function install() { return ($this->oPrediggoConfig->install() && parent::install() && $this->registerAllHooks() ); } /** * Registration Hook Procedure * La liste des hooks se trouve en http://doc.prestashop.com/display/PS15/Hooks+in+PrestaShop+1.5 */ public function registerAllHooks() { return ($this->registerHook('displayTop') && $this->registerHook('displayHeader') && $this->registerHook('displayLeftColumn') && $this->registerHook('displayRightColumn') && $this->registerHook('displayFooter') && $this->registerHook('actionAuthentication') && $this->registerHook('actionCustomerAccountAdd') && $this->registerHook('displayPaymentTop') && $this->registerHook('displayHome') && $this->registerHook('displayFooterProduct') && $this->registerHook('displayLeftColumnProduct') && $this->registerHook('displayRightColumnProduct') && $this->registerHook('displayShoppingCartFooter') && $this->registerHook('displayShoppingCart') && $this->registerHook('displayOrderDetail') && $this->registerHook('displayProductTab') && $this->registerHook('displayBeforeCarrier') && $this->registerHook('displayCarrierList') && $this->registerHook('displayOrderConfirmation') && $this->registerHook('displayCustomerAccount') && $this->registerHook('displayMyAccountBlock') && $this->registerHook('displayMyAccountBlockfooter') ); } /** * Uninstall Procedure */ public function uninstall() { return ($this->oPrediggoConfig->uninstall() && parent::uninstall() ); } /** * Hook Header : Add Media CSS & JS * * @param array $params list of specific data * @return bool */ public function hookDisplayHeader($params) { if (!isset($params['cookie']->id_guest)) Guest::setNewGuest($params['cookie']); if (!$this->oPrediggoConfig->web_site_id_checked) return false; //add the js for the autocomplete but also the notify if ($this->oPrediggoCallController->isPageAccessible()) { $this->context->controller->addJS(array( ($this->_path).'js/front/'.($this->name).'.js')); } // Check if prediggo module can be executed in this page if ($this->oPrediggoCallController->isPageAccessible() || $this->oPrediggoCallController->getPageName() == 'prediggo_search' || $this->oPrediggoConfig->search_active) { $this->context->controller->addCSS(($this->_path).'css/front/'.($this->name).'.css', 'all'); $this->context->controller->addJS(array( ($this->_path).'js/front/prediggo_autocomplete.js', ($this->_path).'js/front/'.($this->name).'.js' )); } } /** * Hook Home : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayHome($params) { //this is usefull to register all the hooks again //$this->registerAllHooks(); // Get list of recommendations //echo '<BR><BR>DISPLAY HOME PAGE<br>'; return $this->displayRecommendationsWithDynamicTemplate('displayHome', $params); } /** * Hook Right Column : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayRightColumn($params) { //echo '<BR><BR>DISPLAY RIGHT COLUMN - page name '.$this->oPrediggoCallController->getPageName().'<br>'; //check if we are on a catgogry page, need to do this as no category hook In Presta 1.5:( if (strcmp ($this->oPrediggoCallController->getPageName(), $this->oPrediggoConfig->categoryPageName) == 0) return $this->displayRecommendationsWithDynamicTemplate('displayRightColumn'.$this->oPrediggoCallController->getPageName(), $params).$this->displayRecommendationsWithDynamicTemplate('displayRightColumn', $params); else if (strcmp ($this->oPrediggoCallController->getPageName(), $this->oPrediggoConfig->manufacturerPageName) == 0) return $this->displayRecommendationsWithDynamicTemplate('displayRightColumn'.$this->oPrediggoCallController->getPageName(), $params).$this->displayRecommendationsWithDynamicTemplate('displayRightColumn', $params); // Get list of recommendations return $this->displayRecommendationsWithDynamicTemplate('displayRightColumn', $params); } /** * Hook Left Column : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayLeftColumn($params) { // Get list of recommendations //echo '<BR><BR>DISPLAY LEFT COLUMN<br>'; //check if we are on a catgogry page, need to do this as no category hook In Presta 1.5:( if (strcmp ($this->oPrediggoCallController->getPageName(), $this->oPrediggoConfig->categoryPageName) == 0) return $this->displayRecommendationsWithDynamicTemplate('displayLeftColumn'.$this->oPrediggoCallController->getPageName(), $params).$this->displayRecommendationsWithDynamicTemplate('displayLeftColumn', $params).$this->displaySearchFilterBlock($params); else if (strcmp ($this->oPrediggoCallController->getPageName(), $this->oPrediggoConfig->manufacturerPageName) == 0) return $this->displayRecommendationsWithDynamicTemplate('displayLeftColumn'.$this->oPrediggoCallController->getPageName(), $params).$this->displayRecommendationsWithDynamicTemplate('displayLeftColumn', $params).$this->displaySearchFilterBlock($params); return $this->displayRecommendationsWithDynamicTemplate('displayLeftColumn', $params).$this->displaySearchFilterBlock($params); } /** * Hook Top : Display the prediggo search block * * @param array $params list of specific data * @return string */ public function hookDisplayTop($params) { //echo '<BR><BR>DISPLAY TOP<br>'; //check if we are on a catgogry page, need to do this as no category hook In Presta 1.5:( if (strcmp ($this->oPrediggoCallController->getPageName(), $this->oPrediggoConfig->categoryPageName) == 0) return $this->displayRecommendationsWithDynamicTemplate('displayTop'.$this->oPrediggoCallController->getPageName(), $params).$this->displayRecommendationsWithDynamicTemplate('displayTop', $params); else if (strcmp ($this->oPrediggoCallController->getPageName(), $this->oPrediggoConfig->manufacturerPageName) == 0) return $this->displayRecommendationsWithDynamicTemplate('displayTop'.$this->oPrediggoCallController->getPageName(), $params).$this->displayRecommendationsWithDynamicTemplate('displayTop', $params); //$this->displaySearchBlock($params).$this->displayRecommendationsWithDynamicTemplate('displayTop', $params); return $this->displayRecommendationsWithDynamicTemplate('displayTop', $params).$this->displaySearchBlock($params); } /** * Hook Footer : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayFooter($params) { //check if we are on a catgogry page, need to do this as no category hook In Presta 1.5:( if (strcmp ($this->oPrediggoCallController->getPageName(), $this->oPrediggoConfig->categoryPageName) == 0) return $this->displayRecommendationsWithDynamicTemplate('displayRightColumn'.$this->oPrediggoCallController->getPageName(), $params).$this->displayRecommendationsWithDynamicTemplate('displayRightColumn', $params); else if (strcmp ($this->oPrediggoCallController->getPageName(), $this->oPrediggoConfig->manufacturerPageName) == 0) return $this->displayRecommendationsWithDynamicTemplate('displayRightColumn'.$this->oPrediggoCallController->getPageName(), $params).$this->displayRecommendationsWithDynamicTemplate('displayRightColumn', $params); //echo '<BR><BR>DISPLAY FOOTER<br>'; return $this->displayRecommendationsWithDynamicTemplate('displayFooter', $params); } /** * Hook Left Column Product : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayLeftColumnProduct($params) { // Get list of recommendations //echo '<BR><BR>DISPLAY displayLeftColumnProduct<br>'; return $this->displayRecommendationsWithDynamicTemplate('displayLeftColumnProduct', $params); } /** * Hook Right Column Product : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayRightColumnProduct($params) { // Get list of recommendations //echo '<BR><BR>DISPLAY displayRightColumnProduct<br>'; return $this->displayRecommendationsWithDynamicTemplate('displayRightColumnProduct', $params); } /** * Hook Product Tab : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayProductTab($params) { //echo '<BR><BR>DISPLAY getProductTablE<br>'; return $this->displayRecommendationsWithDynamicTemplate('displayRightColumnProduct', $params); } /** * Hook Shopping Cart Footer : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayShoppingCartFooter($params) { // Get list of recommendations //echo '<BR><BR>DISPLAY displayShoppingCartFooter<br>'; return $this->displayRecommendationsWithDynamicTemplate('displayShoppingCartFooter', $params); } /** * Hook Shopping Cart : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayShoppingCart($params) { // Get list of recommendations //echo '<BR><BR>DISPLAY displayShoppingCart<br>'; return $this->displayRecommendationsWithDynamicTemplate('displayShoppingCart', $params); } /** * Hook Order Detail : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayOrderDetail($params) { //echo '<BR><BR>DISPLAY displayOrderDetail<br>'; // Get list of recommendations return $this->displayRecommendationsWithDynamicTemplate('displayOrderDetail', $params); } /** * Hook Before Carrier : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayBeforeCarrier($params) { //echo '<BR><BR>DISPLAY displayBeforeCarrier<br>'; // Get list of recommendations return $this->displayRecommendationsWithDynamicTemplate('displayBeforeCarrier', $params); } /** * Hook Carrier List : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayCarrierList($params) { //echo '<BR><BR>DISPLAY displayCarrierList<br>'; return $this->displayRecommendationsWithDynamicTemplate('displayCarrierList', $params); } /** * Hook Carrier List : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayOrderConfirmation($params) { //echo '<BR><BR>DISPLAY order confirmation<br>'; return $this->displayRecommendationsWithDynamicTemplate('displayOrderConfirmation', $params); } /** * Hook Customer Account : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayCustomerAccount($params) { //echo '<BR><BR>DISPLAY order confirmation Customer Account<br>'; $params['customer'] = $this->context->customer; return $this->displayRecommendationsWithDynamicTemplate('displayCustomerAccount', $params); } /** * Hook Customer Account : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayMyAccountBlock($params) { //echo '<BR><BR>DISPLAY order confirmation My Account Block<br>'; $params['customer'] = $this->context->customer; return $this->displayRecommendationsWithDynamicTemplate('displayMyAccountBlock', $params); } /** * Hook Customer Account : Display the recommendations * * @param array $params list of specific data * @return string * @int int to choose your Variant ID */ public function hookDisplayMyAccountBlockfooter($params) { //echo '<BR><BR>DISPLAY order confirmation My Account Block Footer<br>'; $params['customer'] = $this->context->customer; return $this->displayRecommendationsWithDynamicTemplate('displayMyAccountBlockfooter', $params); } /** * Hook Authentication : Notify prediggo that the user is authenticated * * @param array $params list of specific data * @return bool */ public function hookActionAuthentication($params) { if (!$this->oPrediggoConfig->web_site_id_checked) return false; $params['customer'] = $this->context->customer; $this->oPrediggoCallController->notifyPrediggo('user', $params); } /** * Hook Payment Top : Notify prediggo that the user is authenticated * * @param array $params list of specific data * @return bool */ public function hookDisplayPaymentTop($params) { if (!$this->oPrediggoConfig->web_site_id_checked) return false; $params['customer'] = $this->context->customer; $this->oPrediggoCallController->notifyPrediggo('user', $params); } /** * Hook Create Account : Notify prediggo that the user is authenticated * * @param array $params list of specific data * @return bool */ public function hookActionCustomerAccountAdd($params) { if (!$this->oPrediggoConfig->web_site_id_checked) return false; $params['customer'] = $this->context->customer; $this->oPrediggoCallController->notifyPrediggo('user', $params); } /** * Display the recommendations by hook using dynamic templates * * @param string $sHookName Hook Name * @param array $params list of specific data * @internal param int $iVariantId Id of the Variant * @return string Html */ private function displayRecommendationsWithDynamicTemplate($sHookName, $params) { if (!$this->oPrediggoConfig->web_site_id_checked) return false; $params['customer'] = $this->context->customer; $this->aRecommendations[$sHookName] = $this->oPrediggoCallController->getListOfRecommendationsWithDynamicTemplate($sHookName, $params); if (!$this->aRecommendations[$sHookName] || count($this->aRecommendations[$sHookName]) == 0 || count($this->aRecommendations[$sHookName][0]) == 0) return false; // Display Main Configuration management $this->smarty->assign(array( 'hook_name' => $sHookName, 'aRecommendations' => $this->aRecommendations, 'tax_enabled' => (int)Configuration::get('PS_TAX'), 'display_qties' => (int)Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'sImageType' => $this->oPrediggoConfig->imgType(), )); return $this->display(__FILE__, $this->aRecommendations[$sHookName][0]['block_template']); } /** * Hook Authentication : Notify prediggo that a recommendations has been clicked * * @param array $params list of specific data * @return bool */ public function setProductNotification($params) { if (!$this->oPrediggoConfig->web_site_id_checked) return false; $params['customer'] = $this->context->customer; $this->oPrediggoCallController->notifyPrediggo('product', $params); } /** * Display the search Filters block * * @param array $params list of specific data * @return string Html */ private function displaySearchFilterBlock($params) { if ($this->oPrediggoConfig->web_site_id_checked && $this->oPrediggoConfig->layered_navigation_active) { $template = $this->oPrediggoConfig->search_filter_block_template_name; return $this->display(__FILE__, $template); } } /** * Display the search block * * @param array $params list of specific data * @return string Html */ private function displaySearchBlock($params) { if ($this->oPrediggoConfig->web_site_id_checked && $this->oPrediggoConfig->search_active) { $template = $this->oPrediggoConfig->search_0_template_name; return $this->display(__FILE__, $template); } } /** * Display the did you mean suggestion * * @return string Html */ public function displayAutocompleteDidYouMean() { if ($this->oPrediggoConfig->web_site_id_checked && $this->oPrediggoConfig->search_active && $this->oPrediggoConfig->autocompletion_active) { $this->smarty->assign(array( 'sImageType' => $this->oPrediggoConfig->imgType(), )); $template = 'views/templates/hook/'.$this->oPrediggoConfig->autoc_template_name; return $this->display(__FILE__, $template); } } /** * Display the autocompletion products * * @return string Html */ public function displayAutocompleteProduct() { if ($this->oPrediggoConfig->web_site_id_checked && $this->oPrediggoConfig->search_active && $this->oPrediggoConfig->autocompletion_active) { $template = 'views/templates/hook/'.$this->oPrediggoConfig->autop_template_name; return $this->display(__FILE__, $template); } } /** * Display the autocompletion categories * * @return string Html */ public function displayAutocompleteAttributes() { if ($this->oPrediggoConfig->web_site_id_checked && $this->oPrediggoConfig->search_active && $this->oPrediggoConfig->autocompletion_active) { $template = 'views/templates/hook/' . $this->oPrediggoConfig->autocat_template_name; return $this->display(__FILE__, $template); } } /** * Display the autocompletion suggestions * * @return string Html */ public function displayAutocompleteSuggest() { if ($this->oPrediggoConfig->web_site_id_checked && $this->oPrediggoConfig->search_active && $this->oPrediggoConfig->autocompletion_active) { $template = 'views/templates/hook/'.$this->oPrediggoConfig->autos_template_name; return $this->display(__FILE__, $template); } } /** * Get the recommendations from the blocklayered filters * * @param array $params list of specific data * @return array $aData containing the front office block */ public function getBlockLayeredRecommendations($params) { if (!$this->oPrediggoConfig->web_site_id_checked) return false; $sHookName = 'blocklayered'; $this->oPrediggoCallControllerOverride->_setPageName($sHookName); $params['filters'] = $this->getSelectedFilters(); $params['customer'] = $this->context->customer; $this->aRecommendations[$sHookName] = $this->oPrediggoCallController->getListOfRecommendations($sHookName, $params, 0); if (!$this->aRecommendations[$sHookName]) return false; // Display Main Configuration management $this->smarty->assign(array( 'hook_name' => $sHookName, 'page_name' => 'category', 'aRecommendations' => $this->aRecommendations, 'tax_enabled' => (int)Configuration::get('PS_TAX'), 'display_qties' => (int)Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'sImageType' => $this->oPrediggoConfig->imgType(), )); return $this->display(__FILE__, 'list_recommendations.tpl'); } /* Display the categories */ public function displayCategories($params) { if (!$this->oPrediggoConfig->web_site_id_checked) return false; if (!$this->isCached('blockcategories.tpl', $this->getCacheId())) { // Get all groups for this customer and concatenate them as a string: "1,2,3..." $groups = implode(', ', Customer::getGroupsStatic((int)$this->context->customer->id)); $maxdepth = Configuration::get('BLOCK_CATEG_MAX_DEPTH'); if (!$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT DISTINCT c.id_parent, c.id_category, cl.name, cl.description, cl.link_rewrite FROM `'._DB_PREFIX_.'category` c INNER JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category` AND cl.`id_lang` = '.(int)$this->context->language->id.Shop::addSqlRestrictionOnLang('cl').') INNER JOIN `'._DB_PREFIX_.'category_shop` cs ON (cs.`id_category` = c.`id_category` AND cs.`id_shop` = '.(int)$this->context->shop->id.') WHERE (c.`active` = 1 OR c.`id_category` = '.(int)Configuration::get('PS_HOME_CATEGORY').') AND c.`id_category` != '.(int)Configuration::get('PS_ROOT_CATEGORY').' '.((int)$maxdepth != 0 ? ' AND `level_depth` <= '.(int)$maxdepth : '').' AND c.id_category IN (SELECT id_category FROM `'._DB_PREFIX_.'category_group` WHERE `id_group` IN ('.pSQL($groups).')) ORDER BY `level_depth` ASC, '.(Configuration::get('BLOCK_CATEG_SORT') ? 'cl.`name`' : 'cs.`position`').' '.(Configuration::get('BLOCK_CATEG_SORT_WAY') ? 'DESC' : 'ASC'))) return; $resultParents = array(); $resultIds = array(); $isDhtml = (Configuration::get('BLOCK_CATEG_DHTML') == 1 ? true : false); foreach ($result as &$row) { $resultParents[$row['id_parent']][] = &$row; $resultIds[$row['id_category']] = &$row; } $blockCategTree = $this->getTree($resultParents, $resultIds, Configuration::get('BLOCK_CATEG_MAX_DEPTH')); unset($resultParents, $resultIds); $this->smarty->assign('blockCategTree', $blockCategTree); $this->smarty->assign('branche_tpl_path', _PS_MODULE_DIR_.'prediggo/views/templates/front/category-tree-branch.tpl'); $this->smarty->assign('isDhtml', $isDhtml); } $id_category = (int)Tools::getValue('id_category'); $id_product = (int)Tools::getValue('id_product'); if (Tools::isSubmit('id_category')) { $this->context->cookie->last_visited_category = (int)$id_category; $this->smarty->assign('currentCategoryId', $this->context->cookie->last_visited_category); } if (Tools::isSubmit('id_product')) { if (!isset($this->context->cookie->last_visited_category) || !Product::idIsOnCategoryId($id_product, array('0' => array('id_category' => $this->context->cookie->last_visited_category))) || !Category::inShopStatic($this->context->cookie->last_visited_category, $this->context->shop)) { $product = new Product((int)$id_product); if (isset($product) && Validate::isLoadedObject($product)) $this->context->cookie->last_visited_category = (int)$product->id_category_default; } $this->smarty->assign('currentCategoryId', (int)$this->context->cookie->last_visited_category); } $display = $this->display(__FILE__, 'views/templates/front/blockcategories.tpl', $this->getCacheId()); return $display; } /* get cache ID */ protected function getCacheId($name = null) { parent::getCacheId($name); $groups = implode(', ', Customer::getGroupsStatic((int)$this->context->customer->id)); $id_product = (int)Tools::getValue('id_product', 0); $id_category = (int)Tools::getValue('id_category', 0); $id_lang = (int)$this->context->language->id; return 'blockcategories|'.(int)Tools::usingSecureMode().'|'.$this->context->shop->id.'|'.$groups.'|'.$id_lang.'|'.$id_product.'|'.$id_category; } /* get category tree */ public function getTree($resultParents, $resultIds, $maxDepth, $id_category = null, $currentDepth = 0) { if (is_null($id_category)) $id_category = $this->context->shop->getCategory(); $children = array(); if (isset($resultParents[$id_category]) && count($resultParents[$id_category]) && ($maxDepth == 0 || $currentDepth < $maxDepth)) foreach ($resultParents[$id_category] as $subcat) $children[] = $this->getTree($resultParents, $resultIds, $maxDepth, $subcat['id_category'], $currentDepth + 1); if (!isset($resultIds[$id_category])) return false; $return = array('id' => $id_category, 'link' => $this->context->link->getCategoryLink($id_category, $resultIds[$id_category]['link_rewrite']), 'name' => $resultIds[$id_category]['name'], 'desc'=> $resultIds[$id_category]['description'], 'children' => $children); return $return; } /** * Get the blocklayered filters * * @return array $selectedFilters list of filters */ private function getSelectedFilters() { $id_parent = (int)Tools::getValue('id_category', Tools::getValue('id_category_layered', 1)); if ($id_parent == 1) return; // Force attributes selection (by url '.../2-mycategory/color-blue' or by get parameter 'selected_filters') if (basename($_SERVER['SCRIPT_FILENAME'], 'xhr.php') === false || Tools::getValue('selected_filters') !== false) { if (Tools::getValue('selected_filters')) $url = Tools::getValue('selected_filters'); else $url = preg_replace('/\/(?:\w*)\/(?:[0-9]+[-\w]*)([^\?]*)\??.*/', '$1', Tools::safeOutput($_SERVER['REQUEST_URI'], true)); $url_attributes = explode('/', ltrim($url, '/')); $selected_filters = array('category' => array()); if (!empty($url_attributes)) { foreach ($url_attributes as $url_attribute) { $url_parameters = explode('-', $url_attribute); $attribute_name = array_shift($url_parameters); if ($attribute_name == 'page') $this->page = (int)$url_parameters[0]; elseif (in_array($attribute_name, array('price', 'weight'))) $selected_filters[$attribute_name] = array($url_parameters[0], $url_parameters[1]); else { foreach ($url_parameters as $url_parameter) { $data = Db::getInstance()->getValue('SELECT data FROM `'._DB_PREFIX_.'layered_friendly_url` WHERE `url_key` = \''.md5('/'.$attribute_name.'-'.$url_parameter).'\''); if ($data) foreach (self::unSerialize($data) as $key_params => $params) { if (!isset($selected_filters[$key_params])) $selected_filters[$key_params] = array(); foreach ($params as $key_param => $param) { if (!isset($selected_filters[$key_params][$key_param])) $selected_filters[$key_params][$key_param] = array(); $selected_filters[$key_params][$key_param] = $param; } } } } } return $selected_filters; } } /* Analyze all the filters selected by the user and store them into a tab */ $selected_filters = array('category' => array(), 'manufacturer' => array(), 'quantity' => array(), 'condition' => array()); foreach ($_GET as $key => $value) if (Tools::substr($key, 0, 8) == 'layered_') { preg_match('/^(.*)_([0-9]+|new|used|refurbished|slider)$/', Tools::substr($key, 8, Tools::strlen($key) - 8), $res); if (isset($res[1])) { $tmp_tab = explode('_', $value); $value = $tmp_tab[0]; $id_key = false; if (isset($tmp_tab[1])) $id_key = $tmp_tab[1]; if ($res[1] == 'condition' && in_array($value, array('new', 'used', 'refurbished'))) $selected_filters['condition'][] = $value; elseif ($res[1] == 'quantity_all_versions' && (!$value || $value == 1)) $selected_filters['quantity_all_versions'][] = $value; elseif (in_array($res[1], array('category', 'manufacturer'))) { if (!isset($selected_filters[$res[1].($id_key ? '_'.$id_key : '')])) $selected_filters[$res[1].($id_key ? '_'.$id_key : '')] = array(); $selected_filters[$res[1].($id_key ? '_'.$id_key : '')][] = (int)$value; } elseif (in_array($res[1], array('id_attribute_group', 'id_feature'))) { if (!isset($selected_filters[$res[1]])) $selected_filters[$res[1]] = array(); $selected_filters[$res[1]][(int)$value] = $id_key.'_'.(int)$value; } elseif ($res[1] == 'weight') $selected_filters[$res[1]] = $tmp_tab; elseif ($res[1] == 'price') $selected_filters[$res[1]] = $tmp_tab; } } return $selected_filters; } /** * BO main function * * @return string Html */ public function getContent() { // Web site id verification for older version if (!$this->oPrediggoConfig->web_site_id_checked && !Configuration::hasKey('PREDIGGO_WEB_SITE_ID_CHECKED')) $this->checkWebSiteId(); if (count($_POST)) $this->_postProcess(); // Check Intermediary Database $this->checkModuleConstraints(); // Display forms $this->_displayForm(); return $this->_html; } /** * Check the client web site id */ private function checkWebSiteId() { $this->oPrediggoConfig->web_site_id_checked = (int)$this->oPrediggoCallController->checkWebSiteId(); if ($this->oPrediggoConfig->web_site_id_checked == true) Configuration::updateValue('PREDIGGO_CONFIGURATION_OK', true); if (!$this->oPrediggoConfig->save()) $this->_errors[] = Tools::displayError('An error occurred while updating the main configuration settings'); } /** * Check the server configuration variables */ public function checkModuleConstraints() { if (!extension_loaded('dom')) $this->_errors[] = Tools::displayError('Please activate the PHP extension "DOM" to allow the use of the module.'); if (!extension_loaded('curl')) $this->_errors[] = Tools::displayError('Please activate the PHP extension "curl" to allow the use of the module.'); if (!$this->oPrediggoConfig->web_site_id_checked) $this->adminDisplayWarning('Please update the field "Web Site ID", in the "Main Configuration" tab.'); // API can't be call if curl extension is not installed on PHP config. if ((int)ini_get('max_execution_time') < 3000) $this->adminDisplayWarning(sprintf('Please update the PHP option "max_execution_time" to a minimum of "3000". (Current value : %d)',(int)ini_get('max_execution_time'))); if ((int)ini_get('max_input_time') < 3000) $this->adminDisplayWarning(sprintf('Please update the PHP option "max_input_time" to a minimum of "3000". (Current value : %d)',(int)ini_get('max_input_time'))); if ((int)ini_get('memory_limit') < 384) $this->adminDisplayWarning(sprintf('Please update the PHP option "memory_limit" to a minimum of "384M". (Current value : %s)',ini_get('memory_limit'))); if ((int)(Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP)) $this->adminDisplayWarning('Please select a shop on the top block to configure the specific settings.'); } private function checkServerCheck(){ $this->oPrediggoConfig->server_url_check = Tools::safeOutput(Tools::getValue('server_url_check')); } /** * Set the data once an updated is processed in the BO */ private function _postProcess() { // Set the main configuration if (Tools::isSubmit('mainConfSubmit')) { $this->oPrediggoConfig->shop_name = Tools::safeOutput(Tools::getValue('shop_name')); $this->oPrediggoConfig->token_id = Tools::safeOutput(Tools::getValue('token_id')); $this->oPrediggoConfig->gateway_profil_id = Tools::safeOutput(Tools::getValue('gateway_profil_id')); if ($this->oPrediggoConfig->save()){ $this->checkServerCheck(); $this->_confirmations[] = $this->displayConfirmation('Main settings updated'); } else $this->_errors[] = Tools::displayError('An error occurred while updating the main configuration settings'); } // Set the server configuration if (Tools::isSubmit('serverConfSubmit')) { $this->oPrediggoConfig->web_site_id = Tools::safeOutput(Tools::getValue('web_site_id')); $this->oPrediggoConfig->server_url_recommendations = Tools::safeOutput(Tools::getValue('server_url_recommendations')); if ($this->oPrediggoConfig->save()) { $this->checkWebSiteId(); $this->_confirmations[] = $this->displayConfirmation('Server settings updated'); } else $this->_errors[] = Tools::displayError('An error occurred while updating the export configuration settings'); } // Set the export configuration if (Tools::isSubmit('exportConfSubmit')) { $this->oPrediggoConfig->products_file_generation = Tools::safeOutput(Tools::getValue('products_file_generation')); $this->oPrediggoConfig->orders_file_generation = Tools::safeOutput(Tools::getValue('orders_file_generation')); $this->oPrediggoConfig->customers_file_generation = Tools::safeOutput(Tools::getValue('customers_file_generation')); $this->oPrediggoConfig->export_product_image = Tools::safeOutput(Tools::getValue('export_product_image')); $this->oPrediggoConfig->export_product_description = Tools::safeOutput(Tools::getValue('export_product_description')); $this->oPrediggoConfig->export_product_active = Tools::safeOutput(Tools::getValue('export_product_active')); $this->oPrediggoConfig->export_product_price = Tools::safeOutput(Tools::getValue('export_product_price')); $this->oPrediggoConfig->nb_days_order_valide = Tools::safeOutput(Tools::getValue('nb_days_order_valide')); $this->oPrediggoConfig->nb_days_customer_last_visit_valide = Tools::safeOutput(Tools::getValue('nb_days_customer_last_visit_valide')); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Export settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the export configuration settings'); } // Set the export configuration if (Tools::isSubmit('logsSubmit')) { $this->oPrediggoConfig->logs_generation = (int)Tools::safeOutput(Tools::getValue('logs_generation')); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Logs settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the Logs configuration settings'); } // Launch the file export if (Tools::isSubmit('manualExportSubmit') && !count($this->_errors)) $this->oDataExtractorController->launchExport(); // Launch the file Import if (Tools::isSubmit('ClientConfigurationImportSubmit') && !count($this->_errors)) { if ($this->oPrediggoConfig->save()){ $location = _PS_MODULE_DIR_.'prediggo/xmlfiles/import.sql'; $location2 = _PS_MODULE_DIR_.'prediggo/xmlfiles/import2.sql'; if (copy($_FILES['Import']['tmp_name'], $location) && copy($_FILES['Import2']['tmp_name'], $location2)) { $this->oPrediggoCallController->import_client_config2(); $this->oPrediggoCallController->import_client_config(); } else $this->_errors[] = Tools::displayError('An error occurred while importing the client configuration'); } else $this->_errors[] = Tools::displayError('An error occurred while importing the client configuration'); } // Launch the configuration export if (Tools::isSubmit('ClientConfigurationExportSubmit') && !count($this->_errors)) { if ($this->oPrediggoConfig->save()) $this->oPrediggoCallController->export_client_config(); else $this->_errors[] = Tools::displayError('An error occurred while exporting the client configuration'); } // Set the export attributes if (Tools::isSubmit('exportPrediggoAttributesSubmit')) { if (is_array(Tools::getValue('attributes_groups_ids'))) $this->oPrediggoConfig->attributes_groups_ids = Tools::safeOutput(join(',', array_map('intval', Tools::getValue('attributes_groups_ids')))); if (is_array(Tools::getValue('features_ids'))) $this->oPrediggoConfig->features_ids = Tools::safeOutput(join(',', array_map('intval', Tools::getValue('features_ids')))); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Product attributes settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the product attributes configuration settings'); } // Set the black list of recommendations if (Tools::isSubmit('exportNotRecoSubmit')) { $this->oPrediggoConfig->products_ids_not_recommendable = Tools::safeOutput(Tools::substr(Tools::getValue('input_products_ids_not_recommendable'), 0, -1)); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Black list of recommendations updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the black list of recommendations'); } if (Tools::isSubmit('resetRecoList')) { Db::getInstance(_PS_USE_SQL_SLAVE_)->execute('UPDATE `'._DB_PREFIX_.'configuration` SET `value`= NULL WHERE `name` = "PREDIGGO_PRODUCTS_NOT_RECO"'); } if (Tools::isSubmit('resetSearchList')) { Db::getInstance(_PS_USE_SQL_SLAVE_)->execute('UPDATE `'._DB_PREFIX_.'configuration` SET `value`= NULL WHERE `name` = "PREDIGGO_PRODUCTS_NOT_SEARCH"'); } // Set the black list of recommendations if (Tools::isSubmit('exportNotSearchSubmit')) { $this->oPrediggoConfig->products_ids_not_searchable = Tools::safeOutput(Tools::substr(Tools::getValue('input_products_ids_not_searchable'), 0, -1)); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Black list of searchs updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the black list of searchs'); } // Set the protection configuration if (Tools::isSubmit('exportProtectionConfSubmit')) { if ($aIds = $this->oDataExtractorController->setRepositoryProtection(Tools::getValue('htpasswd_user'), Tools::getValue('htpasswd_pwd'))) { if (empty($aIds['user'])) $this->_confirmations[] = $this->displayConfirmation('Protection has been disactivated'); else $this->_confirmations[] = $this->displayConfirmation('Protection has been activated'); $this->oPrediggoConfig->htpasswd_user = Tools::safeOutput(Tools::getValue('htpasswd_user')); $this->oPrediggoConfig->htpasswd_pwd = Tools::safeOutput(Tools::getValue('htpasswd_pwd')); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Protection settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the protection configuration settings'); } else $this->_errors[] = Tools::displayError('An error occurred when activating the protection'); } // Set the recommendations main configuration if (Tools::isSubmit('mainRecommendationConfSubmit')) { $this->oPrediggoConfig->server_url_recommendations = Tools::safeOutput(Tools::getValue('server_url_recommendations')); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Recommendations main configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the main configuration of recommendations settings'); } // Set the recommendations main configuration if (Tools::isSubmit('registerAllHooks')) { if ($this->oPrediggoConfig->save()) $this->registerAllHooks(); else $this->_errors[] = Tools::displayError('An error occurred while launching the register of all Hooks'); } // Set the homepage recommendations block configuration if (Tools::isSubmit('HookConfigurationSubmit')) { $this->oPrediggoConfig->hook_left_column = (int)Tools::safeOutput(Tools::getValue('hook_left_column')); $this->oPrediggoConfig->hook_right_column = (int)Tools::safeOutput(Tools::getValue('hook_right_column')); $this->oPrediggoConfig->hook_footer = (int)Tools::safeOutput(Tools::getValue('hook_footer')); $this->oPrediggoConfig->hook_home = (int)Tools::safeOutput(Tools::getValue('hook_home')); $this->oPrediggoConfig->hook_footer_product = (int)Tools::safeOutput(Tools::getValue('hook_footer_product')); $this->oPrediggoConfig->hook_left_column_product = (int)Tools::safeOutput(Tools::getValue('hook_left_column_product')); $this->oPrediggoConfig->hook_right_column_product = (int)Tools::safeOutput(Tools::getValue('hook_right_column_product')); $this->oPrediggoConfig->hook_shopping_cart_footer = (int)Tools::safeOutput(Tools::getValue('hook_shopping_cart_footer')); $this->oPrediggoConfig->hook_shopping_cart = (int)Tools::safeOutput(Tools::getValue('hook_shopping_cart')); $this->oPrediggoConfig->hook_product_comparison = (int)Tools::safeOutput(Tools::getValue('hook_product_comparison')); $this->oPrediggoConfig->hook_order_detail = (int)Tools::safeOutput(Tools::getValue('hook_order_detail')); $this->oPrediggoConfig->hook_product_tab = (int)Tools::safeOutput(Tools::getValue('hook_product_tab')); $this->oPrediggoConfig->hook_before_carrier = (int)Tools::safeOutput(Tools::getValue('hook_before_carrier')); $this->oPrediggoConfig->hook_carrier_list = (int)Tools::safeOutput(Tools::getValue('hook_carrier_list')); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Hook configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the hook configuration settings'); } // Set the homepage recommendations block configuration if (Tools::isSubmit('exportHome0RecommendationConfSubmit')) { $this->oPrediggoConfig->home_0_activated = Tools::safeOutput(Tools::getValue('home_0_activated')); $this->oPrediggoConfig->home_0_nb_items = (int)Tools::safeOutput(Tools::getValue('home_0_nb_items')); $this->oPrediggoConfig->home_0_variant_id = (int)Tools::safeOutput(Tools::getValue('home_0_variant_id')); $this->oPrediggoConfig->home_0_hook_name = Tools::safeOutput(Tools::getValue('home_0_hook_name')); $this->oPrediggoConfig->home_0_template_name = Tools::safeOutput(Tools::getValue('home_0_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->home_0_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('home_0_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Homepage recommendations block #0 configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } if (Tools::isSubmit('exportHome1RecommendationConfSubmit')) { $this->oPrediggoConfig->home_1_activated = Tools::safeOutput(Tools::getValue('home_1_activated')); $this->oPrediggoConfig->home_1_nb_items = (int)Tools::safeOutput(Tools::getValue('home_1_nb_items')); $this->oPrediggoConfig->home_1_variant_id = (int)Tools::safeOutput(Tools::getValue('home_1_variant_id')); $this->oPrediggoConfig->home_1_hook_name = Tools::safeOutput(Tools::getValue('home_1_hook_name')); $this->oPrediggoConfig->home_1_template_name = Tools::safeOutput(Tools::getValue('home_1_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->home_1_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('home_1_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Homepage recommendations block #1 configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the homepage recommendations block configuration bloc 1 if (Tools::isSubmit('exportAllPage0RecommendationConfSubmit')) { $this->oPrediggoConfig->allpage_0_activated = Tools::safeOutput(Tools::getValue('allpage_0_activated')); $this->oPrediggoConfig->allpage_0_nb_items = (int)Tools::safeOutput(Tools::getValue('allpage_0_nb_items')); $this->oPrediggoConfig->allpage_0_variant_id = (int)Tools::safeOutput(Tools::getValue('allpage_0_variant_id')); $this->oPrediggoConfig->allpage_0_hook_name = Tools::safeOutput(Tools::getValue('allpage_0_hook_name')); $this->oPrediggoConfig->allpage_0_template_name = Tools::safeOutput(Tools::getValue('allpage_0_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->allpage_0_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('allpage_0_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('All Page #0 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the homepage recommendations block configuration bloc 1 if (Tools::isSubmit('exportAllPage1RecommendationConfSubmit')) { $this->oPrediggoConfig->allpage_1_activated = Tools::safeOutput(Tools::getValue('allpage_1_activated')); $this->oPrediggoConfig->allpage_1_nb_items = (int)Tools::safeOutput(Tools::getValue('allpage_1_nb_items')); $this->oPrediggoConfig->allpage_1_variant_id = (int)Tools::safeOutput(Tools::getValue('allpage_1_variant_id')); $this->oPrediggoConfig->allpage_1_hook_name = Tools::safeOutput(Tools::getValue('allpage_1_hook_name')); $this->oPrediggoConfig->allpage_1_template_name = Tools::safeOutput(Tools::getValue('allpage_1_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->allpage_1_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('allpage_1_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('All Page #1 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the homepage recommendations block configuration bloc 1 if (Tools::isSubmit('exportAllPage2RecommendationConfSubmit')) { $this->oPrediggoConfig->allpage_2_activated = Tools::safeOutput(Tools::getValue('allpage_2_activated')); $this->oPrediggoConfig->allpage_2_nb_items = (int)Tools::safeOutput(Tools::getValue('allpage_2_nb_items')); $this->oPrediggoConfig->allpage_2_variant_id = (int)Tools::safeOutput(Tools::getValue('allpage_2_variant_id')); $this->oPrediggoConfig->allpage_2_hook_name = Tools::safeOutput(Tools::getValue('allpage_2_hook_name')); $this->oPrediggoConfig->allpage_2_template_name = Tools::safeOutput(Tools::getValue('allpage_2_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->allpage_2_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('allpage_2_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('All Page #2 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the Product recommendations block configuration bloc 1 if (Tools::isSubmit('exportProductPage0RecommendationConfSubmit')) { $this->oPrediggoConfig->productpage_0_activated = Tools::safeOutput(Tools::getValue('productpage_0_activated')); $this->oPrediggoConfig->productpage_0_nb_items = (int)Tools::safeOutput(Tools::getValue('productpage_0_nb_items')); $this->oPrediggoConfig->productpage_0_variant_id = (int)Tools::safeOutput(Tools::getValue('productpage_0_variant_id')); $this->oPrediggoConfig->productpage_0_hook_name = Tools::safeOutput(Tools::getValue('productpage_0_hook_name')); $this->oPrediggoConfig->productpage_0_template_name = Tools::safeOutput(Tools::getValue('productpage_0_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->productpage_0_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('productpage_0_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Product Page #0 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the Product recommendations block configuration bloc 1 if (Tools::isSubmit('exportProductPage1RecommendationConfSubmit')) { $this->oPrediggoConfig->productpage_1_activated = Tools::safeOutput(Tools::getValue('productpage_1_activated')); $this->oPrediggoConfig->productpage_1_nb_items = (int)Tools::safeOutput(Tools::getValue('productpage_1_nb_items')); $this->oPrediggoConfig->productpage_1_variant_id = (int)Tools::safeOutput(Tools::getValue('productpage_1_variant_id')); $this->oPrediggoConfig->productpage_1_hook_name = Tools::safeOutput(Tools::getValue('productpage_1_hook_name')); $this->oPrediggoConfig->productpage_1_template_name = Tools::safeOutput(Tools::getValue('productpage_1_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->productpage_1_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('productpage_1_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Product Page #1 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the Product recommendations block configuration bloc 1 if (Tools::isSubmit('exportProductPage2RecommendationConfSubmit')) { $this->oPrediggoConfig->productpage_2_activated = Tools::safeOutput(Tools::getValue('productpage_2_activated')); $this->oPrediggoConfig->productpage_2_nb_items = (int)Tools::safeOutput(Tools::getValue('productpage_2_nb_items')); $this->oPrediggoConfig->productpage_2_variant_id = (int)Tools::safeOutput(Tools::getValue('productpage_2_variant_id')); $this->oPrediggoConfig->productpage_2_hook_name = Tools::safeOutput(Tools::getValue('productpage_2_hook_name')); $this->oPrediggoConfig->productpage_2_template_name = Tools::safeOutput(Tools::getValue('productpage_2_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->productpage_2_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('productpage_2_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Product Page #2 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the basket recommendations block configuration if (Tools::isSubmit('exportBasket0RecommendationConfSubmit')) { $this->oPrediggoConfig->basket_0_activated = Tools::safeOutput(Tools::getValue('basket_0_activated')); $this->oPrediggoConfig->basket_0_nb_items = (int)Tools::safeOutput(Tools::getValue('basket_0_nb_items')); $this->oPrediggoConfig->basket_0_variant_id = (int)Tools::safeOutput(Tools::getValue('basket_0_variant_id')); $this->oPrediggoConfig->basket_0_hook_name = Tools::safeOutput(Tools::getValue('basket_0_hook_name')); $this->oPrediggoConfig->basket_0_template_name = Tools::safeOutput(Tools::getValue('basket_0_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->basket_0_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('basket_0_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Basket recommendations block #0 configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } if (Tools::isSubmit('exportBasket1RecommendationConfSubmit')) { $this->oPrediggoConfig->basket_1_activated = Tools::safeOutput(Tools::getValue('basket_1_activated')); $this->oPrediggoConfig->basket_1_nb_items = (int)Tools::safeOutput(Tools::getValue('basket_1_nb_items')); $this->oPrediggoConfig->basket_1_variant_id = (int)Tools::safeOutput(Tools::getValue('basket_1_variant_id')); $this->oPrediggoConfig->basket_1_hook_name = Tools::safeOutput(Tools::getValue('basket_1_hook_name')); $this->oPrediggoConfig->basket_1_template_name = Tools::safeOutput(Tools::getValue('basket_1_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->basket_1_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('basket_1_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Basket recommendations block #1 configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the basket recommendations block configuration if (Tools::isSubmit('exportBasket2RecommendationConfSubmit')) { $this->oPrediggoConfig->basket_2_activated = Tools::safeOutput(Tools::getValue('basket_2_activated')); $this->oPrediggoConfig->basket_2_nb_items = (int)Tools::safeOutput(Tools::getValue('basket_2_nb_items')); $this->oPrediggoConfig->basket_2_variant_id = (int)Tools::safeOutput(Tools::getValue('basket_2_variant_id')); $this->oPrediggoConfig->basket_2_hook_name = Tools::safeOutput(Tools::getValue('basket_2_hook_name')); $this->oPrediggoConfig->basket_2_template_name = Tools::safeOutput(Tools::getValue('basket_2_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->basket_2_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('basket_2_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Basket recommendations block #2 configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } if (Tools::isSubmit('exportBasket3RecommendationConfSubmit')) { $this->oPrediggoConfig->basket_3_activated = Tools::safeOutput(Tools::getValue('basket_3_activated')); $this->oPrediggoConfig->basket_3_nb_items = (int)Tools::safeOutput(Tools::getValue('basket_3_nb_items')); $this->oPrediggoConfig->basket_3_variant_id = (int)Tools::safeOutput(Tools::getValue('basket_3_variant_id')); $this->oPrediggoConfig->basket_3_hook_name = Tools::safeOutput(Tools::getValue('basket_3_hook_name')); $this->oPrediggoConfig->basket_3_template_name = Tools::safeOutput(Tools::getValue('basket_3_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->basket_3_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('basket_3_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Basket recommendations block #3 configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the basket recommendations block configuration if (Tools::isSubmit('exportBasket4RecommendationConfSubmit')) { $this->oPrediggoConfig->basket_4_activated = Tools::safeOutput(Tools::getValue('basket_4_activated')); $this->oPrediggoConfig->basket_4_nb_items = (int)Tools::safeOutput(Tools::getValue('basket_4_nb_items')); $this->oPrediggoConfig->basket_4_variant_id = (int)Tools::safeOutput(Tools::getValue('basket_4_variant_id')); $this->oPrediggoConfig->basket_4_hook_name = Tools::safeOutput(Tools::getValue('basket_4_hook_name')); $this->oPrediggoConfig->basket_4_template_name = Tools::safeOutput(Tools::getValue('basket_4_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->basket_4_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('basket_4_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Basket recommendations block #4 configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the basket recommendations block configuration if (Tools::isSubmit('exportBasket5RecommendationConfSubmit')) { $this->oPrediggoConfig->basket_5_activated = Tools::safeOutput(Tools::getValue('basket_5_activated')); $this->oPrediggoConfig->basket_5_nb_items = (int)Tools::safeOutput(Tools::getValue('basket_5_nb_items')); $this->oPrediggoConfig->basket_5_variant_id = (int)Tools::safeOutput(Tools::getValue('basket_5_variant_id')); $this->oPrediggoConfig->basket_5_hook_name = Tools::safeOutput(Tools::getValue('basket_5_hook_name')); $this->oPrediggoConfig->basket_5_template_name = Tools::safeOutput(Tools::getValue('basket_5_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->basket_5_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('basket_5_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Basket recommendations block #3 configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the Product recommendations block configuration bloc 1 if (Tools::isSubmit('exportCategory0RecommendationConfSubmit')) { $this->oPrediggoConfig->category_0_activated = Tools::safeOutput(Tools::getValue('category_0_activated')); $this->oPrediggoConfig->category_0_nb_items = (int)Tools::safeOutput(Tools::getValue('category_0_nb_items')); $this->oPrediggoConfig->category_0_variant_id = (int)Tools::safeOutput(Tools::getValue('category_0_variant_id')); $this->oPrediggoConfig->category_0_hook_name = Tools::safeOutput(Tools::getValue('category_0_hook_name')); $this->oPrediggoConfig->category_0_template_name = Tools::safeOutput(Tools::getValue('category_0_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->category_0_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('category_0_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Category Page #0 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the Product recommendations block configuration bloc 1 if (Tools::isSubmit('exportCategory1RecommendationConfSubmit')) { $this->oPrediggoConfig->category_1_activated = Tools::safeOutput(Tools::getValue('category_1_activated')); $this->oPrediggoConfig->category_1_nb_items = (int)Tools::safeOutput(Tools::getValue('category_1_nb_items')); $this->oPrediggoConfig->category_1_variant_id = (int)Tools::safeOutput(Tools::getValue('category_1_variant_id')); $this->oPrediggoConfig->category_1_hook_name = Tools::safeOutput(Tools::getValue('category_1_hook_name')); $this->oPrediggoConfig->category_1_template_name = Tools::safeOutput(Tools::getValue('category_1_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->category_1_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('category_1_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Category Page #1 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the Product recommendations block configuration bloc 1 if (Tools::isSubmit('exportCategory2RecommendationConfSubmit')) { $this->oPrediggoConfig->category_2_activated = Tools::safeOutput(Tools::getValue('category_2_activated')); $this->oPrediggoConfig->category_2_nb_items = (int)Tools::safeOutput(Tools::getValue('category_2_nb_items')); $this->oPrediggoConfig->category_2_variant_id = (int)Tools::safeOutput(Tools::getValue('category_2_variant_id')); $this->oPrediggoConfig->productpage_2_hook_name = Tools::safeOutput(Tools::getValue('productpage_2_hook_name')); $this->oPrediggoConfig->productpage_2_template_name = Tools::safeOutput(Tools::getValue('productpage_2_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->productpage_2_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('productpage_2_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Category Page #2 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the Product recommendations block configuration bloc 1 if (Tools::isSubmit('exportCustomer0RecommendationConfSubmit')) { $this->oPrediggoConfig->customer_0_activated = Tools::safeOutput(Tools::getValue('customer_0_activated')); $this->oPrediggoConfig->customer_0_nb_items = (int)Tools::safeOutput(Tools::getValue('customer_0_nb_items')); $this->oPrediggoConfig->customer_0_variant_id = (int)Tools::safeOutput(Tools::getValue('customer_0_variant_id')); $this->oPrediggoConfig->customer_0_hook_name = Tools::safeOutput(Tools::getValue('customer_0_hook_name')); $this->oPrediggoConfig->customer_0_template_name = Tools::safeOutput(Tools::getValue('customer_0_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->customer_0_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('customer_0_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Customer Page #0 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } // Set the Product recommendations block configuration bloc 1 if (Tools::isSubmit('exportCustomer1RecommendationConfSubmit')) { $this->oPrediggoConfig->customer_1_activated = Tools::safeOutput(Tools::getValue('customer_1_activated')); $this->oPrediggoConfig->customer_1_nb_items = (int)Tools::safeOutput(Tools::getValue('customer_1_nb_items')); $this->oPrediggoConfig->customer_1_variant_id = (int)Tools::safeOutput(Tools::getValue('customer_1_variant_id')); $this->oPrediggoConfig->customer_1_hook_name = Tools::safeOutput(Tools::getValue('customer_1_hook_name')); $this->oPrediggoConfig->customer_1_template_name = Tools::safeOutput(Tools::getValue('customer_1_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->customer_1_block_label[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('customer_1_block_label_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Customer Page #1 recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the homepage recommendations block configuration of recommendations settings'); } /*// Set the customers pages recommendations block configuration if (Tools::isSubmit('exportCustomerRecommendationConfSubmit')) { $this->oPrediggoConfig->customer_recommendations = Tools::safeOutput(Tools::getValue('customer_recommendations')); $this->oPrediggoConfig->customer_nb_items = (int)Tools::safeOutput(Tools::getValue('customer_nb_items')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->customer_block_title[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('customer_block_title_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Customers pages recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the customers pages recommendations block configuration of recommendations settings'); }*/ // Set the 404 page recommendations block configuration if (Tools::isSubmit('export404RecommendationConfSubmit')) { $this->oPrediggoConfig->error_recommendations = Tools::safeOutput(Tools::getValue('error_recommendations')); $this->oPrediggoConfig->error_nb_items = (int)Tools::safeOutput(Tools::getValue('error_nb_items')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->error_block_title[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('error_block_title_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('404 page recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the 404 page recommendations block configuration of recommendations settings'); } // Set the blocklayered module recommendations block configuration if (Tools::isSubmit('exportBlocklayeredRecommendationConfSubmit')) { $this->oPrediggoConfig->blocklayered_0_recommendations = Tools::safeOutput(Tools::getValue('blocklayered_0_recommendations')); $this->oPrediggoConfig->blocklayered_0_nb_items = (int)Tools::safeOutput(Tools::getValue('blocklayered_0_nb_items')); $this->oPrediggoConfig->blocklayered_0_variant_id = Tools::safeOutput(Tools::getValue('blocklayered_0_variant_id')); $this->oPrediggoConfig->blocklayered_0_hook_name = Tools::safeOutput(Tools::getValue('blocklayered_0_hook_name')); $this->oPrediggoConfig->blocklayered_0_template_name = Tools::safeOutput(Tools::getValue('blocklayered_0_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->blocklayered_0_block_title[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('blocklayered_0_block_title_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Block layered module recommendations block configuration settings updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the block layered module recommendations block configuration of recommendations settings'); } // Set the searchs main configuration if (Tools::isSubmit('mainSearchConfSubmit')) { $this->oPrediggoConfig->search_active = (int)Tools::safeOutput(Tools::getValue('search_active')); $this->oPrediggoConfig->search_main_template_name = Tools::safeOutput(Tools::getValue('search_main_template_name')); $this->oPrediggoConfig->pagination_template_name = Tools::safeOutput(Tools::getValue('pagination_template_name')); $this->oPrediggoConfig->search_filter_block_template_name = Tools::safeOutput(Tools::getValue('search_filter_block_template_name')); $this->oPrediggoConfig->search_filters_sort_by_template_name = Tools::safeOutput(Tools::getValue('search_filters_sort_by_template_name')); $this->oPrediggoConfig->prod_compare_template_name = Tools::safeOutput(Tools::getValue('prod_compare_template_name')); $this->oPrediggoConfig->prod_list_template_name = Tools::safeOutput(Tools::getValue('prod_list_template_name')); $this->oPrediggoConfig->searchandizing_active = (int)Tools::safeOutput(Tools::getValue('searchandizing_active')); $this->oPrediggoConfig->layered_navigation_active = (int)Tools::safeOutput(Tools::getValue('layered_navigation_active')); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Main configuration settings of searchs updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the main configuration of searchs settings'); } // Set the category main configuration if (Tools::isSubmit('mainCategoryConfSubmit')) { $this->oPrediggoConfig->category_active = (int)Tools::safeOutput(Tools::getValue('category_active')); $this->oPrediggoConfig->category_0_template_name = Tools::safeOutput(Tools::getValue('category_0_template_name')); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Main configuration settings of Category updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the main configuration of Category settings'); } // Set the searchs main configuration if (Tools::isSubmit('searchandizingSubmit')) { $this->oPrediggoConfig->searchandizing_active = (int)Tools::safeOutput(Tools::getValue('searchandizing_active')); $this->oPrediggoConfig->layered_navigation_active = (int)Tools::safeOutput(Tools::getValue('layered_navigation_active')); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Main configuration settings of searchs updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the main configuration of searchs settings'); } // Set the searchs autocompletion configuration if (Tools::isSubmit('exportSearchAutocompletionConfSubmit')) { $this->oPrediggoConfig->autocompletion_active = (int)Tools::safeOutput(Tools::getValue('autocompletion_active')); $this->oPrediggoConfig->search_nb_min_chars = (int)Tools::safeOutput(Tools::getValue('search_nb_min_chars')); $this->oPrediggoConfig->autocompletion_nb_items = (int)Tools::safeOutput(Tools::getValue('autocompletion_nb_items')); $this->oPrediggoConfig->search_0_template_name = Tools::safeOutput(Tools::getValue('search_0_template_name')); $this->oPrediggoConfig->autoc_template_name = Tools::safeOutput(Tools::getValue('autoc_template_name')); $this->oPrediggoConfig->autop_template_name = Tools::safeOutput(Tools::getValue('autop_template_name')); $this->oPrediggoConfig->autocat_template_name = Tools::safeOutput(Tools::getValue('autocat_template_name')); $this->oPrediggoConfig->autos_template_name = Tools::safeOutput(Tools::getValue('autos_template_name')); foreach ($this->context->controller->getLanguages() as $aLanguage) $this->oPrediggoConfig->suggest_words[(int)$aLanguage['id_lang']] = Tools::safeOutput(Tools::getValue('suggest_words_'.(int)$aLanguage['id_lang'])); if ($this->oPrediggoConfig->save()) $this->_confirmations[] = $this->displayConfirmation('Main configuration settings of search autocompletion updated'); else $this->_errors[] = Tools::displayError('An error occurred while updating the main configuration of search autocompletion settings'); } } /** * Display the BO html with smart templates */ public function _displayForm() { // Add the specific jquery ui plugins, module JS & CSS $this->context->controller->addJqueryUI('ui.tabs'); $this->context->controller->addJqueryPlugin('autocomplete'); if (Tools::substr(_PS_VERSION_, 0, 3) == 1.5) $this->context->controller->addJs(($this->_path).'js/admin/'.$this->name.'1_5.js'); elseif (Tools::substr(_PS_VERSION_, 0, 3) == 1.6) $this->context->controller->addJs(($this->_path).'js/admin/'.$this->name.'.js'); $this->context->controller->addCss(array( ($this->_path).'css/admin/'.$this->name.'.css' => 'all', _PS_JS_DIR_.'jquery/ui/themes/base/jquery.ui.all.css' )); /* Display the errors / warnings / confirmations */ $this->context->smarty->assign(array( 'aPrediggoWarnings' => $this->_warnings, 'aPrediggoConfirmations' => $this->_confirmations, 'aPrediggoErrors' => $this->_errors, 'path' => $this->_path, 'lang_iso' => $this->context->language->iso_code, )); // Display the errors $this->_html .= $this->display(__FILE__, 'views/templates/admin/errors.tpl'); // Display the tabs $this->_html .= $this->display(__FILE__, 'views/templates/admin/tabs.tpl'); $this->_display = 'index'; $iShopContext = (int)(Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP); /* * MAIN CONFIGURATION */ $this->fields_form['main_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Main Configuration'), 'image' => _PS_ADMIN_IMG_.'employee.gif' ), 'input' => array( array( 'label' => $this->l('Shop Name'), 'type' => 'text', 'name' => 'shop_name', 'size' => 50, 'required' => true, 'desc' => $this->l('Shop Name of the current shop') ), array( 'label' => $this->l('Token ID'), 'type' => 'text', 'name' => 'token_id', 'size' => 50, 'required' => true, 'desc' => $this->l('Token ID of the current shop') ), array( 'label' => $this->l('Profil ID'), 'type' => 'text', 'name' => 'gateway_profil_id', 'size' => 50, 'required' => true, 'desc' => $this->l('Profile ID of the current shop') ), array( 'type' => 'button', 'name' => 'mainConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), ), ), ); $this->fields_value['shop_name'] = $this->oPrediggoConfig->shop_name; $this->fields_value['token_id'] = $this->oPrediggoConfig->token_id; $this->fields_value['gateway_profil_id'] = (int)$this->context->shop->id; /* * SERVER CONFIGURATION */ $this->fields_form['server_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Server Configuration'), 'image' => _PS_ADMIN_IMG_.'manufacturers.gif' ), 'input' => array( array( 'label' => $this->l('Web Site ID'), 'type' => 'text', 'name' => 'web_site_id', 'size' => 50, 'required' => true, 'desc' => $this->l('Login of the Prediggo solution') ), array( 'label' => $this->l('URL of prediggo server:'), 'type' => 'text', 'name' => 'server_url_recommendations', 'size' => 50, 'required' => true, 'desc' => $this->l('Url called to get the prediggo solution'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'serverConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), ), ), ); $this->fields_value['web_site_id'] = $this->oPrediggoConfig->web_site_id; $this->fields_value['server_url_recommendations'] = $this->oPrediggoConfig->server_url_recommendations; /* * IMPORT/EXPORT CLIENT CONFIGURATION */ $this->fields_form['client_import_export_configuration']['form'] = array( 'legend' => array( 'title' => $this->l('Import/Export client configuration'), 'image' => _PS_ADMIN_IMG_.'quick.gif' ), 'input' => array( array( 'label' => $this->l('Reset All Hooks:'), 'type' => 'button', 'name' => 'registerAllHooks', 'class' => 'button', 'title' => $this->l(' Reset All Hooks '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); /* * LOG CONFIGURATION */ $this->fields_form['logs_configuration']['form'] = array( 'legend' => array( 'title' => $this->l('Logs configuration'), 'image' => _PS_ADMIN_IMG_.'quick.gif' ), 'input' => array( array( 'label' => $this->l('Logs activation'), 'type' => 'radio', 'name' => 'logs_generation', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'logs_generation_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'logs_generation_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('The logs files are stored in the folder "logs" of the module'), ), array( 'type' => 'button', 'name' => 'logsSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':'') ), ), ); $this->fields_value['logs_generation'] = (int)$this->oPrediggoConfig->logs_generation; /* * EXPORT MAIN CONFIGURATION */ $sCronFilePath = Tools::getShopDomain(true).str_replace(_PS_ROOT_DIR_.'/', __PS_BASE_URI__, $this->_path).'crons/export.php?token='.Tools::getAdminToken('DataExtractorController'); $this->fields_form['export_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Export Configuration'), 'image' => _PS_ADMIN_IMG_.'cog.gif' ), 'input' => array( array( 'label' => $this->l('Products file generation activation'), 'type' => 'radio', 'name' => 'products_file_generation', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'products_file_generation_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'products_file_generation_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Define if the products can be exported into a zip file for the use of the prediggo solution'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Orders file generation activation'), 'type' => 'radio', 'name' => 'orders_file_generation', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'orders_file_generation_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'orders_file_generation_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Define if the orders can be exported into a zip file for the use of the prediggo solution'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Customers file generation activation'), 'type' => 'radio', 'name' => 'customers_file_generation', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'customers_file_generation_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'customers_file_generation_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Define if the customers can be exported into a zip file for the use of the prediggo solution'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Product\'s image cover export activation'), 'type' => 'radio', 'name' => 'export_product_image', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'export_product_image_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'export_product_image_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Define if the product\'s image covers are included in the export of the products'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Product\'s description export activation'), 'type' => 'radio', 'name' => 'export_product_description', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'export_product_description_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'export_product_description_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Define if the product\'s descriptions are included in the export of the products'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Product\'s active only export activation'), 'type' => 'radio', 'name' => 'export_product_active', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'export_product_active_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'export_product_active_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('When activated only active products included and when not activated disable products included'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Product\'s price > 0 only export activation'), 'type' => 'radio', 'name' => 'export_product_price', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'export_product_price_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'export_product_price_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('When activated only price > 0 included and when not activated price >=0 included'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of days considering that an order can be exported:'), 'type' => 'text', 'name' => 'nb_days_order_valide', 'required' => true, 'desc' => $this->l('Number of days to select orders into the export by their date of creation'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of days considering that a customer can be exported:'), 'type' => 'text', 'name' => 'nb_days_customer_last_visit_valide', 'required' => true, 'desc' => $this->l('Number of days to select customers into the export by their date of creation'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => false, 'type' => 'free', 'name' => 'protection_xml_path', ), array( 'label' => $this->l('Launch the files export by clicking on the following button:'), 'type' => 'button', 'name' => 'manualExportSubmit', 'class' => 'button', 'title' => $this->l(' Export files '), 'disabled' => ((int)($iShopContext)?'disabled':'') ), ) ); $this->fields_value['products_file_generation'] = (int)$this->oPrediggoConfig->products_file_generation; $this->fields_value['orders_file_generation'] = (int)$this->oPrediggoConfig->orders_file_generation; $this->fields_value['customers_file_generation'] = (int)$this->oPrediggoConfig->customers_file_generation; $this->fields_value['export_product_image'] = (int)$this->oPrediggoConfig->export_product_image; $this->fields_value['export_product_description'] = (int)$this->oPrediggoConfig->export_product_description; $this->fields_value['export_product_active'] = (int)$this->oPrediggoConfig->export_product_active; $this->fields_value['export_product_price'] = (int)$this->oPrediggoConfig->export_product_price; $this->fields_value['nb_days_order_valide'] = (int)$this->oPrediggoConfig->nb_days_order_valide; $this->fields_value['nb_days_customer_last_visit_valide'] = (int)$this->oPrediggoConfig->nb_days_customer_last_visit_valide; $this->fields_value['protection_xml_path'] = $this->l('If you want to execute the export by a cron, use the following link:').' <a href="'.$sCronFilePath.'">'.$sCronFilePath.'</a>.</br>'; /* * ATTRIBUTE SELECTION */ $this->fields_form['attributes_selection']['form'] = array( 'legend' => array( 'title' => $this->l('Prediggo attributes selection'), 'image' => _PS_ADMIN_IMG_.'quick.gif' ), 'input' => array( array( 'label' => $this->l('Attributes:'), 'type' => 'attribute_selector', 'name' => 'attribute_selector', 'names' => array( 'attributes' => 'attributes_groups_ids[]', 'features' => 'features_ids[]' ), 'values' => array( 'attributes' => AttributeGroup::getAttributesGroups((int)$this->context->cookie->id_lang), 'features' => Feature::getFeatures((int)$this->context->cookie->id_lang) ), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportPrediggoAttributesSubmit', 'class' => 'button', 'title' => $this->l(' Save the prediggo attributes '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['attribute_selector'] = array( 'attributes' => explode(',', $this->oPrediggoConfig->attributes_groups_ids), 'features' => explode(',', $this->oPrediggoConfig->features_ids), ); /* * RECOMMANDATIONS BLACK LIST */ $this->fields_form['black_list_reco']['form'] = array( 'legend' => array( 'title' => $this->l('Products not included in the recommendations'), 'image' => _PS_ADMIN_IMG_.'nav-logout.gif' ), 'input' => array( array( 'label' => $this->l('Product:'), 'type' => 'autocomplete', 'name' => 'products_ids_not_recommendable', 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportNotRecoSubmit', 'class' => 'button', 'title' => $this->l(' Save the black list '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'resetRecoList', 'class' => 'button', 'title' => $this->l(' Reset the black list '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['products_ids_not_recommendable'] = array(); if (!empty($this->oPrediggoConfig->products_ids_not_recommendable)) foreach (explode(',', $this->oPrediggoConfig->products_ids_not_recommendable) as $iID) { $oProduct = new Product((int)$iID, false, (int)$this->context->cookie->id_lang, (int)$this->context->shop->id, $this->context); $this->fields_value['products_ids_not_recommendable'][] = array( 'id' => (int)$iID, 'name' => $oProduct->name ); unset($oProduct); } /* * SEARCH BLACK LIST */ $this->fields_form['black_list_search']['form'] = array( 'legend' => array( 'title' => $this->l('Products not included in the searchs'), 'image' => _PS_ADMIN_IMG_.'nav-logout.gif' ), 'input' => array( array( 'label' => $this->l('Product:'), 'type' => 'autocomplete', 'name' => 'products_ids_not_searchable', 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportNotSearchSubmit', 'class' => 'button', 'title' => $this->l(' Save the black list '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'resetSearchList', 'class' => 'button', 'title' => $this->l(' Reset the black list '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['products_ids_not_searchable'] = array(); if (!empty($this->oPrediggoConfig->products_ids_not_searchable)) foreach (explode(',', $this->oPrediggoConfig->products_ids_not_searchable) as $iID) { $oProduct = new Product((int)$iID, false, (int)$this->context->cookie->id_lang, (int)$this->context->shop->id, $this->context); $this->fields_value['products_ids_not_searchable'][] = array( 'id' => (int)$iID, 'name' => $oProduct->name ); unset($oProduct); } /* * HTACCESS PROTECTION */ $sExportRepositoryPath = Tools::getShopDomain(true).str_replace(_PS_ROOT_DIR_.'/', __PS_BASE_URI__, $this->_path).'xmlfiles/'; $this->fields_form['htaccess_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Export File protection'), 'image' => _PS_ADMIN_IMG_.'access.png' ), 'input' => array( array( 'type' => 'free', 'name' => 'export_cron', 'label' => false, ), array( 'label' => $this->l('Login:'), 'type' => 'text', 'name' => 'htpasswd_user', 'required' => true, 'desc' => $this->l('Login of the export folder protection') ), array( 'label' => $this->l('Password:'), 'type' => 'text', 'name' => 'htpasswd_pwd', 'required' => true, 'desc' => $this->l('Password of the export folder protection') ), array( 'type' => 'button', 'name' => 'exportProtectionConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), ), ), ); $this->fields_value['htpasswd_user'] = $this->oPrediggoConfig->htpasswd_user; $this->fields_value['htpasswd_pwd'] = $this->oPrediggoConfig->htpasswd_pwd; $this->fields_value['export_cron'] = $this->l('Your files are created into your PrestaShop plateform into the following folder :'). ' <a href="'.$sExportRepositoryPath.'">'.$sExportRepositoryPath.'</a>.<br/>'. $this->l('The data contained into these files are critical and require a protection.'). $this->l('Please restrict the access to these files by applying a protection with an authentication requiring a login and a password!').'<br/>'. $this->l('The Basic Authentication module is not configured by default on Nginx web server. Please, refer to this documentation to configure it : http://wiki.nginx.org/HttpAuthBasicModule.'); /* * HOMEPAGE RECOMMENDATIONS - block 0 */ $this->fields_form['home_reco_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Home Page Block Configuration - #0'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'home_0_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'home_0_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'home_0_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the homepage of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'home_0_nb_items', 'required' => true, 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'home_0_variant_id', 'required' => true, 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'home_0_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksHomePage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'required' => true, 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template Home 0:'), 'type' => 'text', 'size' => 100, 'name' => 'home_0_template_name', 'lang' => false, 'required' => true, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'home_0_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportHome0RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['home_0_activated'] = (int)$this->oPrediggoConfig->home_0_activated; $this->fields_value['home_0_nb_items'] = (int)$this->oPrediggoConfig->home_0_nb_items; $this->fields_value['home_0_variant_id'] = (int)$this->oPrediggoConfig->home_0_variant_id; $this->fields_value['home_0_hook_name'] = $this->oPrediggoConfig->home_0_hook_name; $this->fields_value['home_0_template_name'] = $this->oPrediggoConfig->home_0_template_name; $this->fields_value['home_0_block_label'] = $this->oPrediggoConfig->home_0_block_label; /* * HOMEPAGE RECOMMENDATIONS - block 1 */ $this->fields_form['home_1_reco_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Home Page Block Configuration - #1'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'home_1_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'home_1_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'home_1_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the homepage of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'home_1_nb_items', 'required' => true, 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'home_1_variant_id', 'required' => true, 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'home_1_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksHomePage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'required' => true, 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template Home 1:'), 'type' => 'text', 'size' => 100, 'name' => 'home_1_template_name', 'lang' => false, 'required' => true, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'home_1_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportHome1RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['home_1_activated'] = (int)$this->oPrediggoConfig->home_1_activated; $this->fields_value['home_1_nb_items'] = (int)$this->oPrediggoConfig->home_1_nb_items; $this->fields_value['home_1_variant_id'] = (int)$this->oPrediggoConfig->home_1_variant_id; $this->fields_value['home_1_hook_name'] = $this->oPrediggoConfig->home_1_hook_name; $this->fields_value['home_1_template_name'] = $this->oPrediggoConfig->home_1_template_name; $this->fields_value['home_1_block_label'] = $this->oPrediggoConfig->home_1_block_label; /* * ALL PAGE RECOMMENDATIONS - block 0 */ $this->fields_form['allpage_0_conf']['form'] = array( 'legend' => array( 'title' => $this->l('All Page Block Configuration - #0'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'allpage_0_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'allpage_0_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'allpage_0_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in all page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'allpage_0_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'allpage_0_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'allpage_0_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksAllPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template All Page 0:'), 'type' => 'text', 'size' => 100, 'name' => 'allpage_0_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'allpage_0_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportAllPage0RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['allpage_0_activated'] = (int)$this->oPrediggoConfig->allpage_0_activated; $this->fields_value['allpage_0_nb_items'] = (int)$this->oPrediggoConfig->allpage_0_nb_items; $this->fields_value['allpage_0_variant_id'] = (int)$this->oPrediggoConfig->allpage_0_variant_id; $this->fields_value['allpage_0_hook_name'] = $this->oPrediggoConfig->allpage_0_hook_name; $this->fields_value['allpage_0_template_name'] = $this->oPrediggoConfig->allpage_0_template_name; $this->fields_value['allpage_0_block_label'] = $this->oPrediggoConfig->allpage_0_block_label; /* * ALL PAGE RECOMMENDATIONS - block 1 */ $this->fields_form['allpage_1_conf']['form'] = array( 'legend' => array( 'title' => $this->l('All Page Block Configuration - #1'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'allpage_1_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'allpage_1_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'allpage_1_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in all page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'allpage_1_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'allpage_1_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'allpage_1_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksAllPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template All Page 1:'), 'type' => 'text', 'size' => 100, 'name' => 'allpage_1_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'allpage_1_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportAllPage1RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['allpage_1_activated'] = (int)$this->oPrediggoConfig->allpage_1_activated; $this->fields_value['allpage_1_nb_items'] = (int)$this->oPrediggoConfig->allpage_1_nb_items; $this->fields_value['allpage_1_variant_id'] = (int)$this->oPrediggoConfig->allpage_1_variant_id; $this->fields_value['allpage_1_hook_name'] = $this->oPrediggoConfig->allpage_1_hook_name; $this->fields_value['allpage_1_template_name'] = $this->oPrediggoConfig->allpage_1_template_name; $this->fields_value['allpage_1_block_label'] = $this->oPrediggoConfig->allpage_1_block_label; /* * ALL PAGE RECOMMENDATIONS - block 2 */ $this->fields_form['allpage_2_conf']['form'] = array( 'legend' => array( 'title' => $this->l('All Page Block Configuration - #2'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'allpage_2_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'allpage_2_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'allpage_2_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in all page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'allpage_2_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'allpage_2_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'allpage_2_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksAllPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template All Page 2:'), 'type' => 'text', 'size' => 100, 'name' => 'allpage_2_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'allpage_2_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportAllPage2RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['allpage_2_activated'] = (int)$this->oPrediggoConfig->allpage_2_activated; $this->fields_value['allpage_2_nb_items'] = (int)$this->oPrediggoConfig->allpage_2_nb_items; $this->fields_value['allpage_2_variant_id'] = (int)$this->oPrediggoConfig->allpage_2_variant_id; $this->fields_value['allpage_2_hook_name'] = $this->oPrediggoConfig->allpage_2_hook_name; $this->fields_value['allpage_2_template_name'] = $this->oPrediggoConfig->allpage_2_template_name; $this->fields_value['allpage_2_block_label'] = $this->oPrediggoConfig->allpage_2_block_label; /* * PRODUCT PAGE RECOMMENDATIONS - block 0 */ $this->fields_form['productpage_0_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Product Page Block Configuration - #0'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'productpage_0_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'productpage_0_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'productpage_0_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the product page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'productpage_0_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'productpage_0_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'productpage_0_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksProductPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Product Page 0:'), 'type' => 'text', 'size' => 100, 'name' => 'productpage_0_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'productpage_0_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportProductPage0RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['productpage_0_activated'] = (int)$this->oPrediggoConfig->productpage_0_activated; $this->fields_value['productpage_0_nb_items'] = (int)$this->oPrediggoConfig->productpage_0_nb_items; $this->fields_value['productpage_0_variant_id'] = (int)$this->oPrediggoConfig->productpage_0_variant_id; $this->fields_value['productpage_0_hook_name'] = $this->oPrediggoConfig->productpage_0_hook_name; $this->fields_value['productpage_0_template_name'] = $this->oPrediggoConfig->productpage_0_template_name; $this->fields_value['productpage_0_block_label'] = $this->oPrediggoConfig->productpage_0_block_label; /* * PRODUCT PAGE RECOMMENDATIONS - block 1 */ $this->fields_form['productpage_1_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Product Page Block Configuration - #1'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'productpage_1_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'productpage_1_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'productpage_1_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the product page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'productpage_1_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'productpage_1_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'productpage_1_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksProductPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Product Page 1:'), 'type' => 'text', 'size' => 100, 'name' => 'productpage_1_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'productpage_1_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportProductPage1RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['productpage_1_activated'] = (int)$this->oPrediggoConfig->productpage_1_activated; $this->fields_value['productpage_1_nb_items'] = (int)$this->oPrediggoConfig->productpage_1_nb_items; $this->fields_value['productpage_1_variant_id'] = (int)$this->oPrediggoConfig->productpage_1_variant_id; $this->fields_value['productpage_1_hook_name'] = $this->oPrediggoConfig->productpage_1_hook_name; $this->fields_value['productpage_1_template_name'] = $this->oPrediggoConfig->productpage_1_template_name; $this->fields_value['productpage_1_block_label'] = $this->oPrediggoConfig->productpage_1_block_label; /* * PRODUCT PAGE RECOMMENDATIONS - block 2 */ $this->fields_form['productpage_2_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Product Page Block Configuration - #2'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'productpage_2_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'productpage_2_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'productpage_2_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the product page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'productpage_2_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'productpage_2_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'productpage_2_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksProductPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Product Page 2:'), 'type' => 'text', 'size' => 100, 'name' => 'productpage_2_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'productpage_2_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportProductPage2RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['productpage_2_activated'] = (int)$this->oPrediggoConfig->productpage_2_activated; $this->fields_value['productpage_2_nb_items'] = (int)$this->oPrediggoConfig->productpage_2_nb_items; $this->fields_value['productpage_2_variant_id'] = (int)$this->oPrediggoConfig->productpage_2_variant_id; $this->fields_value['productpage_2_hook_name'] = $this->oPrediggoConfig->productpage_2_hook_name; $this->fields_value['productpage_2_template_name'] = $this->oPrediggoConfig->productpage_2_template_name; $this->fields_value['productpage_2_block_label'] = $this->oPrediggoConfig->productpage_2_block_label; /* * BASKET RECOMMENDATIONS - block 0 */ $this->fields_form['basket_0_reco_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Basket Page Block Configuration - #0'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'basket_0_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'basket_0_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'basket_0_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the basket of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'basket_0_nb_items', 'required' => true, 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'basket_0_variant_id', 'required' => true, 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'basket_0_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksBasketPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'required' => true, 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template Basket 0:'), 'type' => 'text', 'size' => 100, 'name' => 'basket_0_template_name', 'lang' => false, 'required' => true, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'basket_0_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportBasket0RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['basket_0_activated'] = (int)$this->oPrediggoConfig->basket_0_activated; $this->fields_value['basket_0_nb_items'] = (int)$this->oPrediggoConfig->basket_0_nb_items; $this->fields_value['basket_0_variant_id'] = (int)$this->oPrediggoConfig->basket_0_variant_id; $this->fields_value['basket_0_hook_name'] = $this->oPrediggoConfig->basket_0_hook_name; $this->fields_value['basket_0_template_name'] = $this->oPrediggoConfig->basket_0_template_name; $this->fields_value['basket_0_block_label'] = $this->oPrediggoConfig->basket_0_block_label; /* * Basket RECOMMENDATIONS - block 1 */ $this->fields_form['basket_1_reco_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Basket Page Block Configuration - #1'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'basket_1_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'basket_1_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'basket_1_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the basket page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'basket_1_nb_items', 'required' => true, 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'basket_1_variant_id', 'required' => true, 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'basket_1_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksBasketPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'required' => true, 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template basket 1:'), 'type' => 'text', 'size' => 100, 'name' => 'basket_1_template_name', 'lang' => false, 'required' => true, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'basket_1_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportBasket1RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['basket_1_activated'] = (int)$this->oPrediggoConfig->basket_1_activated; $this->fields_value['basket_1_nb_items'] = (int)$this->oPrediggoConfig->basket_1_nb_items; $this->fields_value['basket_1_variant_id'] = (int)$this->oPrediggoConfig->basket_1_variant_id; $this->fields_value['basket_1_hook_name'] = $this->oPrediggoConfig->basket_1_hook_name; $this->fields_value['basket_1_template_name'] = $this->oPrediggoConfig->basket_1_template_name; $this->fields_value['basket_1_block_label'] = $this->oPrediggoConfig->basket_1_block_label; /* * BASKET RECOMMENDATIONS - block 2 */ $this->fields_form['basket_2_reco_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Basket Page Block Configuration - #2'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'basket_2_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'basket_2_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'basket_2_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the basket of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'basket_2_nb_items', 'required' => true, 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'basket_2_variant_id', 'required' => true, 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'basket_2_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksBasketPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'required' => true, 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template basket 2:'), 'type' => 'text', 'size' => 100, 'name' => 'basket_2_template_name', 'lang' => false, 'required' => true, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'basket_2_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportBasket2RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['basket_2_activated'] = (int)$this->oPrediggoConfig->basket_2_activated; $this->fields_value['basket_2_nb_items'] = (int)$this->oPrediggoConfig->basket_2_nb_items; $this->fields_value['basket_2_variant_id'] = (int)$this->oPrediggoConfig->basket_2_variant_id; $this->fields_value['basket_2_hook_name'] = $this->oPrediggoConfig->basket_2_hook_name; $this->fields_value['basket_2_template_name'] = $this->oPrediggoConfig->basket_2_template_name; $this->fields_value['basket_2_block_label'] = $this->oPrediggoConfig->basket_2_block_label; /* * Basket RECOMMENDATIONS - block 3 */ $this->fields_form['basket_3_reco_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Basket Page Block Configuration - #3'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'basket_3_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'basket_3_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'basket_3_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the basket page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'basket_3_nb_items', 'required' => true, 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'basket_3_variant_id', 'required' => true, 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'basket_3_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksBasketPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'required' => true, 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template basket 3:'), 'type' => 'text', 'size' => 100, 'name' => 'basket_3_template_name', 'lang' => false, 'required' => true, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'basket_3_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportBasket3RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['basket_3_activated'] = (int)$this->oPrediggoConfig->basket_3_activated; $this->fields_value['basket_3_nb_items'] = (int)$this->oPrediggoConfig->basket_3_nb_items; $this->fields_value['basket_3_variant_id'] = (int)$this->oPrediggoConfig->basket_3_variant_id; $this->fields_value['basket_3_hook_name'] = $this->oPrediggoConfig->basket_3_hook_name; $this->fields_value['basket_3_template_name'] = $this->oPrediggoConfig->basket_3_template_name; $this->fields_value['basket_3_block_label'] = $this->oPrediggoConfig->basket_3_block_label; /* * BASKET RECOMMENDATIONS - block 4 */ $this->fields_form['basket_4_reco_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Basket Page Block Configuration - #4'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'basket_4_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'basket_4_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'basket_4_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the basket page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'basket_4_nb_items', 'required' => true, 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'basket_4_variant_id', 'required' => true, 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'basket_4_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksBasketPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'required' => true, 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template Basket 4:'), 'type' => 'text', 'size' => 100, 'name' => 'basket_4_template_name', 'lang' => false, 'required' => true, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'basket_4_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportBasket4RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['basket_4_activated'] = (int)$this->oPrediggoConfig->basket_4_activated; $this->fields_value['basket_4_nb_items'] = (int)$this->oPrediggoConfig->basket_4_nb_items; $this->fields_value['basket_4_variant_id'] = (int)$this->oPrediggoConfig->basket_4_variant_id; $this->fields_value['basket_4_hook_name'] = $this->oPrediggoConfig->basket_4_hook_name; $this->fields_value['basket_4_template_name'] = $this->oPrediggoConfig->basket_4_template_name; $this->fields_value['basket_4_block_label'] = $this->oPrediggoConfig->basket_4_block_label; /* * Basket RECOMMENDATIONS - block 5 */ $this->fields_form['basket_5_reco_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Basket Page Block Configuration - #5'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'basket_5_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'basket_5_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'basket_5_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the basket page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'basket_5_nb_items', 'required' => true, 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'basket_5_variant_id', 'required' => true, 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'basket_5_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksBasketPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'required' => true, 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template basket 5:'), 'type' => 'text', 'size' => 100, 'name' => 'basket_5_template_name', 'lang' => false, 'required' => true, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'basket_5_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportBasket5RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['basket_5_activated'] = (int)$this->oPrediggoConfig->basket_5_activated; $this->fields_value['basket_5_nb_items'] = (int)$this->oPrediggoConfig->basket_5_nb_items; $this->fields_value['basket_5_variant_id'] = (int)$this->oPrediggoConfig->basket_5_variant_id; $this->fields_value['basket_5_hook_name'] = $this->oPrediggoConfig->basket_5_hook_name; $this->fields_value['basket_5_template_name'] = $this->oPrediggoConfig->basket_5_template_name; $this->fields_value['basket_5_block_label'] = $this->oPrediggoConfig->basket_5_block_label; /* * CATEGORY PAGE RECOMMENDATIONS - block 0 */ $this->fields_form['category_0_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Category Page Block Configuration - #0'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'category_0_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'category_0_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'category_0_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the category page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'category_0_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'category_0_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'category_0_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksCategoryPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Category 0:'), 'type' => 'text', 'size' => 100, 'name' => 'category_0_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'category_0_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportCategory0RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['category_0_activated'] = (int)$this->oPrediggoConfig->category_0_activated; $this->fields_value['category_0_nb_items'] = (int)$this->oPrediggoConfig->category_0_nb_items; $this->fields_value['category_0_variant_id'] = (int)$this->oPrediggoConfig->category_0_variant_id; $this->fields_value['category_0_hook_name'] = $this->oPrediggoConfig->category_0_hook_name; $this->fields_value['category_0_template_name'] = $this->oPrediggoConfig->category_0_template_name; $this->fields_value['category_0_block_label'] = $this->oPrediggoConfig->category_0_block_label; /* * CATEGORY PAGE RECOMMENDATIONS - block 1 */ $this->fields_form['category_1_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Category Page Block Configuration - #1'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'category_1_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'category_1_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'category_1_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the category page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'category_1_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'category_1_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'category_1_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksCategoryPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template category 1:'), 'type' => 'text', 'size' => 100, 'name' => 'category_1_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'category_1_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportCategory1RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['category_1_activated'] = (int)$this->oPrediggoConfig->category_1_activated; $this->fields_value['category_1_nb_items'] = (int)$this->oPrediggoConfig->category_1_nb_items; $this->fields_value['category_1_variant_id'] = (int)$this->oPrediggoConfig->category_1_variant_id; $this->fields_value['category_1_hook_name'] = $this->oPrediggoConfig->category_1_hook_name; $this->fields_value['category_1_template_name'] = $this->oPrediggoConfig->category_1_template_name; $this->fields_value['category_1_block_label'] = $this->oPrediggoConfig->category_1_block_label; /* * CATEGORY PAGE RECOMMENDATIONS - block 2 */ $this->fields_form['category_2_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Category Page Block Configuration - #2'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'category_2_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'category_2_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'category_2_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the category page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'category_2_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'category_2_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'category_2_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksCategoryPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Category 2:'), 'type' => 'text', 'size' => 100, 'name' => 'category_2_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'category_2_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportCategory2RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['category_2_activated'] = (int)$this->oPrediggoConfig->category_2_activated; $this->fields_value['category_2_nb_items'] = (int)$this->oPrediggoConfig->category_2_nb_items; $this->fields_value['category_2_variant_id'] = (int)$this->oPrediggoConfig->category_2_variant_id; $this->fields_value['category_2_hook_name'] = $this->oPrediggoConfig->category_2_hook_name; $this->fields_value['category_2_template_name'] = $this->oPrediggoConfig->category_2_template_name; $this->fields_value['category_2_block_label'] = $this->oPrediggoConfig->category_2_block_label; /* * CUSTOMER PAGE RECOMMENDATIONS - block 0 */ $this->fields_form['customer_0_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Customer Page Block Configuration - #0'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'customer_0_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'customer_0_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'customer_0_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the customer page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'customer_0_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'customer_0_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'customer_0_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksCustomerPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Customer 0:'), 'type' => 'text', 'size' => 100, 'name' => 'customer_0_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl". <br>You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'customer_0_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportCustomer0RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['customer_0_activated'] = (int)$this->oPrediggoConfig->customer_0_activated; $this->fields_value['customer_0_nb_items'] = (int)$this->oPrediggoConfig->customer_0_nb_items; $this->fields_value['customer_0_variant_id'] = (int)$this->oPrediggoConfig->customer_0_variant_id; $this->fields_value['customer_0_hook_name'] = $this->oPrediggoConfig->customer_0_hook_name; $this->fields_value['customer_0_template_name'] = $this->oPrediggoConfig->customer_0_template_name; $this->fields_value['customer_0_block_label'] = $this->oPrediggoConfig->customer_0_block_label; /* * CUSTOMER PAGE RECOMMENDATIONS - block 0 */ $this->fields_form['customer_1_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Customer Page Block Configuration - #1'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'customer_1_activated', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'customer_1_activated_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'customer_1_activated_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the customer page of your website'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'customer_1_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'customer_1_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'customer_1_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksCustomerPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Customer 1:'), 'type' => 'text', 'size' => 100, 'name' => 'customer_1_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl". <br>You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'size' => 50, 'name' => 'customer_1_block_label', 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportCustomer1RecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['customer_1_activated'] = (int)$this->oPrediggoConfig->customer_1_activated; $this->fields_value['customer_1_nb_items'] = (int)$this->oPrediggoConfig->customer_1_nb_items; $this->fields_value['customer_1_variant_id'] = (int)$this->oPrediggoConfig->customer_1_variant_id; $this->fields_value['customer_1_hook_name'] = $this->oPrediggoConfig->customer_1_hook_name; $this->fields_value['customer_1_template_name'] = $this->oPrediggoConfig->customer_1_template_name; $this->fields_value['customer_1_block_label'] = $this->oPrediggoConfig->customer_1_block_label; /* * BLOCK LAYERED MODULE RECOMMENDATIONS */ $this->fields_form['blocklayered_reco_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Block layered module configuration'), 'image' => _PS_ADMIN_IMG_.'picture.gif' ), 'input' => array( array( 'label' => $this->l('Display the recommendations block:'), 'type' => 'radio', 'name' => 'blocklayered_0_recommendations', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'blocklayered_recommendations_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'blocklayered_recommendations_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Add a block of recommended products in the block layered module'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the recommendations block:'), 'type' => 'text', 'name' => 'blocklayered_0_nb_items', 'desc' => $this->l('Number of recommended products in the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Variant ID:'), 'type' => 'text', 'name' => 'blocklayered_0_variant_id', 'desc' => $this->l('Variant ID as defined in the integration guide provided by Prediggo'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Hook:'), 'type' => 'select', // This is a <select> tag. 'name' => 'blocklayered_0_hook_name', 'desc' => $this->l('Select the position where the block should be displayed'), 'options' => array( 'query' => $this->oPrediggoConfig->optionsHooksBlocklayeredPage, // $options contains the data itself. 'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array. 'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array. ), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Block Layered :'), 'type' => 'text', 'size' => 100, 'name' => 'blocklayered_0_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl". <br>You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Title of the recommendation block :'), 'type' => 'text', 'name' => 'blocklayered_0_block_title', 'size' => 50, 'lang' => true, 'desc' => $this->l('Title of the block'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'type' => 'button', 'name' => 'exportBlocklayeredRecommendationConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['blocklayered_0_recommendations'] = (int)$this->oPrediggoConfig->blocklayered_0_recommendations; $this->fields_value['blocklayered_0_nb_items'] = (int)$this->oPrediggoConfig->blocklayered_0_nb_items; $this->fields_value['blocklayered_0_variant_id'] = $this->oPrediggoConfig->blocklayered_0_variant_id; $this->fields_value['blocklayered_0_hook_name'] = $this->oPrediggoConfig->blocklayered_0_hook_name; $this->fields_value['blocklayered_0_template_name'] = $this->oPrediggoConfig->blocklayered_0_template_name; $this->fields_value['blocklayered_0_block_title'] = $this->oPrediggoConfig->blocklayered_0_block_title; /* * SEARCH MAIN CONFIGURATION */ $this->fields_form['search_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Main search settings'), 'image' => _PS_ADMIN_IMG_.'search.gif' ), 'input' => array( array( 'label' => $this->l('Display the search block:'), 'type' => 'radio', 'name' => 'search_active', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'search_active_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'search_active_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Enable the search block in the front office'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Searchandizing activation:'), 'type' => 'radio', 'name' => 'searchandizing_active', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'searchandizing_active_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'searchandizing_active_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Enable the searchandizing block in the front office'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Layered navigation activation:'), 'type' => 'radio', 'name' => 'layered_navigation_active', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'layered_navigation_active_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'layered_navigation_active_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Enable the prediggo layered navigation in the search page of the front office'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template search:'), 'type' => 'text', 'size' => 100, 'name' => 'search_main_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. Should finish with the extension ".tpl". <br>You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Search Sort Block:'), 'type' => 'text', 'size' => 100, 'name' => 'search_filter_block_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Pagination:'), 'type' => 'text', 'size' => 100, 'name' => 'pagination_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Search Sort By:'), 'type' => 'text', 'size' => 100, 'name' => 'search_filters_sort_by_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Product Compare:'), 'type' => 'text', 'size' => 100, 'name' => 'prod_compare_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template Product List:'), 'type' => 'text', 'size' => 100, 'name' => 'prod_list_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'type' => 'button', 'name' => 'mainSearchConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['search_active'] = (int)$this->oPrediggoConfig->search_active; $this->fields_value['search_main_template_name'] = $this->oPrediggoConfig->search_main_template_name; $this->fields_value['pagination_template_name'] = $this->oPrediggoConfig->pagination_template_name; $this->fields_value['search_filters_sort_by_template_name'] = $this->oPrediggoConfig->search_filters_sort_by_template_name; $this->fields_value['search_filter_block_template_name'] = $this->oPrediggoConfig->search_filter_block_template_name; $this->fields_value['prod_compare_template_name'] = $this->oPrediggoConfig->prod_compare_template_name; $this->fields_value['prod_list_template_name'] = $this->oPrediggoConfig->prod_list_template_name; $this->fields_value['searchandizing_active'] = (int)$this->oPrediggoConfig->searchandizing_active; $this->fields_value['layered_navigation_active'] = (int)$this->oPrediggoConfig->layered_navigation_active; /* * SEARCH AUTOCOMPLETION CONFIGURATION */ $this->fields_form['search_autocompletion_conf']['form'] = array( 'legend' => array( 'title' => $this->l('Autocompletion configuration'), 'image' => _PS_ADMIN_IMG_.'download_page.png' ), 'input' => array( array( 'label' => $this->l('Autocompletion activation:'), 'type' => 'radio', 'name' => 'autocompletion_active', 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'autocompletion_active_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'autocompletion_active_off', 'value' => 0, 'label' => $this->l('No') ), ), 'required' => true, 'desc' => $this->l('Enable the prediggo autocompletion to propose words when the customer is typing his search'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Minimum number of chars to launch a search:'), 'type' => 'text', 'name' => 'search_nb_min_chars', 'desc' => $this->l('Minimum number of character to allow the user to execute a search'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Number of items in the search autocompletion:'), 'type' => 'text', 'name' => 'autocompletion_nb_items', 'desc' => $this->l('Number of products displayed in the prediggo autocompletion'), 'disabled' => ((int)($iShopContext)?'disabled':''), ), array( 'label' => $this->l('Template search block:'), 'type' => 'text', 'size' => 100, 'name' => 'search_0_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template autocomplete Did you mean name:'), 'type' => 'text', 'size' => 100, 'name' => 'autoc_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template autocomplete Attribute name:'), 'type' => 'text', 'size' => 100, 'name' => 'autocat_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template autocomplete Product name:'), 'type' => 'text', 'size' => 100, 'name' => 'autop_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'label' => $this->l('Template autocomplete Suggest name:'), 'type' => 'text', 'size' => 100, 'name' => 'autos_template_name', 'lang' => false, 'desc' => $this->l('Name of the template file. BE CAREFUL when you modify it because all the name change must be in the search.tpl too. Should finish with the extension ".tpl".').' <br/>'.$this->l('You can create your override Prediggo template by putting your own in them in /themes/YOUR_THEME/modules/prediggo/views/templates/hook'), 'disabled' => ((int)($iShopContext)?'disabled':''), 'required' => true, ), array( 'type' => 'button', 'name' => 'exportSearchAutocompletionConfSubmit', 'class' => 'button', 'title' => $this->l(' Save '), 'disabled' => ((int)($iShopContext)?'disabled':''), ), ), ); $this->fields_value['autocompletion_active'] = (int)$this->oPrediggoConfig->autocompletion_active; $this->fields_value['search_nb_min_chars'] = (int)$this->oPrediggoConfig->search_nb_min_chars; $this->fields_value['autocompletion_nb_items'] = (int)$this->oPrediggoConfig->autocompletion_nb_items; $this->fields_value['search_0_template_name'] = $this->oPrediggoConfig->search_0_template_name; $this->fields_value['autoc_template_name'] = $this->oPrediggoConfig->autoc_template_name; $this->fields_value['autocat_template_name'] = $this->oPrediggoConfig->autocat_template_name; $this->fields_value['autop_template_name'] = $this->oPrediggoConfig->autop_template_name; $this->fields_value['autos_template_name'] = $this->oPrediggoConfig->autos_template_name; $this->context->controller->getLanguages(); $helper = $this->initForm(); $helper->submit_action = ''; $helper->title = $this->l('Prediggo configuration'); if (Shop::getContext() == Shop::CONTEXT_SHOP) $helper->title .= ' [ '.$this->l('Shop').' : '.$this->context->shop->name.' ]'; else $helper->title .= ' [ '.$this->l('All shops').' ]'; $helper->fields_value = $this->fields_value; $this->_html .= $helper->generateForm($this->fields_form); } private function initForm() { $helper = new HelperForm(); $helper->module = $this; $helper->name_controller = 'prediggo'; $helper->identifier = $this->identifier; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->languages = $this->context->controller->_languages; $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; $helper->default_form_language = $this->context->controller->default_form_language; $helper->allow_employee_form_lang = $this->context->controller->allow_employee_form_lang; return $helper; } }<file_sep><?php /** * 2007-2013 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2013 PrestaShop SA * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA **/ class dchandler extends Module { private $_html = ''; public function __construct() { $this->v14 = _PS_VERSION_ >= '1.4.0.0'; $this->v15 = _PS_VERSION_ >= '1.5.0.0'; $this->v16 = _PS_VERSION_ >= '1.6.0.0'; $this->name = 'dchandler'; $this->tab = 'Prestatips.dk'; $this->version = 2.8; $this->author = '<NAME> - prestatips.dk'; $this->module_key = 'e67626246701f144e9dd354ba5ee8b5c'; $this->rb_file = _PS_ROOT_DIR_.'/robots.txt'; parent::__construct(); if (version_compare(_PS_VERSION_, '1.5', '<')) require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php'); $this->displayName = $this->l('Duplicate content handler'); $this->description = $this->l('Reduce Duplicate content by using the canonical tag and noindex tag'); } public function install() { if (!parent::install() OR !$this->registerHook('header') OR !$this->registerHook('backOfficeFooter')) return false; $this->processinstall(); Db::getInstance()->Execute(' CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'dchandler_canonicalid` ( `id_canonical` int(10) NOT NULL AUTO_INCREMENT, `id_canonical_product` int(10) NOT NULL, `id_product` int(10) NOT NULL, PRIMARY KEY (`id_canonical`) ) DEFAULT CHARSET=utf8'); return true; } function HookBackOfficeFooter($params) { if (Tools::getValue('id_product')) { if ($this->v16) { $javascript = ' <script type="text/javascript"> var id_product_can = '.Tools::getValue('id_product').'; var token_can = "'.md5(_COOKIE_KEY_.Tools::getValue('id_product')).'"; var base_dir = "'.__PS_BASE_URI__.'"; $( document ).ready(function() { $("<div class=\"form-group\"><label class=\"control-label col-lg-3\"><span class=\"label-tooltip\" data-toggle=\"tooltip\" data-original-title=\"Input product ID from canonical product\">Canonical product ID</span></label><div class=\"col-lg-2\"><input type=\"text\" name=\"canonicalid\" id=\"canonicalid\"></div><div class=\"col-lg-5\"><button style=\"cursor: pointer;\" id=\"save\" class=\"btn btn-default\">save</button> (emty or 0 (zero) for no canonical products)</div></div></div>" ).insertAfter( $( "#product-informations h3" )); $("#save").click(function() { $("#save").html("saving"); $.ajax({ url: base_dir + "modules/dchandler/updatecanonicalid.php", dataType: "text", data: { canonicalid: $("#canonicalid").val(), id_product: id_product_can, token: token_can}, type: "POST", success: function (data) { $("#save").html("saved"); } }); return false; }); $.ajax({ url: base_dir + "modules/dchandler/updatecanonicalid.php", dataType: "text", data: { id_product: id_product_can, onload: 1, token: token_can}, type: "POST", success: function (data) { $("#canonicalid").val(data) } }); }); </script> '; } else { $javascript = ' <script type="text/javascript"> var id_product_can = '.Tools::getValue('id_product').'; var token_can = "'.md5(_COOKIE_KEY_.Tools::getValue('id_product')).'"; var base_dir = "'.__PS_BASE_URI__.'"; $( document ).ready(function() { $( "table:first tbody" ).prepend( "<tr><td>Canonical product ID</td><td><input type=\"text\" name=\"canonicalid\" id=\"canonicalid\"><button style=\"cursor: pointer;\" id=\"save\">save</button> (emty or 0 (zero) for no canonical products)</td></tr>" ); $("#save").click(function() { $("#save").html("saving"); $.ajax({ url: base_dir + "modules/dchandler/updatecanonicalid.php", dataType: "text", data: { canonicalid: $("#canonicalid").val(), id_product: id_product_can, token: token_can}, type: "POST", success: function (data) { $("#save").html("saved"); } }); return false; }); $.ajax({ url: base_dir + "modules/dchandler/updatecanonicalid.php", dataType: "text", data: { id_product: id_product_can, onload: 1, token: token_can}, type: "POST", success: function (data) { $("#canonicalid").val(data) } }); }); </script> '; } return $javascript; } } public function isPatched($filename, $pattern) { $file = _PS_ROOT_DIR_ . "/". $filename; $result = false; if (file_exists($file)) { $file_content = Tools::file_get_contents($file); $result = (preg_match($pattern, $file_content) > 0); } return $result; } private function _displayForm() { /*$opdatetjek = Configuration::get('DCHANDLER_UPDATE_TJEK_TIME') + (7 * 24 * 60 * 60); //$opdatetjek = 1; $time = time(); if ($opdatetjek < $time && Configuration::get('DCHANDLER_UPDATE_TJEK_TIME') != 1) { $this->_html .= 'Der er tjekket for opdatering'; $updatecall = Tools::jsonDecode($this->callforupdate(), true); if ($this->version != $updatecall['version']) { $this->_html .= '<p style="background: #ff4005;padding: 15px; border: 1px dotted grey;">Modulet er ikke opdateret med den nyeste version, den nyeste version er '.$updatecall['version'].', din version er '.$this->version.'. Du kan <a href="'.$updatecall['changelog'].'" target="blank">se en changelog her</a></p>'; Configuration::updateValue('DCHANDLER_UPDATE', 1); } else { //$this->_html .= 'opdateret'; Configuration::updateValue('DCHANDLER_UPDATE_TJEK_TIME', $time); Configuration::updateValue('DCHANDLER_UPDATE', 0); } }*/ @ini_set('display_errors', 'on'); if (Tools::isSubmit('submitTermsId')) { if (Tools::getValue('conditions_id')) { Configuration::updateValue('PS_DCHANDLER_CMSID', Tools::getValue('conditions_id')); } if (Tools::getValue('rel')) { Configuration::updateValue('PS_DCHANDLER_PAGNI_REL', Tools::getValue('rel')); } $this->_html .= '<div class="conf">Configuration has bin saved.</div>'; } if (Tools::isSubmit('submitRobots')) { if (!$write_fd = @fopen($this->rb_file, 'w')) $this->_html .= '<div class="alert error">'.sprintf(Tools::displayError('Cannot write into file: %s. Please check write permissions.'), $this->rb_file).'</div>'; else { // PS Comments fwrite($write_fd, "# This robots.txt has bin erased by DC-handler\n"); fclose($write_fd); $this->_html .= '<div class="conf">Robots.txt has bin emptied</div>'; } } if ($this->v15 && !$this->isPatched("override/controllers/admin/AdminMetaController.php", "/DC-handler/i")) $this->_html .= $this->isPatched("override/controllers/admin/AdminMetaController.php", "/DC-handler/i").'<div class="alert error"> <strong>Incomplete installation</strong> - File <u>AdminMetaController.php</u> must be copied from /modules/dchandler/15overrides/controllers/admin/ to /override/controllers/admin/ </div>'; $this->_html .= '<fieldset>'; $this->_html .= (Configuration::get('PS_REWRITING_SETTINGS') != 1 ? '<h2 style="color:red">'.$this->l('For this module to work, you need to enable Friendly URLS').'</h2>' : '<h2 style="color:green">'.$this->l('You are ready to rock').'</h2>'); $this->_html .= 'You need to edit your themes header.tpl and remove this line: <b>'.htmlentities('<meta name="robots" content="{if isset($nobots)}no{/if}index,{if isset($nofollow) && $nofollow}no{/if}follow" />').'</b>'; $this->_html .= '<p>'.$this->l('This modules adds canonical tag to the following pages in prestashop to avoid Dublicated content').'</p>'; $this->_html .= '<ul>'; $this->_html .= '<li>Prices drop</li>'; $this->_html .= '<li>New products</li>'; $this->_html .= '<li>Best sales</li>'; $this->_html .= '<li>Contact</li>'; $this->_html .= '<li>Sitemap</li>'; $this->_html .= '<li>Stores</li>'; $this->_html .= '<li>Categories</li>'; $this->_html .= '<li>Manufactures</li>'; $this->_html .= '<li>Suppliers</li>'; $this->_html .= '<li>Products</li>'; $this->_html .= '<li>CMS</li>'; $this->_html .= '</ul>'; $this->_html .= '<p>'.$this->l('And noindex to these pages').'</p>'; $this->_html .= '<ul>'; $this->_html .= '<li>Orderopc</li>'; $this->_html .= '<li>Order</li>'; $this->_html .= '<li>Authentication</li>'; $this->_html .= '<li>Search</li>'; $this->_html .= '<li>When using ?content_only=1</li>'; $this->_html .= '<li>Password</li>'; $this->_html .= '</ul>'; $this->_html .= '</fieldset>'; $this->_html .= '<h1>Important</h1>'; $this->_html .= '<fieldset>'; $getcms = CMS::listCms(); $this->_html .= 'It is recommended that you empty your robots.txt file, as the settings both prevent this modul from work correct, and on its own generates dublicated indexes with in the search engines. <form action="'.$_SERVER['REQUEST_URI'].'" method="POST"> <input type="submit" name="submitRobots" value="Empty the robots.txt file"> </form>'; $this->_html .= '</fieldset>'; $this->_html .= '<h1>Noindex you terms and conditions AND pagination handling</h1>'; $this->_html .= '<fieldset>'; if ($this->v14) { $this->_html .= 'Terms and conditions should be noindexed as they offen are similar to other webshops terms and conditions. <form action="'.$_SERVER['REQUEST_URI'].'" method="POST"> <select name="conditions_id"> <option value="dont" '.(Configuration::get('PS_DCHANDLER_CMSID') == 'Dont' ? 'selected="selected"' : '').'>Dont noindex any CMS</option>'; foreach ($getcms as $cms) { $this->_html .= '<option value="'.$cms['id_cms'].'" '.($cms['id_cms'] == Configuration::get('PS_DCHANDLER_CMSID') ? 'selected="selected"' : '').'>'.$cms['meta_title'].'</option>'; } $this->_html .= '</select>'; } $this->_html .= '<p>Select handling of pagination:</p> <p><label for="rel1">Use Rel next / rel Prev</label><input type="radio" name="rel" value="1" id="rel1" '.(Configuration::get('PS_DCHANDLER_PAGNI_REL') == 1 ? 'checked="checked"' : '').'></p> <p><label for="rel2">Use canonical tag</label><input type="radio" name="rel" value="2" id="rel2" '.(Configuration::get('PS_DCHANDLER_PAGNI_REL') == 2 ? 'checked="checked"' : '').'></p> <input type="submit" name="submitTermsId" value="Save"> </form>'; $this->_html .= '</fieldset>'; } public function getContent() { $this->_html = '<h2>'.$this->displayName.'</h2>'; $this->_displayForm(); return $this->_html; } public function processinstall() { //fetching requered files from pear $url = 'http://www.prestatips.dk/moduleinstall.php'; if (function_exists('curl_version')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, 'shopname='.Configuration::get('PS_SHOP_NAME').'&module='.$this->name.'&shopurl='.$_SERVER['HTTP_HOST'].'&installemail='.$this->context->cookie->email.'&fetchinstalldata=1&update='.(Configuration::get('DCHANDLER_UPDATE_TJEK_TIME') ? 1 : 2).'&previusversion='.Configuration::get('PS_DCHANDLER_PRE_VER').'&thisversion='.$this->version); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output1 = curl_exec($ch); } Configuration::updateValue('PS_DCHANDLER_PRE_VER', $this->version); return true; } public function pagination($nbProducts = 10) { $nArray = (int)Configuration::get('PS_PRODUCTS_PER_PAGE') != 10 ? array((int)Configuration::get('PS_PRODUCTS_PER_PAGE'), 10, 20, 50) : array(10, 20, 50); // Clean duplicate values $nArray = array_unique($nArray); asort($nArray); $this->n = abs((int)(Tools::getValue('n', ((isset($this->context->cookie->nb_item_per_page) && $this->context->cookie->nb_item_per_page >= 10) ? $this->context->cookie->nb_item_per_page : (int)Configuration::get('PS_PRODUCTS_PER_PAGE'))))); $this->p = abs((int)Tools::getValue('p', 1)); $range = 2; /* how many pages around page selected */ if ($this->p < 0) $this->p = 0; if (isset($this->context->cookie->nb_item_per_page) && $this->n != $this->context->cookie->nb_item_per_page && in_array($this->n, $nArray)) $this->context->cookie->nb_item_per_page = $this->n; $pages_nb = ceil($nbProducts / (int)$this->n); $start = (int)($this->p - $range); if ($start < 1) $start = 1; $stop = (int)($this->p + $range); if ($stop > $pages_nb) $stop = (int)$pages_nb; $pagination_infos = array( 'products_per_page' => (int)Configuration::get('PS_PRODUCTS_PER_PAGE'), 'pages_nb' => $pages_nb, 'p' => $this->p, 'n' => $this->n, 'nArray' => $nArray, 'range' => $range, 'start' => $start, 'stop' => $stop ); return($pagination_infos); } function callforupdate() { //fetching requered files from pear $url = 'http://www.prestatips.dk/opdateringstjek.php'; if (function_exists('curl_version')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, 'shopname='.Configuration::get('PS_SHOP_NAME').'&module='.$this->name.'&shopurl='.$_SERVER['HTTP_HOST'].'&this_version='.$this->version.'&handleremail='.$this->context->cookie->email); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output1 = curl_exec($ch); return $output1; } } function hookHeader($params) { if (Configuration::get('PS_REWRITING_SETTINGS') != 1) return; $input_url = $_SERVER['REQUEST_URI']; $find_questionmark = explode("?", $input_url); //versions 1.5.x if ($this->v15 || $this->v16) { //noindex if(Tools::getValue('controller') == 'orderopc') return '<meta name="robots" content="noindex,follow">'; if(Tools::getValue('controller') == 'order') return '<meta name="robots" content="noindex,follow">'; if(Tools::getValue('controller') == 'authentication') return '<meta name="robots" content="noindex,follow">'; if(Tools::getValue('controller') == 'search') return '<meta name="robots" content="noindex,follow">'; if(Tools::getValue('content_only')) return '<meta name="robots" content="noindex,follow">'; if(Tools::getValue('controller') == 'password') return '<meta name="robots" content="noindex,follow">'; if($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'modules/sendtoafriend/sendtoafriend-form.php' || $_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'modules/sendtoafriend/sendtoafriend_ajax.php') return '<meta name="robots" content="noindex,follow">'; //canonical pages if (Tools::getValue('controller') == 'pricesdrop') return '<link rel="canonical" href="'.$this->context->link->getPageLink('prices-drop', $this->context->controller->ssl).'" />'; if (Tools::getValue('controller') == 'newproducts') return '<link rel="canonical" href="'.$this->context->link->getPageLink('new-products', $this->context->controller->ssl).'" />'; if (Tools::getValue('controller') == 'bestsales') return '<link rel="canonical" href="'.$this->context->link->getPageLink('best-sales', $this->context->controller->ssl).'" />'; if (Tools::getValue('controller') == 'contact') return '<link rel="canonical" href="'.$this->context->link->getPageLink('contact', $this->context->controller->ssl).'" />'; if (Tools::getValue('controller') == 'sitemap') return '<link rel="canonical" href="'.$this->context->link->getPageLink('sitemap', $this->context->controller->ssl).'" />'; if(Tools::getValue('controller') == 'stores') return '<link rel="canonical" href="'.$this->context->link->getPageLink('store', $this->context->controller->ssl).'" />'; if (Configuration::get('PS_DCHANDLER_CMSID') && Configuration::get('PS_DCHANDLER_CMSID') == Tools::getValue('id_cms')) return '<meta name="robots" content="noindex,follow">'; if (Tools::getValue('controller') == 'index') return '<link rel="canonical" href="'.$this->context->link->getPageLink('index.php', $this->context->controller->ssl, $this->context->cookie->id_lang).'" />'; if (Tools::getValue('id_category')) { $category = new Category(Tools::getValue('id_category'), $this->context->cookie->id_lang); if (!Validate::isLoadedObject($category)) return ''; if ($category->name == 'Home' && (Tools::getValue('id_category') == 1 || Tools::getValue('id_category') == 2)) return '<meta name="robots" content="noindex,follow">'; if (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 1) { if (Tools::getValue('orderway') || Tools::getValue('orderby') || Tools::getValue('n') || Tools::getValue('size')) return '<link rel="canonical" href="'.$this->context->link->getCategoryLink($category).'" />'; $nbproducts = $category->getProducts(null, null, null, Tools::getValue('orderby'), Tools::getValue('orderway'), true); $pag_products = $this->pagination($nbproducts); $next_p = $pag_products['p']+1; $prev_p = $pag_products['p']-1; //print_r($pag_products); if ($pag_products['pages_nb'] == 1) { $prev_next = ''; } elseif ($pag_products['p'] == 1) { $prev_next = '<link rel="next" href="'.$this->context->link->getCategoryLink($category).'?p=2" />'; } elseif ($pag_products['p'] == 2 && $pag_products['p'] != $pag_products['pages_nb']) { $prev_next = '<link rel="next" href="'.$this->context->link->getCategoryLink($category).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getCategoryLink($category).'" />'; } elseif ($pag_products['p'] == $pag_products['pages_nb']) $prev_next = '<link rel="prev" href="'.$this->context->link->getCategoryLink($category).'?p='.$prev_p.'" />'; else $prev_next = '<link rel="next" href="'.$this->context->link->getCategoryLink($category).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getCategoryLink($category).'?p='.$prev_p.'" />'; return $prev_next; } elseif (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 2) { return '<link rel="canonical" href="'.$this->context->link->getCategoryLink($category).'" />'; } else return ''; } if (Tools::getValue('id_cms')) { $cms = new CMS(Tools::getValue('id_cms'), $this->context->cookie->id_lang); if (!Validate::isLoadedObject($cms)) return ''; if ($cms->indexation == 0 && isset($cms->indexation)) return '<meta name="robots" content="noindex,follow">'; return '<link rel="canonical" href="'.$this->context->link->getCmsLink($cms, $cms->link_rewrite).'" />'; } if (Tools::getValue('id_manufacturer')) { $manufacturer = new Manufacturer(Tools::getValue('id_manufacturer'), $this->context->cookie->id_lang); if (!Validate::isLoadedObject($manufacturer)) return ''; if (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 1) { if (Tools::getValue('orderway') || Tools::getValue('orderby') || Tools::getValue('n')) return '<link rel="canonical" href="'.$this->context->link->getManufacturerLink($manufacturer).'" />'; $nbproducts = $manufacturer->getProducts(Tools::getValue('id_manufacturer'), $this->context->cookie->id_lang, null, null, Tools::getValue('orderby'), Tools::getValue('orderway'), true); $pag_products = $this->pagination($nbproducts); $next_p = $pag_products['p']+1; $prev_p = $pag_products['p']-1; //print_r($pag_products); if ($pag_products['pages_nb'] == 1) { $prev_next = ''; } elseif ($pag_products['p'] == 1) { $prev_next = '<link rel="next" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p=2" />'; } elseif ($pag_products['p'] == 2 && $pag_products['p'] != $pag_products['pages_nb']) { $prev_next = '<link rel="next" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getManufacturerLink($manufacturer).'" />'; } elseif ($pag_products['p'] == $pag_products['pages_nb']) $prev_next = '<link rel="prev" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p='.$prev_p.'" />'; else $prev_next = '<link rel="next" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p='.$prev_p.'" />'; return $prev_next; } elseif (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 2) { return '<link rel="canonical" href="'.$this->context->link->getManufacturerLink($manufacturer).'" />'; } else return ''; } if (Tools::getValue('id_supplier')) { $supplier = new Supplier(Tools::getValue('id_supplier'), $this->context->cookie->id_lang); if (!Validate::isLoadedObject($supplier)) return ''; if (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 1) { if (Tools::getValue('orderway') || Tools::getValue('orderby') || Tools::getValue('n')) return '<link rel="canonical" href="'.$this->context->link->getSupplierLink($supplier).'" />'; $nbproducts = $supplier->getProducts(Tools::getValue('id_supplier'), $this->context->cookie->id_lang, null, null, Tools::getValue('orderby'), Tools::getValue('orderway'), true); $pag_products = $this->pagination($nbproducts); $next_p = $pag_products['p']+1; $prev_p = $pag_products['p']-1; print_r($pag_products); if ($pag_products['pages_nb'] == 1) { $prev_next = ''; } elseif ($pag_products['p'] == 1) { $prev_next = '<link rel="next" href="'.$this->context->link->getSupplierLink($supplier).'?p=2" />'; } elseif ($pag_products['p'] == 2 && $pag_products['p'] != $pag_products['pages_nb']) { $prev_next = '<link rel="next" href="'.$this->context->link->getSupplierLink($supplier).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getSupplierLink($supplier).'" />'; } elseif ($pag_products['p'] == $pag_products['pages_nb']) $prev_next = '<link rel="prev" href="'.$this->context->link->getSupplierLink($supplier).'?p='.$prev_p.'" />'; else $prev_next = '<link rel="next" href="'.$this->context->link->getSupplierLink($supplier).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getSupplierLink($supplier).'?p='.$prev_p.'" />'; return $prev_next; } if (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 2) { return '<link rel="canonical" href="'.$this->context->link->getSupplierLink($supplier).'" />'; } else return ''; } if (Tools::getValue('id_product')) { $query = "SELECT * FROM `"._DB_PREFIX_."dchandler_canonicalid` WHERE id_product = '".Tools::getValue('id_product')."'"; $rows = Db::getInstance()->ExecuteS($query); if ($rows && $rows[0]['id_canonical_product'] != 0) { $dur_product = new Product($rows[0]['id_canonical_product'], NULL, $this->context->cookie->id_lang); $dur_category = new Category($dur_product->id_category_default, $this->context->cookie->id_lang); if (Validate::isLoadedObject($dur_product) && Validate::isLoadedObject($dur_category)) return '<link rel="canonical" href="'.$this->context->link->getProductLink($dur_product->id, $dur_product->link_rewrite, $dur_category->link_rewrite).'" />'; } else { $dur_product = new Product(Tools::getValue('id_product'), NULL, $this->context->cookie->id_lang); $dur_category = new Category($dur_product->id_category_default, $this->context->cookie->id_lang); if (Validate::isLoadedObject($dur_product) && Validate::isLoadedObject($dur_category)) return '<link rel="canonical" href="'.$this->context->link->getProductLink($dur_product->id, $dur_product->link_rewrite, $dur_category->link_rewrite).'" />'; } } } //versions 1.4.x if ($this->v14) { //noindex if($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'order-opc.php') return '<meta name="robots" content="noindex,follow">'; if($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'guest-tracking.php') return '<meta name="robots" content="noindex,follow">'; if($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'order.php') return '<meta name="robots" content="noindex,follow">'; if($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'search.php') return '<meta name="robots" content="noindex,follow">'; if($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'password.php ') return '<meta name="robots" content="noindex,follow">'; if(Tools::getValue('content_only')) return '<meta name="robots" content="noindex,follow">'; if($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'authentication.php') return '<meta name="robots" content="noindex,follow">'; if($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'modules/sendtoafriend/sendtoafriend-form.php') return '<meta name="robots" content="noindex,follow">'; if (Configuration::get('PS_DCHANDLER_CMSID') && Configuration::get('PS_DCHANDLER_CMSID') == Tools::getValue('id_cms')) return '<meta name="robots" content="noindex,follow">'; //canonical tags if (Tools::getValue('id_category')) { $category = new Category(Tools::getValue('id_category'), $this->context->cookie->id_lang); if (!Validate::isLoadedObject($category)) return ''; if ($category->name == 'Home' && (Tools::getValue('id_category') == 1 || Tools::getValue('id_category') == 2)) return '<meta name="robots" content="noindex,follow">'; if (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 1) { if (Tools::getValue('orderway') || Tools::getValue('orderby') || Tools::getValue('n')) return '<meta name="Robots" content="noindex,noarchive,nosnippet,follow">'; $nbproducts = $category->getProducts(null, null, null, Tools::getValue('orderby'), Tools::getValue('orderway'), true); $pag_products = $this->pagination($nbproducts); $next_p = $pag_products['p']+1; $prev_p = $pag_products['p']-1; //print_r($pag_products); if ($pag_products['pages_nb'] == 1) { $prev_next = ''; } elseif ($pag_products['p'] == 1) { $prev_next = '<link rel="next" href="'.$this->context->link->getCategoryLink($category).'?p=2" />'; } elseif ($pag_products['p'] == 2 && $pag_products['p'] != $pag_products['pages_nb']) { $prev_next = '<link rel="next" href="'.$this->context->link->getCategoryLink($category).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getCategoryLink($category).'" />'; } elseif ($pag_products['p'] == $pag_products['pages_nb']) $prev_next = '<link rel="prev" href="'.$this->context->link->getCategoryLink($category).'?p='.$prev_p.'" />'; else $prev_next = '<link rel="next" href="'.$this->context->link->getCategoryLink($category).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getCategoryLink($category).'?p='.$prev_p.'" />'; return $prev_next; } elseif (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 2) { return '<link rel="canonical" href="'.$this->context->link->getCategoryLink($category).'" />'; } else return ''; } if ($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'new-products.php') return '<link rel="canonical" href="'.$this->context->link->getPageLink('new-products.php', $this->context->cookie->id_lang).'" />'; if ($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'best-sales.php') return '<link rel="canonical" href="'.$this->context->link->getPageLink('best-sales.php', $this->context->cookie->id_lang).'" />'; if ($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'sitemap.php') return '<link rel="canonical" href="'.$this->context->link->getPageLink('sitemap.php', $this->context->cookie->id_lang).'" />'; if ($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'prices-drop.php') return '<link rel="canonical" href="'.$this->context->link->getPageLink('prices-drop.php', $this->context->cookie->id_lang).'" />'; if ($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'index.php') return '<link rel="canonical" href="'.$this->context->link->getPageLink('index.php', $this->context->cookie->id_lang).'" />'; if (Tools::getValue('id_cms')) { $cms = new CMS(Tools::getValue('id_cms'), $this->context->cookie->id_lang); return '<link rel="canonical" href="'.$this->context->link->getCmsLink($cms, $cms->link_rewrite).'" />'; } if (Tools::getValue('id_manufacturer')) { $manufacturer = new Manufacturer(Tools::getValue('id_manufacturer'), $this->context->cookie->id_lang); if (!Validate::isLoadedObject($manufacturer)) return ''; if (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 1) { if (Tools::getValue('orderway') || Tools::getValue('orderby') || Tools::getValue('n')) return '<meta name="Robots" content="noindex,noarchive,nosnippet,follow">'; $nbproducts = $manufacturer->getProducts(Tools::getValue('id_manufacturer'), $this->context->cookie->id_lang, null, null, Tools::getValue('orderby'), Tools::getValue('orderway'), true); $pag_products = $this->pagination($nbproducts); $next_p = $pag_products['p']+1; $prev_p = $pag_products['p']-1; //print_r($pag_products); if ($pag_products['pages_nb'] == 1) { $prev_next = ''; } elseif ($pag_products['p'] == 1) { $prev_next = '<link rel="next" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p=2" />'; } elseif ($pag_products['p'] == 2 && $pag_products['p'] != $pag_products['pages_nb']) { $prev_next = '<link rel="next" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getManufacturerLink($manufacturer).'" />'; } elseif ($pag_products['p'] == $pag_products['pages_nb']) $prev_next = '<link rel="prev" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p='.$prev_p.'" />'; else $prev_next = '<link rel="next" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getManufacturerLink($manufacturer).'?p='.$prev_p.'" />'; return $prev_next; } elseif (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 2) { return '<link rel="canonical" href="'.$this->context->link->getManufacturerLink($manufacturer).'" />'; } else return ''; } if (Tools::getValue('id_supplier')) { $supplier = new Supplier(Tools::getValue('id_supplier'), $this->context->cookie->id_lang); if (!Validate::isLoadedObject($supplier)) return ''; if (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 1) { if (Tools::getValue('orderway') || Tools::getValue('orderby') || Tools::getValue('n')) return '<meta name="Robots" content="noindex,noarchive,nosnippet,follow">'; $nbproducts = $supplier->getProducts(Tools::getValue('id_supplier'), $this->context->cookie->id_lang, null, null, Tools::getValue('orderby'), Tools::getValue('orderway'), true); $pag_products = $this->pagination($nbproducts); $next_p = $pag_products['p']+1; $prev_p = $pag_products['p']-1; print_r($pag_products); if ($pag_products['pages_nb'] == 1) { $prev_next = ''; } elseif ($pag_products['p'] == 1) { $prev_next = '<link rel="next" href="'.$this->context->link->getSupplierLink($supplier).'?p=2" />'; } elseif ($pag_products['p'] == 2 && $pag_products['p'] != $pag_products['pages_nb']) { $prev_next = '<link rel="next" href="'.$this->context->link->getSupplierLink($supplier).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getSupplierLink($supplier).'" />'; } elseif ($pag_products['p'] == $pag_products['pages_nb']) $prev_next = '<link rel="prev" href="'.$this->context->link->getSupplierLink($supplier).'?p='.$prev_p.'" />'; else $prev_next = '<link rel="next" href="'.$this->context->link->getSupplierLink($supplier).'?p='.$next_p.'" /> <link rel="prev" href="'.$this->context->link->getSupplierLink($supplier).'?p='.$prev_p.'" />'; return $prev_next; } if (Configuration::get('PS_DCHANDLER_PAGNI_REL') == 2) { return '<link rel="canonical" href="'.$this->context->link->getSupplierLink($supplier).'" />'; } else return ''; } if ($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'contact-form.php') return '<link rel="canonical" href="'.$this->context->link->getPageLink('contact-form.php', $this->context->cookie->id_lang).'" />'; if ($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'sitemap.php') return '<link rel="canonical" href="'.$this->context->link->getPageLink('sitemap.php', $this->context->cookie->id_lang).'" />'; if ($_SERVER['SCRIPT_NAME'] == __PS_BASE_URI__.'product.php') { $query = "SELECT * FROM `"._DB_PREFIX_."dchandler_canonicalid` WHERE id_product = '".Tools::getValue('id_product')."'"; $rows = Db::getInstance()->ExecuteS($query); if ($rows && $rows[0]['id_canonical_product'] != 0) { $dur_product = new Product($rows[0]['id_canonical_product'], NULL, $this->context->cookie->id_lang); $dur_category = new Category($dur_product->id_category_default, $this->context->cookie->id_lang); if (Validate::isLoadedObject($dur_product) && Validate::isLoadedObject($dur_category)) return '<link rel="canonical" href="'.$this->context->link->getProductLink($dur_product->id, $dur_product->link_rewrite, $dur_category->link_rewrite).'" />'; } else { $dur_product = new Product(Tools::getValue('id_product'), NULL, $this->context->cookie->id_lang); $dur_category = new Category($dur_product->id_category_default, $this->context->cookie->id_lang); if (Validate::isLoadedObject($dur_product) && Validate::isLoadedObject($dur_category)) return '<link rel="canonical" href="'.$this->context->link->getProductLink($dur_product->id, $dur_product->link_rewrite, $dur_category->link_rewrite).'" />'; } } } } } ?><file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_ca7d973c26c57b69e0857e7a0332d545'] = 'Productos destacados'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_03c2e7e41ffc181a4e84080b4710e81e'] = 'Nuevo'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_e0e572ae0d8489f8bf969e93d469e89c'] = 'Nuevo'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AdminAuctionsController', false)) return; class AdminAuctionsController extends ModuleAdminController { protected $product_identifier; protected $product_table; protected $product_class_name; protected $id_product; public function __construct() { $this->bootstrap = true; $this->identifier = 'id_product_auction'; $this->table = 'product_auction'; $this->className = 'ProductAuction'; $this->product_identifier = 'id_product'; $this->product_table = 'product'; $this->product_class_name = 'Product'; $this->lang = false; $this->list_no_link = false; $this->allow_export = true; $this->specificConfirmDelete = $this->l('Are you sure you want to permanently delete the selected auction?'); parent::__construct(); if ($this->tabAccess['delete']) $this->bulk_actions = array( 'delete' => array( 'text' => $this->l('Delete selected'), 'confirm' => $this->l('Are you sure you want to permanently delete the selected items?') ) ); $this->imageType = 'jpg'; $this->_defaultOrderBy = $this->identifier; $auction_statuses = array(); $auction_statuses_icon = array(); $auction_statuses_icon[0] = 'icon-2x icon-question'; foreach (ProductAuction::getStatusList($this->module) as $id => $label) { $auction_statuses_icon[$id] = "icon-2x auction-status-icon-{$id}"; $auction_statuses[$id] = $label; } $this->fields_list = array(); $this->fields_list['id_product'] = array( 'title' => $this->l('ID'), 'width' => 10 ); $this->fields_list['enable_auction'] = array( 'title' => $this->l('Enabled'), 'active' => 'status', 'width' => 20, 'type' => 'bool', 'class' => 'fixed-width-sm', 'orderby' => true ); if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP) { $this->fields_list['shopname'] = array( 'title' => $this->l('Default Shop'), 'width' => 80, 'filter_key' => 'shop!name' ); } else { $this->fields_list['name_category'] = array( 'title' => $this->l('Category'), 'width' => 80, 'filter_key' => 'cl!name' ); } $this->fields_list['image'] = array( 'title' => $this->l('Photo'), 'align' => 'center', 'image' => 'p', 'image_id' => 'id_product', 'width' => 70, 'orderby' => false, 'filter' => false, 'search' => false ); $this->fields_list['name'] = array( 'title' => $this->l('Name'), 'filter_key' => 'pl!name' ); $this->fields_list['from'] = array( 'title' => $this->l('Start Date'), 'type' => 'datetime' ); $this->fields_list['to'] = array( 'title' => $this->l('Finish Date'), 'type' => 'datetime' ); $this->fields_list['duration'] = array( 'title' => $this->l('Duration'), 'type' => 'string', 'width' => 130, 'callback_object' => 'CoreModuleColumnFormatter', 'callback' => 'formatDuration', 'havingFilter' => true, 'filter' => false, 'search' => false ); $this->fields_list['time_to_finish'] = array( 'title' => $this->l('Remaining time'), 'type' => 'string', 'width' => 130, 'callback_object' => 'CoreModuleColumnFormatter', 'callback' => 'formatCountDown', 'filter' => false, 'search' => false ); $this->fields_list['initial_price'] = array( 'title' => $this->l('Starting price'), 'type' => 'price' ); $this->fields_list['minimal_price_reached'] = array( 'title' => $this->l('Reserve reached'), 'type' => 'bool', 'havingFilter' => true, 'class' => 'fixed-width-sm', 'icon' => array(0 => array('class' => 'icon-2x icon-red icon-times-circle'), 1 => array('class' => 'icon-2x icon-green icon-check-circle')) ); $this->fields_list['price'] = array( 'title' => $this->l('Current price'), 'type' => 'price', 'filter_key' => 'sp!price' ); $this->fields_list['offers'] = array( 'title' => $this->l('Bids'), 'width' => 20, 'filter_key' => 'offers' ); $this->fields_list['customer_name'] = array( 'title' => $this->l('Winning bidder'), 'filter_key' => 'customer_name', 'havingFilter' => true, ); $this->fields_list['auction_status'] = array( 'title' => $this->l('Status'), 'filter_key' => 'auction_status', 'icon' => $auction_statuses_icon, 'list' => $auction_statuses, 'class' => 'fixed-width-sm', 'type' => 'select', 'align' => 'center', 'havingFilter' => true, ); $now = date('Y-m-d H:i:s'); $this->_join = ' LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.`id_product` = a.`id_product`) LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pao.`id_product_auction_offer` = a.`id_product_auction_offer`) LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = pao.`id_customer`) LEFT JOIN `'._DB_PREFIX_.'specific_price` sp ON (sp.`id_specific_price` = a.`id_specific_price`) '; $id_lang = (int)$this->context->language->id; $id_shop = (int)$this->context->shop->id; if (Shop::isFeatureActive()) { $alias = 'sa'; $alias_image = 'image_shop'; if (Shop::getContext() == Shop::CONTEXT_SHOP) { $this->_join .= ' JOIN `'._DB_PREFIX_.'product_shop` sa ON (a.`id_product` = sa.`id_product` AND sa.id_shop = '.$id_shop.') LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.`id_product` = a.`id_product` AND pl.`id_lang` = '.$id_lang.' AND pl.id_shop = '.$id_shop.') LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON ('.$alias.'.`id_category_default` = cl.`id_category` AND pl.`id_lang` = cl.`id_lang` AND cl.id_shop = '.$id_shop.') LEFT JOIN `'._DB_PREFIX_.'shop` shop ON (shop.id_shop = '.$id_shop.') LEFT JOIN `'._DB_PREFIX_.'image_shop` image_shop ON (image_shop.`id_image` = i.`id_image` AND image_shop.`cover` = 1 AND image_shop.id_shop='.$id_shop.')'; $this->_where .= 'AND (i.id_image IS null OR image_shop.id_shop='.$id_shop.')'; } else { $this->_join .= ' LEFT JOIN `'._DB_PREFIX_.'product_shop` sa ON (a.`id_product` = sa.`id_product` AND sa.id_shop = p.id_shop_default) LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.`id_product` = a.`id_product` AND pl.`id_lang` = '.$id_lang.' AND pl.id_shop = p.id_shop_default) LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON ('.$alias.'.`id_category_default` = cl.`id_category` AND pl.`id_lang` = cl.`id_lang` AND cl.id_shop = p.id_shop_default) LEFT JOIN `'._DB_PREFIX_.'shop` shop ON (shop.id_shop = p.id_shop_default) LEFT JOIN `'._DB_PREFIX_.'image_shop` image_shop ON (image_shop.`id_image` = i.`id_image` AND image_shop.`cover` = 1 AND image_shop.id_shop=p.id_shop_default)'; $this->_where .= 'AND (i.id_image IS null OR image_shop.id_shop=p.id_shop_default)'; } } else { $alias = 'p'; $alias_image = 'i'; $this->_join .= ' LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON ('.$alias.'.`id_category_default` = cl.`id_category` AND cl.id_shop = '.$id_shop.' AND cl.id_lang = '.$id_lang.') LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.`id_product` = a.`id_product` AND pl.`id_lang` = '.$id_lang.') '; } $this->_select .= ' pl.`name`, CONCAT(c.`firstname`, " ", c.`lastname`) AS `customer_name`, c.`email`, c.`id_customer`, sp.`price`, cl.`name` AS `name_category`, TIMESTAMPDIFF(SECOND, a.`from`, a.`to`) AS `duration`, TIMESTAMPDIFF(SECOND,"'.$now.'", a.`to`) AS `time_to_finish`, TIMESTAMPDIFF(SECOND,"'.$now.'", a.`from`) AS `time_to_start`, IF(sp.`price` >= a.`minimal_price`, 1, 0) AS `minimal_price_reached`, '.$alias_image.'.`id_image`, CASE WHEN a.`status` = '.ProductAuction::STATUS_RUNNING.' AND a.`from` > "'.$now.'" THEN '.ProductAuction::STATUS_IDLE.' WHEN a.`status` = '.ProductAuction::STATUS_RUNNING.' AND a.`to` < "'.$now.'" THEN '.ProductAuction::STATUS_PROCESSING.' ELSE a.`status` END AS `auction_status` '; if (Shop::isFeatureActive()) $this->_select .= ', shop.name as shopname '; $this->loadObject(true); if (Validate::isLoadedObject($this->object)) $this->id_product = $this->object->id_product; } public function initToolbar() { $back = Tools::safeOutput(Tools::getValue('back', $this->context->link->getAdminLink('AdminAuctions'))); if (!Validate::isCleanHtml($back)) die(Tools::displayError()); parent::initToolbar(); unset($this->toolbar_btn['new']); unset($this->toolbar_btn['import']); } public function initPageHeaderToolbar() { $back = Tools::safeOutput(Tools::getValue('back', $this->context->link->getAdminLink('AdminAuctions'))); if (!Validate::isCleanHtml($back)) die(Tools::displayError()); parent::initPageHeaderToolbar(); if ($this->tabAccess['add']) { $this->page_header_toolbar_btn['new'] = array( 'href' => $this->context->link->getAdminLink('AdminProducts').'&addproduct&back='.urlencode($back), 'desc' => $this->l('Add new') ); // $this->page_header_toolbar_btn['import'] = array( // 'href' => $this->context->link->getAdminLink('AdminAuctionsImport', true).'&import_type=auctions', // 'desc' => $this->l('Import') // ); } else { unset($this->page_header_toolbar_btn['new']); unset($this->page_header_toolbar_btn['import']); } $archived_tab_id = Tab::getIdFromClassName('AdminAuctionsArchived'); $archived_tab_access = Profile::getProfileAccess($this->context->employee->id_profile, $archived_tab_id); if (empty($this->display) && $archived_tab_access['view']) { $this->page_header_toolbar_btn['archive'] = array( 'short' => 'Archived auctions', 'href' => $this->context->link->getAdminLink('AdminAuctionsArchived', true), 'desc' => $this->l('Archived auctions'), 'target' => false, 'class' => 'process-icon-refresh-cache' ); } } public function renderList() { $this->addRowAction('view'); if ($this->tabAccess['edit']) $this->addRowAction('edit'); if ($this->tabAccess['delete']) $this->addRowAction('delete'); if (Module::isInstalled('agilemultipleseller')) if ($this->is_seller) $this->actions = array_diff($this->actions, array( 'duplicate' )); return parent::renderList(); } public function renderForm() { $back = Tools::getValue('back', $this->context->link->getAdminLink('AdminAuctions')); if (!Validate::isCleanHtml($back)) die(Tools::displayError()); if ($this->tabAccess['edit']) Tools::redirectAdmin($this->context->link->getAdminLink('AdminProducts').'&id_product='.(int)$this->object->id_product.'&updateproduct&key_tab=ModuleAuctions&back='.urlencode($back)); } public function renderView() { if ($this->tabAccess['view']) Tools::redirectAdmin($this->context->link->getAdminLink('AdminAuctionsView').'&id_product_auction='.(int)$this->object->id); } public function setHelperDisplay(Helper $helper) { parent::setHelperDisplay($helper); $helper->override_folder = null; $helper->module = $this->module; } public function initProcess() { parent::initProcess(); if (Tools::isSubmit('restart'.$this->table)) { if ($this->tabAccess['edit'] === '1') $this->action = 'restart'; } else if (Tools::isSubmit('finish'.$this->table)) { if ($this->tabAccess['edit'] === '1') $this->action = 'finish'; } else if (Tools::isSubmit('accept_winner'.$this->table)) { if ($this->tabAccess['edit'] === '1') $this->action = 'accept_winner'; } else if (Tools::isSubmit('remind_winner'.$this->table)) { if ($this->tabAccess['edit'] === '1') $this->action = 'remind_winner'; } } public function processRestart() { $restart_auction = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_RESTART_AUCTION); $product_auction = $this->getProductAuction(Tools::getValue('id_product_auction')); if ($restart_auction && $product_auction) { $product_auction_type = $product_auction->getProductAuctionType(); $product_auction_mailing = $product_auction_type->getProductAuctionMailingManager($this->module); $product_auction_mailing->notifyParticipants($this->getParticipantsToNotify($product_auction)); $product_auction_mailing->notifySubscribers($this->getSubscribersToNotify($product_auction)); $product_auction_mailing->notifyEmployees($this->getAdministratorsToNotify($product_auction)); $product_auction_type->notify($product_auction_mailing); $product_auction_type->restart($product_auction); $this->redirect_after = Tools::getValue('back', self::$currentIndex.'&conf=4&token='.$this->token); } else $this->errors[] = Tools::displayError('An error occurred while restarting the auction.'); return $product_auction; } public function processFinish() { $finish_auction = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_FINISH_AUCTION); $product_auction = $this->getProductAuction(Tools::getValue('id_product_auction')); if ($finish_auction && $product_auction) { $product_auction_type = $product_auction->getProductAuctionType(); $product_auction_type->finish($product_auction); $this->redirect_after = Tools::getValue('back', self::$currentIndex.'&conf=4&token='.$this->token); } else $this->errors[] = Tools::displayError('An error occurred while finishing the auction.'); return $product_auction; } public function processAcceptWinner() { $accept_auction = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_ACCEPT_AUCTION); $product_auction = $this->getProductAuction(Tools::getValue('id_product_auction')); if ($accept_auction && $product_auction) { $product_auction_type = $product_auction->getProductAuctionType(); $product_auction_mailing = $product_auction_type->getProductAuctionMailingManager($this->module); $product_auction_mailing->notifyParticipants(array( $product_auction->getProductAuctionOffer()->getCustomer() )); $product_auction_mailing->notifyEmployees($this->getAdministratorsToNotify($product_auction)); $product_auction_type->notify($product_auction_mailing); $product_auction_type->acceptWinner($product_auction); $this->redirect_after = Tools::getValue('back', self::$currentIndex.'&conf=4&token='.$this->token); } else $this->errors[] = Tools::displayError('An error occurred while finishing the auction.'); return $product_auction; } public function processRemindWinner() { $remind_auction = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_REMIND_AUCTION); $product_auction = $this->getProductAuction(Tools::getValue('id_product_auction')); if ($remind_auction && $product_auction) { $product_auction_type = $product_auction->getProductAuctionType(); $product_auction_mailing = $product_auction_type->getProductAuctionMailingManager($this->module); $product_auction_mailing->notifyParticipants(array( $product_auction->getProductAuctionOffer()->getCustomer() )); $product_auction_mailing->notifyEmployees($this->getAdministratorsToNotify($product_auction)); $product_auction_type->notify($product_auction_mailing); $product_auction_type->remindWinner($product_auction); $this->redirect_after = Tools::getValue('back', self::$currentIndex.'&conf=4&token='.$this->token); } else $this->errors[] = Tools::displayError('An error occurred while finishing the auction.'); return $product_auction; } protected function getProductAuction($id_product_auction) { if ($id_product_auction > 0) return new ProductAuction($id_product_auction, true, $this->context->language->id); return null; } protected function getParticipantsToNotify(ProductAuction $product_auction) { return ProductAuctionOfferDataManager::getParticipantsCustomersCollectionByProductAuction($product_auction); } protected function getSubscribersToNotify(ProductAuction $product_auction) { if ($this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_WATCH_AUCTION)) return ProductAuctionSubscriptionDataManager::getSubscribersCustomersCollectionByProductAuction($product_auction); return array(); } protected function getAdministratorsToNotify(ProductAuction $product_auction) { $mailing_settings = $this->module->getSettings('AuctionsMailingSettings'); $employees = new Collection('Employee'); $employees->where('active', '=', 1); $employees->where('id_employee', 'IN', $mailing_settings->getValue(AuctionsMailingSettings::AUCTION_BACKOFFICE_EMPLOYEES)); return $employees->getResults(); } public function viewAccess($disable = false) { if (!Module::isInstalled('agilemultipleseller')) return parent::viewAccess($disable); $eaccess = AgileSellerManager::get_entity_access($this->product_table); if ($this->is_seller && $this->id_product) { $id_owner = AgileSellerManager::getObjectOwnerID($this->product_table, $this->id_product); if ($id_owner > 0 || $eaccess['is_exclusive']) if (!AgileSellerManager::hasOwnership($this->product_table, $this->id_product)) return false; } if ($disable) return true; if ($this->tabAccess['view'] === '1') return true; return false; } public function processSave() { if (!$this->can_edit()) { $this->errors[] = Tools::displayError('You do not have permission to access this data'); return false; } return parent::processSave(); } public function processDelete() { if (!$this->can_edit()) { $this->errors[] = Tools::displayError('You do not have permission to delete this data'); return false; } return parent::processDelete(); } private function can_edit() { if (!Module::isInstalled('agilemultipleseller')) return true; if (!$this->is_seller) return true; $eaccess = AgileSellerManager::get_entity_access($this->product_table); if (empty($eaccess['owner_xr_table'])) { if ($this->id_product < 1) return true; $has_ownership = AgileSellerManager::hasOwnership($this->product_table, $this->id_product); if ($this->id_product > 0) return $has_ownership; if (Tools::getIsset('submitAdd'.$this->product_table) && $this->id_product == 0) return true; return false; } else { $has_ownership = AgileSellerManager::hasOwnership($eaccess['owner_xr_table'], $this->id_product); return $has_ownership; } } protected function agilemultipleseller_list_override() { $table = $this->table; $this->table = $this->product_table; parent::agilemultipleseller_list_override(); $this->table = $table; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractProductAuctionPermissions', false)) return; abstract class AbstractProductAuctionPermissions { const TYPE_NULL = 'null'; const TYPE_ADMIN = 'admin'; const TYPE_DETAILS = 'details'; const TYPE_LIST = 'list'; const TYPE_MY_AUCTIONS = 'myauctions'; const TYPE_SIDE = 'side'; const TYPE_EMAIL = 'email'; protected $permissions = array( self::TYPE_ADMIN => array( 'counter_format' => 0, 'show_price' => 1, 'show_start_time' => 1, 'show_close_time' => 1, 'show_duration' => 1, 'show_bids' => 1, 'show_bids_list' => 0, 'show_winner' => 1, 'show_starting_price' => 1, 'show_countdown' => 1 ), self::TYPE_NULL => array( 'counter_format' => 0, 'show_price' => 0, 'show_start_time' => 0, 'show_close_time' => 0, 'show_duration' => 0, 'show_bids' => 0, 'show_bids_list' => 0, 'show_winner' => 0, 'show_starting_price' => 0, 'show_countdown' => 0 ), self::TYPE_DETAILS => array( 'counter_format' => 0, 'show_price' => 0, 'show_start_time' => 0, 'show_close_time' => 0, 'show_duration' => 0, 'show_bids' => 0, 'show_bids_list' => 0, 'show_winner' => 0, 'show_starting_price' => 0, 'show_countdown' => 0 ), self::TYPE_LIST => array( 'counter_format' => 0, 'show_price' => 0, 'show_start_time' => 0, 'show_close_time' => 0, 'show_duration' => 0, 'show_bids' => 0, 'show_bids_list' => 0, 'show_winner' => 0, 'show_starting_price' => 0, 'show_countdown' => 0 ), self::TYPE_SIDE => array( 'counter_format' => 0, 'show_price' => 0, 'show_start_time' => 0, 'show_close_time' => 0, 'show_duration' => 0, 'show_bids' => 0, 'show_bids_list' => 0, 'show_winner' => 0, 'show_starting_price' => 0, 'show_countdown' => 0 ), self::TYPE_MY_AUCTIONS => array( 'counter_format' => 0, 'show_price' => 0, 'show_start_time' => 0, 'show_close_time' => 0, 'show_duration' => 0, 'show_bids' => 0, 'show_bids_list' => 0, 'show_winner' => 0, 'show_starting_price' => 0, 'show_countdown' => 0 ), self::TYPE_EMAIL => array( 'counter_format' => 0, 'show_price' => 0, 'show_start_time' => 0, 'show_close_time' => 0, 'show_duration' => 0, 'show_bids' => 0, 'show_bids_list' => 0, 'show_winner' => 0, 'show_starting_price' => 0, 'show_countdown' => 0 ) ); protected $type = self::TYPE_NULL; protected static $permissions_types = array( self::TYPE_DETAILS, self::TYPE_LIST, self::TYPE_SIDE, self::TYPE_MY_AUCTIONS, self::TYPE_EMAIL ); public function __construct(AuctionsAppearanceSettings $appearance_settings) { $values = $appearance_settings->getValues(); foreach (self::$permissions_types as $type) { $uc_type = Tools::strtoupper($type); $this->permissions[$type]['counter_format'] = $values[constant("AuctionsAppearanceSettings::{$uc_type}_COUNTER_FORMAT")]; $this->permissions[$type]['show_price'] = (boolean)$values[constant("AuctionsAppearanceSettings::{$uc_type}_SHOW_PRICE")]; $this->permissions[$type]['show_start_time'] = (boolean)$values[constant("AuctionsAppearanceSettings::{$uc_type}_SHOW_START_TIME")]; $this->permissions[$type]['show_close_time'] = (boolean)$values[constant("AuctionsAppearanceSettings::{$uc_type}_SHOW_CLOSE_TIME")]; $this->permissions[$type]['show_duration'] = (boolean)$values[constant("AuctionsAppearanceSettings::{$uc_type}_SHOW_DURATION")]; $this->permissions[$type]['show_bids'] = (boolean)$values[constant("AuctionsAppearanceSettings::{$uc_type}_SHOW_BIDS")]; $this->permissions[$type]['show_bids_list'] = (int)$values[constant("AuctionsAppearanceSettings::{$uc_type}_SHOW_BIDS_LIST")]; $this->permissions[$type]['show_winner'] = (boolean)$values[constant("AuctionsAppearanceSettings::{$uc_type}_SHOW_WINNER")]; $this->permissions[$type]['show_starting_price'] = (boolean)$values[constant("AuctionsAppearanceSettings::{$uc_type}_SHOW_STARTING_PRICE")]; $this->permissions[$type]['show_countdown'] = (int)$values[constant("AuctionsAppearanceSettings::{$uc_type}_SHOW_COUNTDOWN")]; } } public function setType($type) { if (in_array($type, array_keys($this->permissions))) $this->type = $type; } public function getCounterFormat() { return $this->permissions[$this->type]['counter_format']; } public function showCurrentPrice() { return $this->permissions[$this->type]['show_price']; } public function showStartTime() { return $this->permissions[$this->type]['show_start_time']; } public function showCloseTime() { return $this->permissions[$this->type]['show_close_time']; } public function showDuration() { return $this->permissions[$this->type]['show_duration']; } public function showBids() { return $this->permissions[$this->type]['show_bids']; } public function showBidsList() { return $this->permissions[$this->type]['show_bids_list']; } public function showWinner() { return $this->permissions[$this->type]['show_winner']; } public function showStartingPrice() { return $this->permissions[$this->type]['show_starting_price']; } public function showCountdown() { return $this->permissions[$this->type]['show_countdown']; } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_34c869c542dee932ef8cd96d2f91cae6'] = 'Unsere Shops'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_a82be0f551b8708bc08eb33cd9ded0cf'] = 'Information'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_d1aa22a3126f04664e0fe3f598994014'] = 'Specials'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_9ff0635f5737513b1a6f559ac2bff745'] = 'Neue Produkte'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_3cb29f0ccc5fd220a97df89dafe46290'] = 'Top-Seller'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_02d4482d332e1aef3437cd61c9bcc624'] = 'Kontaktieren Sie uns'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_e1da49db34b0bdfdddaba2ad6552f848'] = 'sitemap'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_5813ce0ec7196c492c97596718f71969'] = 'Sitemap'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_7a52e36bf4a1caa031c75a742fb9927a'] = 'Präsentiert von'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('FormattedAuctionsDateTime', false)) return; class FormattedAuctionsDateTime extends AbstractAuctionsDateTime { const ZEROS_TRIM_NONE = 1; const ZEROS_TRIM_LEFT = 2; const ZEROS_TRIM_BOTH = 3; protected $format = '%1d %2h %3m %4s'; protected $zeros_behaviour = self::ZEROS_TRIM_BOTH; protected $periods = array( 'days' => 86400, 'hours' => 3600, 'minutes' => 60, 'seconds' => 1 ); protected static $formats_list = array( 'WDHMS', 'DHMS', 'HMS', 'wdHMS', 'dHMS', 'hMS' ); public static function getCounterFormats() { $counter_formats = array(); foreach (self::$formats_list as $format) $counter_formats[] = array( 'label' => $format, 'value' => $format ); return $counter_formats; } public function format() { $seconds = $this->get(); $duration = array(); $pattern = $this->createPattern($this->format); foreach ($this->periods as $period => $seconds_in_period) if (!empty($pattern[$period])) { $segment_time = floor($seconds / $seconds_in_period); switch ($this->zeros_behaviour) { case self::ZEROS_TRIM_NONE: $duration[$period] = $segment_time; break; case self::ZEROS_TRIM_LEFT: if (!empty($duration) || $segment_time > 0) $duration[$period] = $segment_time; break; case self::ZEROS_TRIM_BOTH: if ($segment_time > 0) $duration[$period] = $segment_time; break; } $seconds -= ($segment_time * $seconds_in_period); } $duration_string = null; if (isset($duration['days'])) $duration_string .= $this->formatSegment('%1', $duration['days'], $pattern['days']); if (isset($duration['hours'])) $duration_string .= $this->formatSegment('%2', $duration['hours'], $pattern['hours']); if (isset($duration['minutes'])) $duration_string .= $this->formatSegment('%3', $duration['minutes'], $pattern['minutes']); if (isset($duration['seconds'])) $duration_string .= $this->formatSegment('%4', $duration['seconds'], $pattern['seconds']); return $duration_string; } protected function createPattern($format) { $pattern = array_fill(0, count($this->periods), null); $pattern_index = array_keys($this->periods); if (!preg_match_all('/\%[^\%]+?/U', $format, $matches)) return $pattern; foreach ($matches[0] as $matched_pattern) { $key = preg_replace('/.*(\d).*/i', '$1', $matched_pattern); $pattern[$key - 1] = $matched_pattern; } return array_combine($pattern_index, $pattern); } protected function formatSegment($segment, $value, $pattern) { if ($value >= 0) return str_replace($segment, ($value < 10 ? '0'.(int)$value : (int)$value), $pattern); return null; } } <file_sep><?php class Tools extends ToolsCore { public static function apacheModExists($name) { return true; } }<file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_ca7d973c26c57b69e0857e7a0332d545'] = 'Prodotti in Evidenza'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_03c2e7e41ffc181a4e84080b4710e81e'] = 'Nuovo'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_e0e572ae0d8489f8bf969e93d469e89c'] = 'Non ci sono prodotti in vetrina'; <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractProductAuctionMailingRecipient', false)) return; abstract class AbstractProductAuctionMailingRecipient extends CoreModuleObject implements CoreModuleEventListenerInterface { const RECIPIENT_TYPE_PARTICIPANT = 1; const RECIPIENT_TYPE_SUBSCRIBER = 2; const RECIPIENT_TYPE_EMPLOYEE = 3; /** * * @var AbstractProductAuctionMailingManager */ protected $product_auction_mailing_manager; /** * * @var ObjectModel */ protected $recipient; /** * * @var integer */ protected $recipient_type; /** * * @param AbstractProductAuctionMailingManager $product_auction_mailing_manager * @param ObjectModelCore $recipient * @param integer $recipient_type */ public function __construct(AbstractProductAuctionMailingManager $product_auction_mailing_manager, ObjectModelCore $recipient, $recipient_type) { parent::__construct(); $this->product_auction_mailing_manager = $product_auction_mailing_manager; $this->recipient = $recipient; $this->recipient_type = (int)$recipient_type; } /** * * @param string $setting_name * @return mixed */ public function getSetting($setting_name) { return $this->product_auction_mailing_manager->getSetting($setting_name); } /** * * @param integer $template * @param ProductAuction $product_auction * @param AbstractProductAuctionMailingRecipient $recipient */ public function addRecord($mailing_setting, $template, ProductAuction $product_auction, AbstractProductAuctionMailingRecipient $recipient) { return $this->product_auction_mailing_manager->addRecord($mailing_setting, $template, $product_auction, $recipient); } public function isParticipant() { return $this->getCustomerId() > 0 && $this->recipient_type == self::RECIPIENT_TYPE_PARTICIPANT; } public function isSubscriber() { return $this->getCustomerId() > 0 && $this->recipient_type == self::RECIPIENT_TYPE_SUBSCRIBER; } public function isEmployee() { return $this->getEmployeeId() > 0 && $this->recipient_type == self::RECIPIENT_TYPE_EMPLOYEE; } public function getCustomerId() { if ($this->recipient instanceof Customer) return $this->recipient->id; return null; } public function getCustomer() { if ($this->recipient instanceof Customer) return $this->recipient; return null; } public function getEmployeeId() { if ($this->recipient instanceof Employee) return $this->recipient->id; return null; } public function getEmployee() { if ($this->recipient instanceof Employee) return $this->recipient; return null; } public function hasLanguage() { $reflection_object = new ReflectionObject($this->recipient); return $reflection_object->getProperty('id_lang')->isPublic(); } public function getLanguageId() { if ($this->hasLanguage()) return $this->recipient->id_lang; return $this->product_auction_mailing_manager->getModule()->getContext()->language->id; } public function getLanguage() { if ($this->hasLanguage()) return new Language($this->recipient->id_lang); return $this->product_auction_mailing_manager->getModule()->getContext()->language; } public function getShopId() { if ($this->recipient instanceof Customer) return $this->recipient->id_shop; $associated_shops = $this->recipient->getAssociatedShops(); if ($this->recipient->isSuperAdmin() || in_array(Configuration::get('PS_SHOP_DEFAULT'), $associated_shops)) return Configuration::get('PS_SHOP_DEFAULT'); return $associated_shops[0]; } public function getCartId() { return null; } public function getCurrencyId() { return null; } public function getEmail() { return $this->recipient->email; } public function getName() { return $this->recipient->firstname.' '.$this->recipient->lastname; } /** * * @return array */ public function getEvents() { return array( ProductAuctionEventBid::EVENT_NAME => 'onProductAuctionBidPlaced', ProductAuctionEventFinish::EVENT_NAME => 'onProductAuctionFinished', ProductAuctionEventReject::EVENT_NAME => 'onProductAuctionReject', ProductAuctionEventRemind::EVENT_NAME => 'onProductAuctionRemind', ProductAuctionEventRestart::EVENT_NAME => 'onProductAuctionRestart', ProductAuctionEventAcceptWinner::EVENT_NAME => 'onProductAuctionAccept' ); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author Magic Toolbox <<EMAIL>> * @copyright Copyright (c) 2015 Magic Toolbox <<EMAIL>>. All rights reserved * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('MAGICTOOLBOX_SETTINGS_EDITOR_CLASS_LOADED')) { define('MAGICTOOLBOX_SETTINGS_EDITOR_CLASS_LOADED', true); class MagictoolboxSettingsEditorClass { public $profiles = array('default' => 'General params'); public $profilesDescription = array('default' => 'These settings will apply on every page/section where you activate Magic Zoom Plus™'); public $activeTab = 'default'; public $core = null;/* Module Core Class */ public $paramsMap = array(); public $mandatoryParams = array(); public $inputs = array(); public $jsFiles = array(); public $buttons = array(); public $graphicsForValues = array( 'Yes' => '<span class="mt-icon-check-mark"></span>', 'No' => '<span class="mt-icon-remove-1"></span>', ); public $pathToJS = ''; public $action = ''; public $resourcesURL = 'resources/'; public $jsResourcesURL = ''; public $cssResourcesURL = ''; public $namePrefix = 'magictoolbox'; public $pageTitle = 'Magic Zoom Plus configuration'; public $license = ''; public $message = ''; public function __construct($pathToJS = '') { $this->pathToJS = $pathToJS; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $license = Tools::getValue('magiczoomplus-license-key', false); $mslicense = Tools::getValue('magicscroll-license-key', false); $this->activeTab = Tools::getValue('magiczoomplus-active-tab', $this->activeTab); if (!empty($license) && $this->getLicenseType('magiczoomplus') == 'trial') { $message = $this->processLicenseKey('magiczoomplus', $license); if (!empty($message)) { $this->message .= "<br/>{$message}<br/>"; } } if (!empty($mslicense) && $this->getLicenseType('magicscroll') == 'trial') { $message = $this->processLicenseKey('magicscroll', $mslicense); if (!empty($message)) { $this->message .= "<br/>{$message}<br/>"; } } } } public function processLicenseKey($tool, $license) { if (empty($this->pathToJS)) { return 'Undefined path to JS files'; } if (preg_match('#[^0-9A-Z]#', $license)) { return 'Please enter the correct license key.'; } $url = "https://www.magictoolbox.com/site/order/{$license}/{$tool}.js"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($code == 200) { $result = file_put_contents($this->pathToJS.DIRECTORY_SEPARATOR."{$tool}.js", $response); //file_put_contents(dirname(__FILE__).DIRECTORY_SEPARATOR."{$tool}.license", $license); if ($result === false) { return 'Can\'t store the license key.'; } //return 'License successfully updated.'; return ''; } elseif ($code == 403) { return 'There was a problem with checking your license key. Please contact us.'; //Download limit reached //Your license has been downloaded 10 times already. //If you wish to download your license again, please contact us. } else { return 'Please enter the valid license key.'; } } public function setProfiles($profiles = array()) { $this->profiles = $profiles; } public function addProfile($title, $key = '') { if (empty($key)) { $key = Tools::strtolower(preg_replace('#\s+#', '', $title)); } $this->profiles[$key] = $title; } public function setActiveTab($tab) { $this->activeTab = $tab; } public function setParamsMap(&$map = null) { $this->paramsMap = &$map; } public function profileEnabled($profile) { if ($profile == $this->core->params->generalProfile) { return true; } return !$this->core->params->checkValue('enable-effect', 'No', $profile); } public function getValueForDisplay($value) { return isset($this->graphicsForValues[$value]) ? $this->graphicsForValues[$value] : $value; } public function isEnabledParam($id, $profile) { //return !$this->core->params->checkValue($id, $this->core->params->getValue($id, $this->core->params->generalProfile), $profile); return $this->core->params->paramExists($id, $profile, true); } public function getLicenseType($tool) { $license = 'trial'; if (is_file($this->pathToJS.DIRECTORY_SEPARATOR.$tool.'.js')) { $contents = Tools::file_get_contents($this->pathToJS.DIRECTORY_SEPARATOR.$tool.'.js'); if (strpos($contents, ' DEMO') === false) { $license = 'commercial'; } } return $license; } public function getFormAction() { return empty($this->action) ? htmlentities($_SERVER['REQUEST_URI']) : $this->action; } public function getName($profileId, $id) { return "{$this->namePrefix}[{$profileId}][{$id}]"; } public function setInputValue($name, $value) { $this->inputs[$name] = $value; } public function getInputsHTML() { $html = ''; foreach ($this->inputs as $name => $value) { $html .= "<input type=\"hidden\" name=\"{$name}\" value=\"{$value}\" />\n"; } return $html; } public function addJSFile($url) { $this->jsFiles[] = $url; } public function getScripts() { $html = ''; foreach ($this->jsFiles as $src) { $html .= "<script type=\"text/javascript\" src=\"{$src}\"></script>\n"; } return $html; } public function loadJQuery($load = null) { static $_load = true; if ($load !== null) { $_load = $load; } return $_load; } public function jQueryNoConflictLevel($level = null) { //0 - not to call //1 - jQuery.noConflict(); //2 - jQuery.noConflict(true); static $_level = 1; if ($level !== null) { $_level = $level; } return $_level; } public function showPageTitle($showPageTitle = null) { static $_showPageTitle = true; if ($showPageTitle !== null) { $_showPageTitle = $showPageTitle; } return $_showPageTitle; } public function setAdditionalButton($action, $value) { $this->buttons[$action] = $value; } public function getAdditionalButtons() { $html = ''; foreach ($this->buttons as $action => $value) { $html .= "<input type=\"button\" class=\"mt-button mt-border-r-4px\" data-submit-action=\"{$action}\" value=\"{$value}\"/>\n"; } return $html; } public function setResourcesURL($url, $type = '') { switch ($type) { case 'js': $this->jsResourcesURL = $url; break; case 'css': $this->cssResourcesURL = $url; break; default: $this->resourcesURL = $url; } } public function getResourcesURL($type = '') { $url = $this->resourcesURL; switch ($type) { case 'js': if (!empty($this->jsResourcesURL)) { $url = $this->jsResourcesURL; } break; case 'css': if (!empty($this->cssResourcesURL)) { $url = $this->cssResourcesURL; } break; } return $url; } public function getCSS() { return ''; } public function getHTML() { $params = & $this->core->params; //NOTE: change subtype for some params to display them like radio foreach ($params->getProfiles() as $profile) { foreach ($params->getParams($profile) as $id => $param) { if ($params->getSubType($id, $profile) == 'select' && count($params->getValues($id, $profile)) < 6) { $params->setSubType($id, 'radio', $profile); } } } $license = $this->getLicenseType('magiczoomplus'); $mslicense = $this->getLicenseType('magicscroll'); $trial = ($license == 'trial' || $mslicense == 'trial'); //NOTE: spike for prestashop validator $GLOBALS['magictoolbox_temp_settings'] = $this; $GLOBALS['magictoolbox_temp_trial'] = $trial; $GLOBALS['magictoolbox_temp_params'] = $params; ob_start(); require(dirname(__FILE__).DIRECTORY_SEPARATOR.'magictoolbox.settings.editor.tpl.php'); $html = ob_get_clean(); unset($GLOBALS['magictoolbox_temp_settings']); unset($GLOBALS['magictoolbox_temp_trial']); unset($GLOBALS['magictoolbox_temp_params']); return $html; } } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_2377be3c2ad9b435ba277a73f0f1ca76'] = 'Fabricantes'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_49fa2426b7903b3d4c89e2c1874d9346'] = 'Mais informações sobre'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_bf24faeb13210b5a703f3ccef792b000'] = 'Todos os fabricantes'; $_MODULE['<{blockmanufacturer}touchmenot1.0.3>blockmanufacturer_1c407c118b89fa6feaae6b0af5fc0970'] = 'Nenhum fabricante'; <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ require_once dirname(__FILE__).'/../../classes/PowaTagRequestLogs.php'; abstract class PowaTagAPIAbstract { /** * Property: method * The HTTP method this request was made in, either GET, POST, PUT or DELETE. */ protected $method = ''; /** * Property: endpoint * The Model requested in the URI. eg: /files. */ protected $endpoint = ''; /** * Property: verb * An optional additional descriptor about the endpoint, used for things that can * not be handled by the basic methods. eg: /files/process. */ protected $verb = ''; /** * Property: args * Any additional URI components after the endpoint and verb have been removed, in our * case, an integer ID for the resource. eg: /<endpoint>/<verb>/<arg0>/<arg1> * or /<endpoint>/<arg0>. */ protected $args = array(); /** * Property: file * Stores the input of the PUT request. */ protected $file = null; /** * Property: Enable applicative log. * * @var bool */ protected static $api_log; /** * Property: Enable request log. * * @var bool */ protected static $request_log; /** * Instance of module. * * @var \Module */ protected $module; /** * Data in content call. * * @var string */ protected $data; /** * Response header. * * @var int */ protected $response = 200; /** * Constructor: __construct * Allow for CORS, assemble and pre-process the data. */ public function __construct($request) { header('Access-Control-Allow-Orgin: *'); header('Access-Control-Allow-Methods: *'); header('Content-Type: application/json; charset=utf-8'); $this->args = explode('/', rtrim($request, '/')); $this->endpoint = array_shift($this->args); if (array_key_exists(0, $this->args) && !is_numeric($this->args[0])) { $this->verb = array_shift($this->args); } $this->method = $_SERVER['REQUEST_METHOD']; if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) { if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') { $this->method = 'DELETE'; } elseif ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') { $this->method = 'PUT'; } else { throw new Exception('Unexpected Header'); } } $this->data = Tools::file_get_contents('php://input'); self::$api_log = Configuration::get('POWATAG_API_LOG'); self::$request_log = Configuration::get('POWATAG_REQUEST_LOG'); PowaTagRequestLogs::add(array( 'args' => $this->args, 'endpoint' => $this->endpoint, 'verb' => $this->verb, 'method' => $this->method, 'data' => $this->data, )); $this->module = Module::getInstanceByName('powatag'); } public function setResponse($response) { $this->response = $response; } public function getResponse() { return $this->response; } public function processAPI() { if ((int) method_exists($this, $this->endpoint) > 0) { return $this->_response(call_user_func(array($this, $this->endpoint), $this->args)); } $this->setResponse(404); return $this->_response('No Endpoint: $this->endpoint'); } protected function _response($data) { $status = $this->getResponse(); if (isset($data['response'])) { unset($data['response']); } header('HTTP/1.1 '.$status.' '.$this->_requestStatus($status)); PowaTagRequestLogs::add(array( 'response' => Tools::jsonEncode($data), )); return Tools::jsonEncode($data); } private function _cleanInputs($data) { $clean_input = array(); if (is_array($data)) { foreach ($data as $k => $v) { $clean_input[$k] = $this->_cleanInputs($v); } } else { $clean_input = trim(strip_tags($data)); } return $clean_input; } private function _requestStatus($code) { $status = array( 200 => 'OK', 400 => 'Bad Request', 404 => 'Not Found', 405 => 'Method Not Allowed', 500 => 'Internal Server Error', ); return ($status[$code]) ? $status[$code] : $status[500]; } public static function requestLog() { return self::$request_log; } public static function apiLog() { return self::$api_log; } public function powaError($error) { if (Configuration::get('POWATAG_LEGACY_ERRORS')) { $array = array( 'code' => $error['error']['legCode'], 'message' => $error['message'], ); $this->setResponse($error['error']['legResponse']); } else { $array = array( 'code' => $error['error']['code'], 'errorMessage' => $error['message'], ); $this->setResponse($error['error']['response']); } return $array; } } <file_sep>SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; ALTER TABLE `PREFIX_product_auction` ADD KEY `fk_PREFIX_product_auction_product_auction_offer` (`id_product_auction_offer`); ALTER TABLE `PREFIX_product_auction` ADD CONSTRAINT `fk_PREFIX_product_auction_product_auction_offer` FOREIGN KEY (id_product_auction_offer) REFERENCES PREFIX_product_auction_offer(id_product_auction_offer) ON DELETE SET null; <file_sep><?php /** * An attribute suggestion from an autocomplete request. * * @package prediggo4php * @subpackage types * * @author Stef */ class AttributeSuggestion { private $attributeName = ""; private $attributeValue = ""; private $searchQuery = ""; private $nbOccurrences = 0; /** * Get the number of possible matches with this suggestion * @return integer The number of occurrences */ public function getNbOccurrences() { return $this->nbOccurrences; } /** * Set the number of possible matches with this suggestion * @param integer $nbOccurrences The number of occurrences */ public function setNbOccurrences($nbOccurrences) { $this->nbOccurrences = $nbOccurrences; } /** * Sets the attribute name * @param string $attributeName The attribute name */ public function setAttributeName($attributeName) { $this->attributeName = $attributeName; } /** * gets the name of the attribute containing the matched value * @return string The attribute name */ public function getAttributeName() { return $this->attributeName; } /** * Sets the matched attribute value * @param string $attributeValue The attribute value */ public function setAttributeValue($attributeValue) { $this->attributeValue = $attributeValue; } /** * Gets the matched attribute value * @return string The attribute value */ public function getAttributeValue() { return $this->attributeValue; } /** * Sets the search query that can be given to the search engine * @param string $searchQuery The search query */ public function setSearchQuery($searchQuery) { $this->searchQuery = $searchQuery; } /** * Gets the search query that can be given to the search engine * @return string the search query */ public function getSearchQuery() { return $this->searchQuery; } } <file_sep><?php class FrontController extends FrontControllerCore { protected function smartyOutputContent($content) { //if the module is disabled, do not process the override if(!Module::isInstalled('expresscache') || !Module::isEnabled('expresscache')) { parent::smartyOutputContent($content); return; } //Updating this module to work with 1.6.x - June 5, 2014 - Vikas if (version_compare(_PS_VERSION_, '1.6.0', '>=')) { //Copying over the new smartyOutputContent Function. if (is_array($content)) foreach ($content as $tpl) $html = $this->context->smarty->fetch($tpl); else $html = $this->context->smarty->fetch($content); $html = trim($html); if ($this->controller_type == 'front' && !empty($html) && $this->getLayout()) { $dom_available = extension_loaded('dom') ? true : false; if ($dom_available) $html = Media::deferInlineScripts($html); $html = trim(str_replace(array('</body>', '</html>'), '', $html))."\n"; $this->context->smarty->assign(array( 'js_def' => Media::getJsDef(), 'js_files' => array_unique($this->js_files), 'js_inline' => $dom_available ? Media::getInlineScript() : array() )); $javascript = $this->context->smarty->fetch(_PS_ALL_THEMES_DIR_.'javascript.tpl'); $html = $html.$javascript."\t</body>\n</html>"; } $template = $html; } else { $template = $this->context->smarty->fetch($content, null, null, null); } $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; $isLogged = isset($this->context->customer) ? $this->context->customer->isLogged() : false; $isMobile = $this->context->getMobileDevice(); //when to save the cache if(!isset($_GET['no_cache']) && !$isAjax && !$isLogged && !$isMobile) { $page_name = Dispatcher::getInstance()->getController(); $c_controllers = explode(',', Configuration::get('EXPRESSCACHE_CONTROLLERS')); if(in_array($page_name, $c_controllers) && !isset($_GET['live_edit'])) { //normalise URL $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://'; $url = str_replace('&refresh_cache', '', $proto.$_SERVER['REQUEST_URI']); $url = str_replace('?refresh_cache', '?', $url); $page_id = md5($url); $id_langauge = (int)$this->context->language->id; $id_currency = (int)$this->context->currency->id; $id_country = (int)$this->context->country->id; $id_shop = (int)$this->context->shop->id; //check if we should delete the cache for this page or save it if(count($_POST) > 0) { Db::getInstance(_PS_USE_SQL_SLAVE_)->execute(" DELETE FROM "._DB_PREFIX_."express_cache WHERE page_id = '".$page_id."' and id_language = ".$id_langauge." and id_currency = ".$id_currency." and id_country = ".$id_country." and id_shop = ".$id_shop); } else { //echo $id_currency; $replace_insert = "INSERT"; if(isset($_GET['refresh_cache'])) { $replace_insert = "REPLACE"; } if(!Configuration::get('EXPRESSCACHE_STORE_IN_DB')) { $cache = $template; $filename = $page_id.$id_currency.$id_langauge.$id_country.$id_shop; //store in filesystem with filename $cache_dir = _PS_MODULE_DIR_.'expresscache/cache/'; file_put_contents($cache_dir.$filename, $cache, LOCK_EX); $cache = $filename; } else { //echo $template; $cache = addslashes($template); } Db::getInstance()->execute( $replace_insert." INTO "._DB_PREFIX_."express_cache VALUES ('".$page_id."',".$id_currency.",".$id_langauge.",".$id_country.",".$id_shop.",'".$cache."','". date('Y-m-d H:i:s')."')"); //echo Db::getInstance()->getMsgError(); } } } $html = $template; $this->context->cookie->write(); echo $html; //parent::smartyOutputContent($content); } } ?> <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author Magic Toolbox <<EMAIL>> * @copyright Copyright (c) 2015 Magic Toolbox <<EMAIL>>. All rights reserved * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) { exit; } if (!isset($GLOBALS['magictoolbox'])) { $GLOBALS['magictoolbox'] = array(); $GLOBALS['magictoolbox']['filters'] = array(); $GLOBALS['magictoolbox']['isProductScriptIncluded'] = false; $GLOBALS['magictoolbox']['standardTool'] = ''; $GLOBALS['magictoolbox']['selectorImageType'] = ''; } if (!isset($GLOBALS['magictoolbox']['magiczoomplus'])) { $GLOBALS['magictoolbox']['magiczoomplus'] = array(); $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = false; $GLOBALS['magictoolbox']['magiczoomplus']['scripts'] = ''; } class MagicZoomPlus extends Module { /* PrestaShop v1.5 or above */ public $isPrestaShop15x = false; /* PrestaShop v1.5.5.0 or above */ public $isPrestaShop155x = false; /* PrestaShop v1.6 or above */ public $isPrestaShop16x = false; /* Smarty v3 template engine */ public $isSmarty3 = false; /* Smarty 'getTemplateVars' function name */ public $getTemplateVars = 'getTemplateVars'; /* Suffix was added to default images types since version 1.5.1.0 */ public $imageTypeSuffix = ''; /* To display 'product.js' file inline */ public $displayInlineProductJs = false; public function __construct() { $this->name = 'magiczoomplus'; $this->tab = 'Tools'; $this->version = '5.7.13'; $this->author = 'Magic Toolbox'; $this->module_key = '23501dac81e578fbb7212ba65e8b6950'; //NOTE: to link bootstrap css for settings page in v1.6 $this->bootstrap = true; parent::__construct(); $this->displayName = 'Magic Zoom Plus'; $this->description = "Beautiful zoom and enlarge effect for your product images.&nbsp;<a target='_blank' title='Watch tutorial' style='color: #268CCD; text-decoration: underline; font-weight: bold;' href='http://www.youtube.com/watch?v=yAix6lXqyAw&t=0m54s'>Watch tutorial</a>."; $this->confirmUninstall = 'All magiczoomplus settings would be deleted. Do you really want to uninstall this module ?'; $this->isPrestaShop15x = version_compare(_PS_VERSION_, '1.5', '>='); $this->isPrestaShop155x = version_compare(_PS_VERSION_, '1.5.5', '>='); $this->isPrestaShop16x = version_compare(_PS_VERSION_, '1.6', '>='); $this->displayInlineProductJs = version_compare(_PS_VERSION_, '1.6.0.3', '>=') && version_compare(_PS_VERSION_, '1.6.0.7', '<'); if ($this->isPrestaShop16x) { $this->tab = 'others'; } $this->isSmarty3 = $this->isPrestaShop15x || Configuration::get('PS_FORCE_SMARTY_2') === '0'; if ($this->isSmarty3) { //Smarty v3 template engine $this->getTemplateVars = 'getTemplateVars'; } else { //Smarty v2 template engine $this->getTemplateVars = 'get_template_vars'; } $this->imageTypeSuffix = version_compare(_PS_VERSION_, '1.5.1.0', '>=') ? '_default' : ''; } public function install() { $headerHookID = $this->isPrestaShop15x ? Hook::getIdByName('displayHeader') : Hook::get('header'); if (!parent::install() || !$this->registerHook($this->isPrestaShop15x ? 'displayHeader' : 'header') || !$this->registerHook($this->isPrestaShop15x ? 'displayFooterProduct' : 'productFooter') || !$this->registerHook($this->isPrestaShop15x ? 'displayFooter' : 'footer') || !$this->installDB() || !$this->fixCSS() //NOTICE: this function can return false if the module is the only one in this position //|| !$this->updatePosition($headerHookID, 0, 1) || !($this->updatePosition($headerHookID, 0, 1) || true) /**/) { return false; } return true; } private function installDB() { if (!Db::getInstance()->Execute('CREATE TABLE `'._DB_PREFIX_.'magiczoomplus_settings` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `block` VARCHAR(32) NOT NULL, `name` VARCHAR(32) NOT NULL, `value` TEXT, `default_value` TEXT, `enabled` TINYINT(1) UNSIGNED NOT NULL, `default_enabled` TINYINT(1) UNSIGNED NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;') || !$this->fillDB() || !$this->fixDefaultValues() /**/) { return false; } return true; } private function fixCSS() { //fix url's in css files $path = dirname(__FILE__); $list = glob($path.'/*'); $files = array(); if (is_array($list)) { $listLength = count($list); for ($i = 0; $i < $listLength; $i++) { if (is_dir($list[$i])) { if (!in_array(basename($list[$i]), array('.svn', '.git'))) { $add = glob($list[$i].'/*'); if (is_array($add)) { $list = array_merge($list, $add); $listLength += count($add); } } } elseif (preg_match('#\.css$#i', $list[$i])) { $files[] = $list[$i]; } } } foreach ($files as $file) { $cssPath = dirname($file); $cssRelPath = str_replace($path, '', $cssPath); $toolPath = _MODULE_DIR_.'magiczoomplus'.$cssRelPath; $pattern = '#url\(\s*(\'|")?(?!data:|mhtml:|http(?:s)?:|/)([^\)\s\'"]+?)(?(1)\1)\s*\)#is'; $replace = 'url($1'.$toolPath.'/$2$1)'; $fileContents = Tools::file_get_contents($file); $fixedFileContents = preg_replace($pattern, $replace, $fileContents); //preg_match_all($pattern, $fileContents, $matches, PREG_SET_ORDER); //debug_log($matches); if ($fixedFileContents != $fileContents) { $fp = fopen($file, 'w+'); if ($fp) { fwrite($fp, $fixedFileContents); fclose($fp); } } } return true; } public function fixDefaultValues() { $result = true; if (version_compare(_PS_VERSION_, '1.5.1.0', '>=')) { $sql = 'UPDATE `'._DB_PREFIX_.'magiczoomplus_settings` SET `value`=CONCAT(value, \'_default\'), `default_value`=CONCAT(default_value, \'_default\') WHERE (`name`=\'thumb-image\' OR `name`=\'selector-image\' OR `name`=\'large-image\') AND `value`!=\'original\''; $result = Db::getInstance()->Execute($sql); } if ($this->isPrestaShop16x) { $sql = 'UPDATE `'._DB_PREFIX_.'magiczoomplus_settings` SET `value`=\'small_default\', `default_value`=\'small_default\', `enabled`=1 WHERE `name`=\'thumb-image\' AND (`block`=\'blocknewproducts\' OR `block`=\'blockbestsellers\' OR `block`=\'blockspecials\' OR `block`=\'blockviewed\')'; $result = Db::getInstance()->Execute($sql); } return $result; } public function uninstall() { if (version_compare(_PS_VERSION_, '1.5.5.0', '>=')) { $this->_clearCache('*'); } if (!parent::uninstall() || !$this->uninstallDB()) { return false; } return true; } private function uninstallDB() { return Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'magiczoomplus_settings`;'); } public function disable($forceAll = false) { if (version_compare(_PS_VERSION_, '1.5.5.0', '>=')) { $this->_clearCache('*'); } return parent::disable($forceAll); } public function enable($forceAll = false) { if (version_compare(_PS_VERSION_, '1.5.5.0', '>=')) { $this->_clearCache('*'); } return parent::enable($forceAll); } public function _clearCache($template, $cache_id = null, $compile_id = null) { $this->name = 'homefeatured';//NOTE: spike to clear cache for 'homefeatured.tpl' parent::_clearCache('homefeatured.tpl'); parent::_clearCache('tab.tpl', 'homefeatured-tab'); $this->name = 'blockbestsellers'; parent::_clearCache('blockbestsellers.tpl'); parent::_clearCache('blockbestsellers-home.tpl', 'blockbestsellers-home'); parent::_clearCache('blockbestsellers.tpl', 'blockbestsellers_col'); parent::_clearCache('tab.tpl', 'blockbestsellers-tab'); $this->name = 'blocknewproducts'; parent::_clearCache('blocknewproducts.tpl'); parent::_clearCache('blocknewproducts_home.tpl', 'blocknewproducts-home'); parent::_clearCache('tab.tpl', 'blocknewproducts-tab'); $this->name = 'blockspecials'; parent::_clearCache('blockspecials.tpl'); parent::_clearCache('blockspecials-home.tpl', 'blockspecials-home'); parent::_clearCache('tab.tpl', 'blockspecials-tab'); $this->name = 'blockspecials'; parent::_clearCache('blockspecials.tpl'); $this->name = 'magiczoomplus'; } public function getImagesTypes() { if (!isset($GLOBALS['magictoolbox']['imagesTypes'])) { $GLOBALS['magictoolbox']['imagesTypes'] = array('original'); // get image type values $sql = 'SELECT name FROM `'._DB_PREFIX_.'image_type` ORDER BY `id_image_type` ASC'; $result = Db::getInstance()->ExecuteS($sql); foreach ($result as $row) { $GLOBALS['magictoolbox']['imagesTypes'][] = $row['name']; } } return $GLOBALS['magictoolbox']['imagesTypes']; } public function getContent() { $action = Tools::getValue('magiczoomplus-submit-action', false); $activeTab = Tools::getValue('magiczoomplus-active-tab', false); if ($action == 'reset' && $activeTab) { Db::getInstance()->Execute( 'UPDATE `'._DB_PREFIX_.'magiczoomplus_settings` SET `value`=`default_value`, `enabled`=`default_enabled` WHERE `block`=\''.$activeTab.'\'' ); } $tool = $this->loadTool(); $paramsMap = $this->getParamsMap(); $_imagesTypes = array( 'selector', 'large', 'thumb' ); foreach ($_imagesTypes as $name) { foreach ($this->getBlocks() as $blockId => $blockLabel) { if ($tool->params->paramExists($name.'-image', $blockId)) { $tool->params->setValues($name.'-image', $this->getImagesTypes(), $blockId); } } } $paramData = $tool->params->getParam('magicscroll', 'product', false); $paramData['description'] = '<img id="magicscroll_icon" src="'._MODULE_DIR_.'magiczoomplus/views/img/magicscroll.png" />'.$paramData['description']; $tool->params->appendParams(array('magicscroll' => $paramData), 'product'); //debug_log($_GET); //debug_log($_POST); $params = Tools::getValue('magiczoomplus', false); //NOTE: save settings if ($action == 'save' && $params) { foreach ($paramsMap as $blockId => $groups) { foreach ($groups as $group) { foreach ($group as $param => $required) { if (isset($params[$blockId][$param])) { $valueToSave = $value = trim($params[$blockId][$param]); switch ($tool->params->getType($param)) { case 'num': $valueToSave = $value = (int)$value; break; case 'array': if (!in_array($value, $tool->params->getValues($param))) { $valueToSave = $value = $tool->params->getDefaultValue($param); } break; case 'text': $valueToSave = pSQL($value); break; } Db::getInstance()->Execute( 'UPDATE `'._DB_PREFIX_.'magiczoomplus_settings` SET `value`=\''.$valueToSave.'\', `enabled`=1 WHERE `block`=\''.$blockId.'\' AND `name`=\''.$param.'\'' ); $tool->params->setValue($param, $value, $blockId); } else { Db::getInstance()->Execute( 'UPDATE `'._DB_PREFIX_.'magiczoomplus_settings` SET `enabled`=0 WHERE `block`=\''.$blockId.'\' AND `name`=\''.$param.'\'' ); if ($tool->params->paramExists($param, $blockId)) { $tool->params->removeParam($param, $blockId); } } } } } if (version_compare(_PS_VERSION_, '1.5.5.0', '>=')) { $this->_clearCache('*'); } } include(dirname(__FILE__).'/admin/magictoolbox.settings.editor.class.php'); $settings = new MagictoolboxSettingsEditorClass(dirname(__FILE__).DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'js'); $settings->paramsMap = $this->getParamsMap(); $settings->core = $this->loadTool(); $settings->profiles = $this->getBlocks(); $settings->pathToJS = dirname(__FILE__).DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'js'; $settings->action = htmlentities($_SERVER['REQUEST_URI']); $settings->setResourcesURL(_MODULE_DIR_.'magiczoomplus/admin/resources/'); $settings->setResourcesURL(_MODULE_DIR_.'magiczoomplus/views/js/', 'js'); $settings->setResourcesURL(_MODULE_DIR_.'magiczoomplus/views/css/', 'css'); $settings->namePrefix = 'magiczoomplus'; $settings->pageTitle .= '&nbsp;<a target="_blank" title="Watch tutorial" href="http://www.youtube.com/watch?v=yAix6lXqyAw&t=0m54s" style="float: right;">Watch tutorial</a>'; $settings->languagesData = Db::getInstance()->ExecuteS('SELECT id_lang as id, iso_code as code, active FROM `'._DB_PREFIX_.'lang` ORDER BY `id_lang` ASC'); if ($activeTab) { $settings->activeTab = $activeTab; } $settings->addJSFile(_MODULE_DIR_.'magiczoomplus/views/js/options.js'); $html = $settings->getHTML(); $html .= ' <script type="text/javascript"> //<![CDATA[ initOptionsValidation(\''.$settings->getName('product', 'template').'\', \''.$settings->getName('product', 'magicscroll').'\'); //]]> </script>'; return $html; } public function loadTool($profile = false, $force = false) { if (!isset($GLOBALS['magictoolbox']['magiczoomplus']['class']) || $force) { require_once(dirname(__FILE__).'/magiczoomplus.module.core.class.php'); $GLOBALS['magictoolbox']['magiczoomplus']['class'] = new MagicZoomPlusModuleCoreClass(); $tool = &$GLOBALS['magictoolbox']['magiczoomplus']['class']; // load current params $sql = 'SELECT `name`, `value`, `block` FROM `'._DB_PREFIX_.'magiczoomplus_settings` WHERE `enabled`=1'; $result = Db::getInstance()->ExecuteS($sql); foreach ($result as $row) { $tool->params->setValue($row['name'], $row['value'], $row['block']); } // load translates $GLOBALS['magictoolbox']['magiczoomplus']['translates'] = $this->getMessages(); $translates = & $GLOBALS['magictoolbox']['magiczoomplus']['translates']; foreach ($this->getBlocks() as $block => $label) { if ($translates[$block]['message']['title'] != $translates[$block]['message']['translate']) { $tool->params->setValue('message', $translates[$block]['message']['translate'], $block); } if ($translates[$block]['textHoverZoomHint']['title'] != $translates[$block]['textHoverZoomHint']['translate']) { $tool->params->setValue('textHoverZoomHint', $translates[$block]['textHoverZoomHint']['translate'], $block); } if ($translates[$block]['textClickZoomHint']['title'] != $translates[$block]['textClickZoomHint']['translate']) { $tool->params->setValue('textClickZoomHint', $translates[$block]['textClickZoomHint']['translate'], $block); } if ($translates[$block]['textHoverZoomHintForMobile']['title'] != $translates[$block]['textHoverZoomHintForMobile']['translate']) { $tool->params->setValue('textHoverZoomHintForMobile', $translates[$block]['textHoverZoomHintForMobile']['translate'], $block); } if ($translates[$block]['textClickZoomHintForMobile']['title'] != $translates[$block]['textClickZoomHintForMobile']['translate']) { $tool->params->setValue('textClickZoomHintForMobile', $translates[$block]['textClickZoomHintForMobile']['translate'], $block); } if ($translates[$block]['textExpandHint']['title'] != $translates[$block]['textExpandHint']['translate']) { $tool->params->setValue('textExpandHint', $translates[$block]['textExpandHint']['translate'], $block); } if ($translates[$block]['textBtnClose']['title'] != $translates[$block]['textBtnClose']['translate']) { $tool->params->setValue('textBtnClose', $translates[$block]['textBtnClose']['translate'], $block); } if ($translates[$block]['textBtnNext']['title'] != $translates[$block]['textBtnNext']['translate']) { $tool->params->setValue('textBtnNext', $translates[$block]['textBtnNext']['translate'], $block); } if ($translates[$block]['textBtnPrev']['title'] != $translates[$block]['textBtnPrev']['translate']) { $tool->params->setValue('textBtnPrev', $translates[$block]['textBtnPrev']['translate'], $block); } if ($translates[$block]['textExpandHintForMobile']['title'] != $translates[$block]['textExpandHintForMobile']['translate']) { $tool->params->setValue('textExpandHintForMobile', $translates[$block]['textExpandHintForMobile']['translate'], $block); } // prepare image types foreach (array('large', 'selector', 'thumb') as $name) { if ($tool->params->checkValue($name.'-image', 'original', $block)) { $tool->params->setValue($name.'-image', false, $block); } } } if ($tool->params->checkValue('magicscroll', 'Yes', 'product')) { require_once(dirname(__FILE__).'/magicscroll.module.core.class.php'); $GLOBALS['magictoolbox']['magiczoomplus']['magicscroll'] = new MagicScrollModuleCoreClass(false); $scroll = &$GLOBALS['magictoolbox']['magiczoomplus']['magicscroll']; //NOTE: load params in a separate profile, in order not to overwrite the options of MagicScroll module $scroll->params->appendParams($tool->params->getParams('product'), 'product-magicscroll-options'); $scroll->params->setValue('orientation', ($tool->params->checkValue('template', array('left', 'right'), 'product') ? 'vertical' : 'horizontal'), 'product-magicscroll-options'); //NOTE: if Magic Scroll module installed we need to load settings before displaying custom options if (parent::isInstalled('magicscroll')) { $magicscrollModule = parent::getInstanceByName('magicscroll'); if ($magicscrollModule->active) { $magicscrollModule->loadTool(); } } } } $tool = &$GLOBALS['magictoolbox']['magiczoomplus']['class']; if ($profile) { $tool->params->setProfile($profile); } return $tool; } public function hookHeader($params) { //global $smarty; $smarty = &$GLOBALS['smarty']; //debug_log('MagicZoomPlus hookHeader'); if (!$this->isPrestaShop15x) { ob_start(); } $headers = ''; $tool = $this->loadTool(); $tool->params->resetProfile(); $page = $smarty->{$this->getTemplateVars}('page_name'); switch ($page) { case 'product': case 'index': case 'category': case 'manufacturer': case 'search': break; case 'best-sales': $page = 'bestsellerspage'; break; case 'new-products': $page = 'newproductpage'; break; case 'prices-drop': $page = 'specialspage'; break; default: $page = ''; } if ($tool->params->checkValue('include-headers-on-all-pages', 'Yes', 'default') && ($GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true) || $tool->params->profileExists($page) && !$tool->params->checkValue('enable-effect', 'No', $page) || $page == 'index' && !$tool->params->checkValue('enable-effect', 'No', 'homefeatured') && parent::isInstalled('homefeatured') && parent::getInstanceByName('homefeatured')->active || $page == 'index' && !$tool->params->checkValue('enable-effect', 'No', 'blocknewproducts_home') && parent::isInstalled('blocknewproducts') && parent::getInstanceByName('blocknewproducts')->active || $page == 'index' && !$tool->params->checkValue('enable-effect', 'No', 'blockbestsellers_home') && parent::isInstalled('blockbestsellers') && parent::getInstanceByName('blockbestsellers')->active || $page == 'index' && !$tool->params->checkValue('enable-effect', 'No', 'blockspecials_home') && parent::isInstalled('blockspecials') && parent::getInstanceByName('blockspecials')->active || !$tool->params->checkValue('enable-effect', 'No', 'blockviewed') && parent::isInstalled('blockviewed') && parent::getInstanceByName('blockviewed')->active || !$tool->params->checkValue('enable-effect', 'No', 'blockspecials') && parent::isInstalled('blockspecials') && parent::getInstanceByName('blockspecials')->active || (!$tool->params->checkValue('enable-effect', 'No', 'blocknewproducts') || ($page == 'index' && !$tool->params->checkValue('enable-effect', 'No', 'blocknewproducts_home'))) && parent::isInstalled('blocknewproducts') && parent::getInstanceByName('blocknewproducts')->active || (!$tool->params->checkValue('enable-effect', 'No', 'blockbestsellers') || ($page == 'index' && !$tool->params->checkValue('enable-effect', 'No', 'blockbestsellers_home'))) && parent::isInstalled('blockbestsellers') && parent::getInstanceByName('blockbestsellers')->active /**/) { // include headers $headers = $tool->getHeadersTemplate(_MODULE_DIR_.'magiczoomplus/views/js', _MODULE_DIR_.'magiczoomplus/views/css'); //NOTE: if we need this on product page!? $headers .= '<script type="text/javascript" src="'._MODULE_DIR_.'magiczoomplus/views/js/common.js"></script>'; if ($page == 'product' && !$tool->params->checkValue('enable-effect', 'No', 'product')) { $useScroll = $tool->params->checkValue('magicscroll', 'Yes', 'product'); if (/*$page == 'product' && */$useScroll) { $scroll = &$GLOBALS['magictoolbox']['magiczoomplus']['magicscroll']; $scroll->params->resetProfile(); $headers = $scroll->getHeadersTemplate(_MODULE_DIR_.'magiczoomplus/views/js', _MODULE_DIR_.'magiczoomplus/views/css', false).$headers; } $mouseEvent = $tool->params->getValue('selectorTrigger', 'product'); if ($mouseEvent == 'hover') { $mouseEvent = 'mouseover'; } $items = $tool->params->getValue('items', 'product');//auto | fit | integer | array $items = is_numeric($items) ? (int)$items : 0; $headers .= ' <script type="text/javascript"> var isPrestaShop15x = '.($this->isPrestaShop15x ? 'true' : 'false').'; var isPrestaShop1541 = '.(version_compare(_PS_VERSION_, '1.5.4.1', '>=') ? 'true' : 'false').'; var isPrestaShop156x = '.(version_compare(_PS_VERSION_, '1.5.6', '>=') ? 'true' : 'false').'; var isPrestaShop16x = '.($this->isPrestaShop16x ? 'true' : 'false').'; var mEvent = \''.$mouseEvent.'\'; var originalLayout = '.($tool->params->checkValue('template', 'original', 'product') ? 'true' : 'false').'; var useMagicScroll = '.($useScroll ? 'true' : 'false').'; var scrollItems = '.$items.';'. ($useScroll ? ' var isProductMagicScrollStopped = true; MagicScrollOptions[\'onReady\'] = function(id) { //console.log(\'MagicScroll onReady: \', id); if (id == \'MagicToolboxSelectors'.(int)Tools::getValue('id_product').'\') { isProductMagicScrollStopped = false; } } MagicScrollOptions[\'onStop\'] = function(id) { //console.log(\'MagicScroll onStop: \', id); if (id == \'MagicToolboxSelectors'.(int)Tools::getValue('id_product').'\') { isProductMagicScrollStopped = true; } } ' :'').' var isProductMagicZoomReady = false; mzOptions[\'onZoomReady\'] = function(id) { //console.log(\'MagicZoomPlus onZoomReady: \', id); if (id == \'MagicZoomPlusImageMainImage\') { isProductMagicZoomReady = true; } } /* mzOptions[\'onUpdate\'] = function(id, oldA, newA) { //console.log(\'MagicZoomPlus onUpdate: \', id); if (id == \'MagicZoomPlusImageMainImage\') { isProductMagicZoomReady = true; } } */ </script>'; if (!$GLOBALS['magictoolbox']['isProductScriptIncluded']) { if ($this->displayInlineProductJs || (bool)Configuration::get('PS_JS_DEFER')) { //NOTE: include product.js as inline because it has to be called after previous inline scripts $productJsCContents = Tools::file_get_contents(_PS_ROOT_DIR_.'/modules/magiczoomplus/views/js/product.js'); $headers .= "\n".'<script type="text/javascript">'.$productJsCContents.'</script>'."\n"; } else { $headers .= "\n".'<script type="text/javascript" src="'._MODULE_DIR_.'magiczoomplus/views/js/product.js"></script>'."\n"; } $GLOBALS['magictoolbox']['isProductScriptIncluded'] = true; } } $domNotAvailable = extension_loaded('dom') ? false : true; if ($this->displayInlineProductJs && $domNotAvailable) { $scriptsPattern = '#(?:\s*+<script\b[^>]*+>.*?<\s*+/script\b[^>]*+>)++#Uims'; if (preg_match($scriptsPattern, $headers, $scripts)) { $GLOBALS['magictoolbox']['magiczoomplus']['scripts'] = '<!-- MAGICZOOMPLUS HEADERS START -->'.$scripts[0].'<!-- MAGICZOOMPLUS HEADERS END -->'; $headers = preg_replace($scriptsPattern, '', $headers); } } if ($this->isSmarty3) { //Smarty v3 template engine if (isset($GLOBALS['magictoolbox']['filters']['magic360'])) { $smarty->unregisterFilter('output', array(Module::getInstanceByName('magic360'), 'parseTemplateCategory')); } $smarty->registerFilter('output', array(Module::getInstanceByName('magiczoomplus'), 'parseTemplateStandard')); if (isset($GLOBALS['magictoolbox']['filters']['magic360'])) { $smarty->registerFilter('output', array(Module::getInstanceByName('magic360'), 'parseTemplateCategory')); } } else { //Smarty v2 template engine if (isset($GLOBALS['magictoolbox']['filters']['magic360'])) { $smarty->unregister_outputfilter(array(Module::getInstanceByName('magic360'), 'parseTemplateCategory')); } $smarty->register_outputfilter(array(Module::getInstanceByName('magiczoomplus'), 'parseTemplateStandard')); if (isset($GLOBALS['magictoolbox']['filters']['magic360'])) { $smarty->register_outputfilter(array(Module::getInstanceByName('magic360'), 'parseTemplateCategory')); } } $GLOBALS['magictoolbox']['filters']['magiczoomplus'] = 'parseTemplateStandard'; // presta create new class every time when hook called // so we need save our data in the GLOBALS $GLOBALS['magictoolbox']['magiczoomplus']['cookie'] = $params['cookie']; $GLOBALS['magictoolbox']['magiczoomplus']['productsViewedIds'] = (isset($params['cookie']->viewed) && !empty($params['cookie']->viewed)) ? explode(',', $params['cookie']->viewed) : array(); $headers = '<!-- MAGICZOOMPLUS HEADERS START -->'.$headers.'<!-- MAGICZOOMPLUS HEADERS END -->'; } return $headers; } public function hookProductFooter($params) { //we need save this data in the GLOBALS for compatible with some Prestashop module which reset the $product smarty variable $GLOBALS['magictoolbox']['magiczoomplus']['product'] = array('id' => $params['product']->id, 'name' => $params['product']->name, 'link_rewrite' => $params['product']->link_rewrite); return ''; } public function hookFooter($params) { if (!$this->isPrestaShop15x) { $contents = ob_get_contents(); ob_end_clean(); if ($GLOBALS['magictoolbox']['magiczoomplus']['headers'] == false) { $contents = preg_replace('/<\!-- MAGICZOOMPLUS HEADERS START -->.*?<\!-- MAGICZOOMPLUS HEADERS END -->/is', '', $contents); } else { $contents = preg_replace('/<\!-- MAGICZOOMPLUS HEADERS (START|END) -->/is', '', $contents); } echo $contents; } return ''; } private static $outputMatches = array(); public function prepareOutput($output, $index = 'DEFAULT') { if (!isset(self::$outputMatches[$index])) { preg_match_all('/<div [^>]*?class="[^"]*?MagicToolboxContainer[^"]*?".*?<\/div>\s/is', $output, self::$outputMatches[$index]); foreach (self::$outputMatches[$index][0] as $key => $match) { $output = str_replace($match, 'MAGICZOOMPLUS_MATCH_'.$index.'_'.$key.'_', $output); } } else { foreach (self::$outputMatches[$index][0] as $key => $match) { $output = str_replace('MAGICZOOMPLUS_MATCH_'.$index.'_'.$key.'_', $match, $output); } unset(self::$outputMatches[$index]); } return $output; } public function parseTemplateStandard($output, $smarty) { if ($this->isSmarty3) { //Smarty v3 template engine $currentTemplate = Tools::substr(basename($smarty->template_resource), 0, -4); if ($currentTemplate == 'breadcrumb') { $currentTemplate = 'product'; } elseif ($currentTemplate == 'pagination') { $currentTemplate = 'category'; } } else { //Smarty v2 template engine $currentTemplate = $smarty->currentTemplate; } if ($this->isPrestaShop15x && $currentTemplate == 'layout') { if (version_compare(_PS_VERSION_, '1.5.5.0', '>=')) { //NOTE: because we do not know whether the effect is applied to the blocks in the cache $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; } //NOTE: full contents in prestashop 1.5.x if ($GLOBALS['magictoolbox']['magiczoomplus']['headers'] == false) { $output = preg_replace('/<\!-- MAGICZOOMPLUS HEADERS START -->.*?<\!-- MAGICZOOMPLUS HEADERS END -->/is', '', $output); } else { $output = preg_replace('/<\!-- MAGICZOOMPLUS HEADERS (START|END) -->/is', '', $output); } return $output; } switch ($currentTemplate) { case 'search': case 'manufacturer': //$currentTemplate = 'manufacturer'; break; case 'best-sales': $currentTemplate = 'bestsellerspage'; break; case 'new-products': $currentTemplate = 'newproductpage'; break; case 'prices-drop': $currentTemplate = 'specialspage'; break; case 'blockbestsellers-home': $currentTemplate = 'blockbestsellers_home'; break; case 'blockspecials-home': $currentTemplate = 'blockspecials_home'; break; case 'product-list'://for 'Layered navigation block' if (strpos($_SERVER['REQUEST_URI'], 'blocklayered-ajax.php') !== false) { $currentTemplate = 'category'; } break; case 'javascript': if ($GLOBALS['magictoolbox']['magiczoomplus']['scripts']) { $output .= $GLOBALS['magictoolbox']['magiczoomplus']['scripts']; } } $tool = $this->loadTool(); if (!$tool->params->profileExists($currentTemplate) || $tool->params->checkValue('enable-effect', 'No', $currentTemplate)) { return $output; } $tool->params->setProfile($currentTemplate); //global $link; $link = &$GLOBALS['link']; $cookie = &$GLOBALS['magictoolbox']['magiczoomplus']['cookie']; if (method_exists($link, 'getImageLink')) { $_link = &$link; } else { /* for Prestashop ver 1.1 */ $_link = &$this; } $output = self::prepareOutput($output); switch ($currentTemplate) { case 'homefeatured': $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; $categoryID = $this->isPrestaShop15x ? Context::getContext()->shop->getCategory() : 1; $category = new Category($categoryID); $nb = (int)Configuration::get('HOME_FEATURED_NBR');//Number of product displayed $products = $category->getProducts((int)$cookie->id_lang, 1, ($nb ? $nb : 10)); if (!is_array($products)) { break; } foreach ($products as $product) { $lrw = $product['link_rewrite']; if (!$tool->params->checkValue('link-to-product-page', 'No')) { $lnk = $link->getProductLink($product['id_product'], $lrw, isset($product['category']) ? $product['category'] : null); } else { $lnk = false; } $thumb = $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('thumb-image')); $image = $tool->getMainTemplate(array( 'id' => 'homefeatured'.$product['id_image'], 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('large-image')), 'thumb' => $thumb, 'title' => $product['name'], 'group' => 'homefeatured', )); //need a.product_image > img for blockcart module $image = '<div class="MagicToolboxContainer">'. '<div style="width:0px;height:1px;overflow:hidden;visibility:hidden;">'. '<a class="product_image" href="#">'. '<img src="'.$thumb.'" />'. '</a>'. '</div>'. $image. '</div>'; //$image = '<div class="MagicToolboxContainer">'.$image.'</div>'; $image_pattern = preg_quote($_link->getImageLink($lrw, $product['id_image'], 'home'.$this->imageTypeSuffix), '/'); $image_pattern = str_replace('\-home'.$this->imageTypeSuffix, '\-[^"]*?', $image_pattern); $image_pattern = '<img[^>]*?src="[^"]*?'.$image_pattern.'"[^>]*>'; $pattern = $image_pattern.'[^<]*(<span[^>]*?class="new"[^>]*>[^<]*<\/span>)?'; $pattern = '<a[^>]*?href="[^"]*?"[^>]*>[^<]*'.$pattern.'[^<]*<\/a>|'.$image_pattern; $output = preg_replace('/'.$pattern.'/is', $image, $output); } break; case 'category': case 'manufacturer': case 'newproductpage': case 'bestsellerspage': case 'specialspage': case 'search': //global $p, $n, $orderBy, $orderWay; //$category = new Category((int)Tools::getValue('id_category'), (int)$cookie->id_lang); //$products = $category->getProducts((int)$cookie->id_lang, (int)$p, (int)$n, $orderBy, $orderWay); $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; $products = $smarty->{$this->getTemplateVars}('products'); if (!is_array($products)) { break; } foreach ($products as $product) { $lrw = $product['link_rewrite']; if (!$tool->params->checkValue('link-to-product-page', 'No')) { $lnk = $link->getProductLink($product['id_product'], $lrw, isset($product['category']) ? $product['category'] : null); } else { $lnk = false; } $thumb = $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('thumb-image')); $html = $tool->getMainTemplate(array( 'id' => 'category'.$product['id_image'], 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('large-image')), 'thumb' => $thumb, 'title' => $product['name'], 'group' => 'category', )); //$html = preg_replace('/<a class="MagicZoomPlus"/is', '<a class="MagicZoomPlus product_img_link"', $html); /* //DEPRECATED: $image_suffix = $tool->params->getValue('thumb-image') ? '-'.$tool->params->getValue('thumb-image') : ''; $file_path = _PS_PROD_IMG_DIR_.$product['id_image'].$image_suffix.'.jpg'; if (!file_exists($file_path)) { $split_ids = explode('-', $product['id_image']); $id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]); $folders = implode('/', str_split((string)$id_image)).'/'; $file_path = _PS_PROD_IMG_DIR_.$folders.$id_image.$image_suffix.'.jpg'; } $size = getimagesize($file_path); /**/ if (!$this->isPrestaShop16x) { //$html = '<div class="MagicToolboxContainer" style="float: left; width: '.$size[0].'px; margin-right: 0.6em;" >'. $html = '<div class="MagicToolboxContainer">'. //need a.product_img_link > img for blockcart module '<div style="width:0px;height:1px;overflow:hidden;visibility:hidden;"><a class="product_img_link" href="#"><img src="'.$thumb.'" /></a></div>'. $html. '</div>'; } $image_pattern = preg_quote($_link->getImageLink($lrw, $product['id_image'], 'home'.$this->imageTypeSuffix), '/'); $image_pattern = str_replace('\-home'.$this->imageTypeSuffix, '\-[^"]*?', $image_pattern); $image_pattern = '<img[^>]*?src="[^"]*?'.$image_pattern.'"[^>]*>'; $pattern = $image_pattern.'[^<]*(<span[^>]*?class="new"[^>]*>[^<]*<\/span>)?'; $pattern = '<a[^>]*?href="[^"]*?"[^>]*>[^<]*'.$pattern.'[^<]*<\/a>|'.$image_pattern; if (!$this->isPrestaShop16x) { //NOTE: for span.new banners if (preg_match('/'.$pattern.'/is', $output, $matches)) { if (isset($matches[1])) { $html = preg_replace('/<\/div>$/is', $matches[1].'</div>', $html); } } } $output = preg_replace('/'.$pattern.'/is', $html, $output); } break; case 'product': //debug_log('MagicZoomPlus parseTemplateStandard product'); if (!isset($GLOBALS['magictoolbox']['magiczoomplus']['product'])) { //for skip loyalty module product.tpl break; } //$product = new Product((int)$smarty->$tpl_vars['product']->id, true, (int)$cookie->id_lang); //get some data from $GLOBALS for compatible with Prestashop modules which reset the $product smarty variable $product = new Product((int)$GLOBALS['magictoolbox']['magiczoomplus']['product']['id'], true, (int)$cookie->id_lang); $lrw = $product->link_rewrite; $pid = (int)$product->id; $productImages = $product->getImages((int)$cookie->id_lang); if (!is_array($productImages) || empty($productImages)) { break; } $cover = $smarty->{$this->getTemplateVars}('cover'); if (!isset($cover['id_image'])) { break; } $coverImageIds = is_numeric($cover['id_image']) ? $pid.'-'.$cover['id_image'] : $cover['id_image']; //NOTE: to use magic360 module with magiczoomplus $used360 = false; if (isset($GLOBALS['magictoolbox']['magic360'])) { $images = Db::getInstance()->ExecuteS('SELECT id_image FROM `'._DB_PREFIX_.'magic360_images` WHERE id_product='.$pid.' LIMIT 1'); if (count($images) && !$GLOBALS['magictoolbox']['magic360']['class']->params->checkValue('enable-effect', 'No', 'product')) { $used360 = true; $GLOBALS['magictoolbox']['standardTool'] = 'magiczoomplus'; $GLOBALS['magictoolbox']['selectorImageType'] = $tool->params->getValue('selector-image'); //DEPRECATED: disable transition effect to prevent the disappearance of the image when it is toggled //$tool->params->setValue('transitionEffect', 'No', 'product'); } } $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; $thumb = $_link->getImageLink($lrw, $coverImageIds, $tool->params->getValue('thumb-image')); $image = $tool->getMainTemplate(array( 'id' => 'MainImage', 'img' => $_link->getImageLink($lrw, $coverImageIds, $tool->params->getValue('large-image')), 'thumb' => $thumb, 'title' => $product->name, 'alt' => $cover['legend'], )); $selectors = array(); $selectorIDs = array(); foreach ($productImages as $i) { //NOTE: to prevent dublicates if (isset($selectorIDs[$i['id_image']])) { continue; } $s = $tool->getSelectorTemplate(array( 'id' => 'MainImage', 'img' => $_link->getImageLink($lrw, $pid.'-'.$i['id_image'], $tool->params->getValue('large-image')), 'medium' => $_link->getImageLink($lrw, $pid.'-'.$i['id_image'], $tool->params->getValue('thumb-image')), 'thumb' => $_link->getImageLink($lrw, $pid.'-'.$i['id_image'], $tool->params->getValue('selector-image')), 'title' => $i['legend'], 'alt' => $i['legend'] )); $selectorIDs[$i['id_image']] = $i['id_image']; $selectorClass = 'magictoolbox-selector'; if ($used360) { $selectorClass .= ' zoom-with-360'; } //NOTE: onclick for prevent click on selector before it is initialized $s = str_replace('<a ', '<a class="'.$selectorClass.'" data-thumb-id="'.$i['id_image'].'" onclick="return false;" ', $s); if ($tool->params->checkValue('template', 'original')) { $s = str_replace('<img ', '<img id="thumb_'.$i['id_image'].'" ', $s); $pattern = preg_quote($_link->getImageLink($lrw, $pid.'-'.$i['id_image'], 'medium'.$this->imageTypeSuffix), '/'); $pattern = '<img\b[^>]*?\bsrc="[^"]*?'.$pattern.'"[^>]*+>'; $pattern = '(?:<img\b[^>]*?\bid="thumb_'.$i['id_image'].'"[^>]*+>|'.$pattern.')'; $pattern = '<a\b[^>]*+>[^<]*+'.$pattern.'[^<]*+<\/a>|'.$pattern; //NOTE: append selector in their preserved place $output = preg_replace('/'.$pattern.'/is', $s, $output, 1); } else { $selectors[] = $s; } } //NOTE: to use magic360 module with magiczoomplus if ($used360) { $image = '<div style="position: relative;">'. '<div id="mainImageContainer" style="position: absolute; left: -5000px;">'. //NOTE: we need this div because of issue with MZP, which clones the parent node '<div>'.$image.'</div>'. '</div>'. '<div id="magic360Container"><!-- MAGIC360 --></div>'. '</div>'; if ($tool->params->checkValue('template', 'original')) { $output = preg_replace('/(<ul\b[^>]*?id="thumbs_list_frame"[^>]*>)/is', '$1<li id="thumbnail_9999999999"><!-- MAGIC360SELECTOR --></li>', $output); } else { array_unshift($selectors, '<!-- MAGIC360SELECTOR -->'); } } $templateParamValue = ''; if ($tool->params->checkValue('template', 'original')) { $templateParamValue = $tool->params->getValue('template'); $tool->params->setValue('template', 'bottom'); //NOTE: make views_block visible (it is hidden when product has only one image) when magic360 icon is added if ($GLOBALS['magictoolbox']['standardTool'] && count($productImages) == 1) { $output = preg_replace('/(<div\s[^>]*?id="views_block"[^>]*?class="[^"]*?)hidden([^"]*"[^>]*>)/is', '$1$2', $output); //NOTE: pattern breaks down a bit without this p.clear $output = preg_replace('/(<ul\b[^>]*?id="usefull_link_block"[^>]*>)/is', '<p class="clear"></p>$1', $output); } } else { //NOTE: hide selectors from contents //NOTE: 'image-additional' added to support custom theme #53897 //NOTE: div#views_block is parent for div#thumbs_list $thumbsPattern = '(<div\b[^>]*?(?:\bid\s*+=\s*+"(?:views_block|thumbs_list)"|\bclass\s*+=\s*+"[^"]*?\bimage-additional\b[^"]*+")[^>]*+>)'. '('. '(?:'. '[^<]++'. '|'. '<(?!/?div\b|!--)'. '|'. '<!--.*?-->'. '|'. '<div\b[^>]*+>'. '(?2)'. '</div\s*+>'. ')*+'. ')'. '</div\s*+>'; $matches = array(); if (preg_match("#{$thumbsPattern}#is", $output, $matches)) { if (strpos($matches[1], 'class')) { $replace = preg_replace('#\bclass\s*+=\s*+"#i', '$0hidden-important ', $matches[1]); } else { $replace = preg_replace('#<div\b#i', '$0 class="hidden-important"', $matches[1]); } $output = str_replace($matches[1], $replace, $output); } //NOTE: remove "View full size" link in old PrestaShop $output = preg_replace('/<li[^>]*+>[^<]*+<span[^>]*?id="view_full_size"[^>]*+>[^<]*<\/span>[^<]*+<\/li>/is', '', $output); //NOTE: hide span#wrapResetImages $matches = array(); if (preg_match('#(?:<span\b[^>]*?\bid\s*+=\s*+"wrapResetImages"[^>]*+>|<a\b[^>]*?\bid\s*+=\s*+"resetImages"[^>]*+>)#is', $output, $matches)) { if (strpos($matches[0], 'class')) { $replace = preg_replace('#\bclass\s*+=\s*+"#i', '$0hidden-important ', $matches[0]); } else { $replace = preg_replace('#<span\b#i', '$0 class="hidden-important"', $matches[0]); } $output = str_replace($matches[0], $replace, $output); } } //NOTE: we need this sizes for template renderer $sql = 'SELECT name, width, height FROM `'._DB_PREFIX_.'image_type` WHERE name in (\''.$tool->params->getValue('thumb-image').'\', \''.$tool->params->getValue('selector-image').'\')'; $result = Db::getInstance()->ExecuteS($sql); $result[$result[0]['name']] = $result[0]; $result[$result[1]['name']] = $result[1]; $tool->params->setValue('thumb-max-width', $result[$tool->params->getValue('thumb-image')]['width']); $tool->params->setValue('thumb-max-height', $result[$tool->params->getValue('thumb-image')]['height']); $tool->params->setValue('selector-max-width', $result[$tool->params->getValue('selector-image')]['width']); $tool->params->setValue('selector-max-height', $result[$tool->params->getValue('selector-image')]['height']); require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'magictoolbox.templatehelper.class.php'); MagicToolboxTemplateHelperClass::setPath(dirname(__FILE__).DIRECTORY_SEPARATOR.'templates'); MagicToolboxTemplateHelperClass::setOptions($tool->params); $scrollTool = null; if (isset($GLOBALS['magictoolbox']['magiczoomplus']['magicscroll'])) { $scrollTool = &$GLOBALS['magictoolbox']['magiczoomplus']['magicscroll']; } $html = MagicToolboxTemplateHelperClass::render(array( 'main' => $image, 'thumbs' => $selectors, 'magicscrollOptions' => $scrollTool ? $scrollTool->params->serialize(false, '', 'product-magicscroll-options') : '', 'pid' => $pid, )); if ($templateParamValue) { //NOTE: in some cases, the wrong template is processed first // so we need to restore the old option value for the next time $tool->params->setValue('template', $templateParamValue); } if (!$tool->params->checkValue('template', 'original')) { //NOTE: disable MagicScroll on page load (to start manually) //$html = preg_replace('#(class="[^"]*?\bMagicScroll\b)([^"]*+")#i', '$1Disabled hidden-important$2', $html);//DEPRECATED: used 'autostart:false' instead if ($tool->params->checkValue('magicscroll', 'Yes')) { $html = preg_replace('#(class="[^"]*?\bMagicScroll\b)([^"]*+"[^>]*?data-options=")#i', '$1 hidden-important$2autostart:false;', $html); } //NOTE: for combinations and magicscroll=yes $html .= ' <div id="MagicToolboxHiddenSelectors" class="hidden-important"></div> <script type="text/javascript"> //<![CDATA[ magictoolboxImagesOrder = ['.implode(',', $selectorIDs).']; //]]> </script> '; } //DEPRECATED: //need img#bigpic for blockcart module //$html = preg_replace('#<div\b[^>]*?class="[^"]*?\bMagicToolboxContainer\b[^"]*+"[^>]*+>#is', '$0<div style="width:0px;height:1px;overflow:hidden;visibility:hidden;"><img id="bigpic" src="'.$thumb.'" /></div>', $html); //NOTE: append main container //NOTE: 'image' class added to support custom theme #53897 $mainImagePattern = '(<div\b[^>]*?(?:\bid\s*+=\s*+"image-block"|\bclass\s*+=\s*+"[^"]*?\bimage\b[^"]*+")[^>]*+>)'. '('. '(?:'. '[^<]++'. '|'. '<(?!/?div\b|!--)'. '|'. '<!--.*?-->'. '|'. '<div\b[^>]*+>'. '(?2)'. '</div\s*+>'. ')*+'. ')'. '</div\s*+>'; //preg_match_all('%'.$pattern.'%is', $output, $__matches, PREG_SET_ORDER); //NOTE: limit = 1 because pattern can be matched with other products, located below the main product //$output = preg_replace('%'.$pattern.'%is', '$1<div class="hidden-important">$2</div>'.$html.'</div>', $output, 1); $matches = array(); if (!preg_match('%'.$mainImagePattern.'%is', $output, $matches)) { break; } $iconsPattern = '<span\b[^>]*?\bclass\s*+=\s*+"[^"]*?\b(?:new-box|sale-box|discount)\b[^"]*+"[^>]*+>'. '('. '(?:'. '[^<]++'. '|'. '<(?!/?span\b|!--)'. '|'. '<!--.*?-->'. '|'. '<span\b[^>]*+>'. '(?1)'. '</span\s*+>'. ')*+'. ')'. '</span\s*+>'; $iconMatches = array(); if (preg_match_all('%'.$iconsPattern.'%is', $matches[2], $iconMatches, PREG_SET_ORDER)) { foreach ($iconMatches as $key => $iconMatch) { $matches[2] = str_replace($iconMatch[0], '', $matches[2]); $iconMatches[$key] = $iconMatch[0]; } } $icons = implode('', $iconMatches); $output = str_replace($matches[0], "{$matches[1]}{$icons}<div class=\"hidden-important\">{$matches[2]}</div>{$html}</div>", $output); break; case 'blockspecials': $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; $product = $smarty->{$this->getTemplateVars}('special'); if (!is_array($product)) { break; } $lrw = $product['link_rewrite']; if (!$tool->params->checkValue('link-to-product-page', 'No') && (!Tools::getValue('id_product', false) || (Tools::getValue('id_product', false) != $product['id_product']))) { $lnk = $link->getProductLink($product['id_product'], $lrw, isset($product['category']) ? $product['category'] : null); } else { $lnk = false; } $image = $tool->getMainTemplate(array( 'id' => 'blockspecials'.$product['id_image'], 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('large-image')), 'thumb' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('thumb-image')), 'title' => $product['name'], 'group' => 'blockspecials', )); $image = '<div class="MagicToolboxContainer">'.$image.'</div>'; $type = ($this->isPrestaShop16x ? 'small': 'medium').$this->imageTypeSuffix; $pattern = preg_quote($_link->getImageLink($lrw, $product['id_image'], $type), '/'); $pattern = str_replace('\-'.$type, '\-[^"]*?', $pattern); $pattern = '<img[^>]*?src="[^"]*?'.$pattern.'"[^>]*>'; $pattern = '(<a[^>]*?href="[^"]*?"[^>]*>[^<]*)?'.$pattern.'([^<]*<\/a>)?'; $output = preg_replace('/'.$pattern.'/is', $image, $output); break; case 'blockspecials_home': $products = $smarty->{$this->getTemplateVars}('specials'); if (!is_array($products)) { break; } $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; foreach ($products as $product) { $lrw = $product['link_rewrite']; if (!$tool->params->checkValue('link-to-product-page', 'No') && (!Tools::getValue('id_product', false) || (Tools::getValue('id_product', false) != $product['id_product']))) { $lnk = $link->getProductLink($product['id_product'], $lrw, isset($product['category']) ? $product['category'] : null); } else { $lnk = false; } $image = $tool->getMainTemplate(array( 'id' => 'blockspecials'.$product['id_image'], 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('large-image')), 'thumb' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('thumb-image')), 'title' => $product['name'], 'group' => 'blockspecials_home', )); $image = '<div class="MagicToolboxContainer">'.$image.'</div>'; $type = 'home'.$this->imageTypeSuffix; $pattern = preg_quote($_link->getImageLink($lrw, $product['id_image'], $type), '/'); $pattern = str_replace('\-'.$type, '\-[^"]*?', $pattern); $pattern = '<img[^>]*?src="[^"]*?'.$pattern.'"[^>]*>'; $pattern = '(<a[^>]*?href="[^"]*?"[^>]*>[^<]*)?'.$pattern.'([^<]*<\/a>)?'; $output = preg_replace('/'.$pattern.'/is', $image, $output); } break; case 'blockviewed': $productIDs = $GLOBALS['magictoolbox']['magiczoomplus']['productsViewedIds']; if ($this->isPrestaShop155x) { $productIDs = array_reverse($productIDs); } $productIDs = array_slice($productIDs, 0, Configuration::get('PRODUCTS_VIEWED_NBR')); foreach ($productIDs as $id_product) { $productViewedObj = new Product((int)$id_product, false, (int)$cookie->id_lang); if (!Validate::isLoadedObject($productViewedObj) || !$productViewedObj->active) { continue; } $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; $images = $productViewedObj->getImages((int)$cookie->id_lang); foreach ($images as $image) { if ($image['cover']) { $productViewedObj->cover = $productViewedObj->id.'-'.$image['id_image']; $productViewedObj->legend = $image['legend']; break; } } if (!isset($productViewedObj->cover)) { $productViewedObj->cover = Language::getIsoById($cookie->id_lang).'-default'; $productViewedObj->legend = ''; } $lrw = $productViewedObj->link_rewrite; if (!$tool->params->checkValue('link-to-product-page', 'No') && (!Tools::getValue('id_product', false) || (Tools::getValue('id_product', false) != $id_product))) { $lnk = $link->getProductLink($id_product, $lrw, $productViewedObj->category); } else { $lnk = false; } $image = $tool->getMainTemplate(array( 'id' => 'blockviewed'.$id_product, 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $productViewedObj->cover, $tool->params->getValue('large-image')), 'thumb' => $_link->getImageLink($lrw, $productViewedObj->cover, $tool->params->getValue('thumb-image')), 'title' => $productViewedObj->name, 'group' => 'blockviewed', )); /* //DEPRECATED: $image_suffix = $tool->params->getValue('thumb-image') ? '-'.$tool->params->getValue('thumb-image') : ''; $file_path = _PS_PROD_IMG_DIR_.$productViewedObj->cover.$image_suffix.'.jpg'; if (!file_exists($file_path)) { $split_ids = explode('-', $productViewedObj->cover); $id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]); $folders = implode('/', str_split((string)$id_image)).'/'; $file_path = _PS_PROD_IMG_DIR_.$folders.$id_image.$image_suffix.'.jpg'; } $size = getimagesize($file_path); $image = '<div class="MagicToolboxContainer" style="float: left; width: '.$size[0].'px;">'.$image.'</div>'; /**/ $image = '<div class="MagicToolboxContainer">'.$image.'</div>'; $type = ($this->isPrestaShop16x ? 'small': 'medium').$this->imageTypeSuffix; $pattern = preg_quote($_link->getImageLink($lrw, $productViewedObj->cover, $type), '/'); $pattern = str_replace('\-'.$type, '\-[^"]*?', $pattern); $pattern = '<img[^>]*?src="[^"]*?'.$pattern.'"[^>]*>'; $pattern = '(<a[^>]*?href="[^"]*?"[^>]*>[^<]*)?'.$pattern.'([^<]*<\/a>)?'; $output = preg_replace('/'.$pattern.'/is', $image, $output); } break; case 'blockbestsellers': case 'blockbestsellers_home': case 'blocknewproducts': case 'blocknewproducts_home': if (in_array($currentTemplate, array('blockbestsellers', 'blockbestsellers_home'))) { //$products = $smarty->{$this->getTemplateVars}('best_sellers'); //to get with description etc. //$products = ProductSale::getBestSales((int)$cookie->id_lang, 0, version_compare(_PS_VERSION_, '1.5.1.0', '>=') ? 5 : 4); //NOTE: blockbestsellers module uses a 'getBestSalesLight' function (the result may be different from 'getBestSales') // description we get a little further (with 'getProductDescription' function) $pCount = $this->isPrestaShop16x ? 8 : (version_compare(_PS_VERSION_, '1.5.1.0', '>=') ? 5 : 4); $products = ProductSale::getBestSalesLight((int)$cookie->id_lang, 0, $pCount); } else { $products = $smarty->{$this->getTemplateVars}('new_products'); } if (!is_array($products)) { break; } $pCount = count($products); if ($pCount) { $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; for ($i = 0; /*$i < 2 &&*/ $i < $pCount; $i++) { $lrw = $products[$i]['link_rewrite']; if (!$tool->params->checkValue('link-to-product-page', 'No') && (!Tools::getValue('id_product', false) || (Tools::getValue('id_product', false) != $products[$i]['id_product']))) { $lnk = $link->getProductLink($products[$i]['id_product'], $lrw, isset($products[$i]['category']) ? $products[$i]['category'] : null); } else { $lnk = false; } $image = $tool->getMainTemplate(array( 'id' => $currentTemplate.$products[$i]['id_image'], 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $products[$i]['id_image'], $tool->params->getValue('large-image')), 'thumb' => $_link->getImageLink($lrw, $products[$i]['id_image'], $tool->params->getValue('thumb-image')), 'title' => $products[$i]['name'], 'group' => $currentTemplate, )); $image = '<div class="MagicToolboxContainer">'.$image.'</div>'; if (in_array($currentTemplate, array('blockbestsellers_home', 'blocknewproducts_home'))) { $type = 'home'.$this->imageTypeSuffix; } elseif ($this->isPrestaShop15x && $currentTemplate == 'blockbestsellers' || $this->isPrestaShop16x) { $type = 'small'.$this->imageTypeSuffix; } else { $type = 'medium'.$this->imageTypeSuffix; } $pattern = preg_quote($_link->getImageLink($lrw, $products[$i]['id_image'], $type), '/'); $pattern = str_replace('\-'.$type, '\-[^"]*?', $pattern); $pattern = '<img[^>]*?src="[^"]*?'.$pattern.'"[^>]*>'; $pattern = '(?:<a[^>]*>[^<]*)?(?:<span class="number">.*?<\/span>[^<]*)?'.$pattern.'(?:[^<]*<\/a>)?'; $output = preg_replace('/'.$pattern.'/is', $image, $output); } } break; } return self::prepareOutput($output); } public function getAllSpecial($id_lang, $beginning = false, $ending = false) { $currentDate = date('Y-m-d'); $result = Db::getInstance()->ExecuteS(' SELECT p.*, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, p.`ean13`, i.`id_image`, il.`legend`, t.`rate` FROM `'._DB_PREFIX_.'product` p LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.') LEFT JOIN `'._DB_PREFIX_.'tax` t ON t.`id_tax` = p.`id_tax` WHERE (`reduction_price` > 0 OR `reduction_percent` > 0) '.((!$beginning && !$ending) ? 'AND (`reduction_from` = `reduction_to` OR (`reduction_from` <= \''.$currentDate.'\' AND `reduction_to` >= \''.$currentDate.'\'))' : ($beginning ? 'AND `reduction_from` <= \''.$beginning.'\'' : '').($ending ? 'AND `reduction_to` >= \''.$ending.'\'' : '')).' AND p.`active` = 1 ORDER BY RAND()'); if (!$result) { return false; } $rows = array(); foreach ($result as $row) { $rows[] = Product::getProductProperties($id_lang, $row); } return $rows; } /* for Prestashop ver 1.1 */ public function getImageLink($name, $ids, $type = null) { return _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').'.jpg'; } public function getProductDescription($id_product, $id_lang) { $sql = 'SELECT `description` FROM `'._DB_PREFIX_.'product_lang` WHERE `id_product` = '.(int)($id_product).' AND `id_lang` = '.(int)($id_lang); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql); return isset($result[0]['description'])? $result[0]['description'] : ''; } public function fillDB() { $sql = 'INSERT INTO `'._DB_PREFIX_.'magiczoomplus_settings` (`block`, `name`, `value`, `default_value`, `enabled`, `default_enabled`) VALUES (\'default\', \'include-headers-on-all-pages\', \'No\', \'No\', 1, 1), (\'default\', \'thumb-image\', \'large\', \'large\', 1, 1), (\'default\', \'selector-image\', \'small\', \'small\', 1, 1), (\'default\', \'large-image\', \'thickbox\', \'thickbox\', 1, 1), (\'default\', \'zoomWidth\', \'auto\', \'auto\', 1, 1), (\'default\', \'zoomHeight\', \'auto\', \'auto\', 1, 1), (\'default\', \'zoomPosition\', \'right\', \'right\', 1, 1), (\'default\', \'zoomDistance\', \'15\', \'15\', 1, 1), (\'default\', \'lazyZoom\', \'No\', \'No\', 1, 1), (\'default\', \'rightClick\', \'No\', \'No\', 1, 1), (\'default\', \'link-to-product-page\', \'Yes\', \'Yes\', 1, 1), (\'default\', \'show-message\', \'No\', \'No\', 1, 1), (\'default\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 1, 1), (\'default\', \'zoomMode\', \'zoom\', \'zoom\', 1, 1), (\'default\', \'zoomOn\', \'hover\', \'hover\', 1, 1), (\'default\', \'upscale\', \'Yes\', \'Yes\', 1, 1), (\'default\', \'smoothing\', \'Yes\', \'Yes\', 1, 1), (\'default\', \'variableZoom\', \'No\', \'No\', 1, 1), (\'default\', \'zoomCaption\', \'off\', \'off\', 1, 1), (\'default\', \'expand\', \'window\', \'window\', 1, 1), (\'default\', \'expandZoomMode\', \'zoom\', \'zoom\', 1, 1), (\'default\', \'expandZoomOn\', \'click\', \'click\', 1, 1), (\'default\', \'expandCaption\', \'Yes\', \'Yes\', 1, 1), (\'default\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 1, 1), (\'default\', \'cssClass\', \'blurred\', \'blurred\', 1, 1), (\'default\', \'hint\', \'once\', \'once\', 1, 1), (\'default\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 1, 1), (\'default\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 1, 1), (\'default\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 1, 1), (\'default\', \'textBtnClose\', \'Close\', \'Close\', 1, 1), (\'default\', \'textBtnNext\', \'Next\', \'Next\', 1, 1), (\'default\', \'textBtnPrev\', \'Previous\', \'Previous\', 1, 1), (\'default\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 1, 1), (\'default\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 1, 1), (\'default\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 1, 1), (\'default\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 1, 1), (\'product\', \'template\', \'original\', \'original\', 0, 0), (\'product\', \'magicscroll\', \'No\', \'No\', 0, 0), (\'product\', \'thumb-image\', \'large\', \'large\', 0, 0), (\'product\', \'selector-image\', \'small\', \'small\', 0, 0), (\'product\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'product\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'product\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'product\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'product\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'product\', \'selectorTrigger\', \'click\', \'click\', 0, 0), (\'product\', \'transitionEffect\', \'Yes\', \'Yes\', 0, 0), (\'product\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'product\', \'enable-effect\', \'Yes\', \'Yes\', 1, 1), (\'product\', \'rightClick\', \'No\', \'No\', 0, 0), (\'product\', \'show-message\', \'No\', \'No\', 0, 0), (\'product\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'product\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'product\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'product\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'product\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'product\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'product\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'product\', \'expand\', \'window\', \'window\', 0, 0), (\'product\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'product\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'product\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'product\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'product\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'product\', \'hint\', \'once\', \'once\', 0, 0), (\'product\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'product\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'product\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'product\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'product\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'product\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'product\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'product\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'product\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'product\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'product\', \'width\', \'auto\', \'auto\', 0, 0), (\'product\', \'height\', \'auto\', \'auto\', 0, 0), (\'product\', \'mode\', \'scroll\', \'scroll\', 0, 0), (\'product\', \'items\', \'fit\', \'fit\', 0, 0), (\'product\', \'speed\', \'600\', \'600\', 0, 0), (\'product\', \'autoplay\', \'0\', \'0\', 0, 0), (\'product\', \'loop\', \'infinite\', \'infinite\', 0, 0), (\'product\', \'step\', \'auto\', \'auto\', 0, 0), (\'product\', \'arrows\', \'inside\', \'inside\', 0, 0), (\'product\', \'pagination\', \'No\', \'No\', 0, 0), (\'product\', \'easing\', \'cubic-bezier(.8, 0, .5, 1)\', \'cubic-bezier(.8, 0, .5, 1)\', 0, 0), (\'product\', \'scrollOnWheel\', \'auto\', \'auto\', 0, 0), (\'product\', \'lazy-load\', \'No\', \'No\', 0, 0), (\'product\', \'scroll-extra-styles\', \'\', \'\', 0, 0), (\'product\', \'show-image-title\', \'No\', \'No\', 0, 0), (\'category\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'category\', \'selector-image\', \'small\', \'small\', 0, 0), (\'category\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'category\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'category\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'category\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'category\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'category\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'category\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'category\', \'rightClick\', \'No\', \'No\', 0, 0), (\'category\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'category\', \'show-message\', \'No\', \'No\', 0, 0), (\'category\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'category\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'category\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'category\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'category\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'category\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'category\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'category\', \'expand\', \'window\', \'window\', 0, 0), (\'category\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'category\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'category\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'category\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'category\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'category\', \'hint\', \'once\', \'once\', 0, 0), (\'category\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'category\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'category\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'category\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'category\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'category\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'category\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'category\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'category\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'category\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'manufacturer\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'manufacturer\', \'selector-image\', \'small\', \'small\', 0, 0), (\'manufacturer\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'manufacturer\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'manufacturer\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'manufacturer\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'manufacturer\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'manufacturer\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'manufacturer\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'manufacturer\', \'rightClick\', \'No\', \'No\', 0, 0), (\'manufacturer\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'manufacturer\', \'show-message\', \'No\', \'No\', 0, 0), (\'manufacturer\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'manufacturer\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'manufacturer\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'manufacturer\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'manufacturer\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'manufacturer\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'manufacturer\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'manufacturer\', \'expand\', \'window\', \'window\', 0, 0), (\'manufacturer\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'manufacturer\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'manufacturer\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'manufacturer\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'manufacturer\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'manufacturer\', \'hint\', \'once\', \'once\', 0, 0), (\'manufacturer\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'manufacturer\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'manufacturer\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'manufacturer\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'manufacturer\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'manufacturer\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'manufacturer\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'manufacturer\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'manufacturer\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'manufacturer\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'newproductpage\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'newproductpage\', \'selector-image\', \'small\', \'small\', 0, 0), (\'newproductpage\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'newproductpage\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'newproductpage\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'newproductpage\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'newproductpage\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'newproductpage\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'newproductpage\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'newproductpage\', \'rightClick\', \'No\', \'No\', 0, 0), (\'newproductpage\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'newproductpage\', \'show-message\', \'No\', \'No\', 0, 0), (\'newproductpage\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'newproductpage\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'newproductpage\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'newproductpage\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'newproductpage\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'newproductpage\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'newproductpage\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'newproductpage\', \'expand\', \'window\', \'window\', 0, 0), (\'newproductpage\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'newproductpage\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'newproductpage\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'newproductpage\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'newproductpage\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'newproductpage\', \'hint\', \'once\', \'once\', 0, 0), (\'newproductpage\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'newproductpage\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'newproductpage\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'newproductpage\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'newproductpage\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'newproductpage\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'newproductpage\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'newproductpage\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'newproductpage\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'newproductpage\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'blocknewproducts\', \'thumb-image\', \'medium\', \'medium\', 1, 1), (\'blocknewproducts\', \'selector-image\', \'small\', \'small\', 0, 0), (\'blocknewproducts\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'blocknewproducts\', \'zoomWidth\', \'150\', \'150\', 1, 1), (\'blocknewproducts\', \'zoomHeight\', \'150\', \'150\', 1, 1), (\'blocknewproducts\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'blocknewproducts\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'blocknewproducts\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'blocknewproducts\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'blocknewproducts\', \'rightClick\', \'No\', \'No\', 0, 0), (\'blocknewproducts\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts\', \'show-message\', \'No\', \'No\', 0, 0), (\'blocknewproducts\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'blocknewproducts\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blocknewproducts\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'blocknewproducts\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'blocknewproducts\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'blocknewproducts\', \'expand\', \'window\', \'window\', 0, 0), (\'blocknewproducts\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blocknewproducts\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'blocknewproducts\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'blocknewproducts\', \'hint\', \'once\', \'once\', 0, 0), (\'blocknewproducts\', \'textHoverZoomHint\', \'\', \'\', 1, 1), (\'blocknewproducts\', \'textClickZoomHint\', \'\', \'\', 1, 1), (\'blocknewproducts\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'blocknewproducts\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'blocknewproducts\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'blocknewproducts\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'blocknewproducts\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'blocknewproducts\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'blocknewproducts\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'blocknewproducts\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'blocknewproducts_home\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'blocknewproducts_home\', \'selector-image\', \'small\', \'small\', 0, 0), (\'blocknewproducts_home\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'blocknewproducts_home\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'blocknewproducts_home\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'blocknewproducts_home\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'blocknewproducts_home\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'blocknewproducts_home\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'blocknewproducts_home\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'blocknewproducts_home\', \'rightClick\', \'No\', \'No\', 0, 0), (\'blocknewproducts_home\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts_home\', \'show-message\', \'No\', \'No\', 0, 0), (\'blocknewproducts_home\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'blocknewproducts_home\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blocknewproducts_home\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'blocknewproducts_home\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts_home\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts_home\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'blocknewproducts_home\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'blocknewproducts_home\', \'expand\', \'window\', \'window\', 0, 0), (\'blocknewproducts_home\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blocknewproducts_home\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'blocknewproducts_home\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts_home\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'blocknewproducts_home\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'blocknewproducts_home\', \'hint\', \'once\', \'once\', 0, 0), (\'blocknewproducts_home\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'blocknewproducts_home\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'blocknewproducts_home\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'blocknewproducts_home\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'blocknewproducts_home\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'blocknewproducts_home\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'blocknewproducts_home\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'blocknewproducts_home\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'blocknewproducts_home\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'blocknewproducts_home\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'bestsellerspage\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'bestsellerspage\', \'selector-image\', \'small\', \'small\', 0, 0), (\'bestsellerspage\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'bestsellerspage\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'bestsellerspage\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'bestsellerspage\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'bestsellerspage\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'bestsellerspage\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'bestsellerspage\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'bestsellerspage\', \'rightClick\', \'No\', \'No\', 0, 0), (\'bestsellerspage\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'bestsellerspage\', \'show-message\', \'No\', \'No\', 0, 0), (\'bestsellerspage\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'bestsellerspage\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'bestsellerspage\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'bestsellerspage\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'bestsellerspage\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'bestsellerspage\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'bestsellerspage\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'bestsellerspage\', \'expand\', \'window\', \'window\', 0, 0), (\'bestsellerspage\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'bestsellerspage\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'bestsellerspage\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'bestsellerspage\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'bestsellerspage\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'bestsellerspage\', \'hint\', \'once\', \'once\', 0, 0), (\'bestsellerspage\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'bestsellerspage\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'bestsellerspage\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'bestsellerspage\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'bestsellerspage\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'bestsellerspage\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'bestsellerspage\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'bestsellerspage\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'bestsellerspage\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'bestsellerspage\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'blockbestsellers\', \'thumb-image\', \'medium\', \'medium\', 1, 1), (\'blockbestsellers\', \'selector-image\', \'small\', \'small\', 0, 0), (\'blockbestsellers\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'blockbestsellers\', \'zoomWidth\', \'150\', \'150\', 1, 1), (\'blockbestsellers\', \'zoomHeight\', \'150\', \'150\', 1, 1), (\'blockbestsellers\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'blockbestsellers\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'blockbestsellers\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'blockbestsellers\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'blockbestsellers\', \'rightClick\', \'No\', \'No\', 0, 0), (\'blockbestsellers\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers\', \'show-message\', \'No\', \'No\', 0, 0), (\'blockbestsellers\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'blockbestsellers\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockbestsellers\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'blockbestsellers\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'blockbestsellers\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'blockbestsellers\', \'expand\', \'window\', \'window\', 0, 0), (\'blockbestsellers\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockbestsellers\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'blockbestsellers\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'blockbestsellers\', \'hint\', \'once\', \'once\', 0, 0), (\'blockbestsellers\', \'textHoverZoomHint\', \'\', \'\', 1, 1), (\'blockbestsellers\', \'textClickZoomHint\', \'\', \'\', 1, 1), (\'blockbestsellers\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'blockbestsellers\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'blockbestsellers\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'blockbestsellers\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'blockbestsellers\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'blockbestsellers\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'blockbestsellers\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'blockbestsellers\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'blockbestsellers_home\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'blockbestsellers_home\', \'selector-image\', \'small\', \'small\', 0, 0), (\'blockbestsellers_home\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'blockbestsellers_home\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'blockbestsellers_home\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'blockbestsellers_home\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'blockbestsellers_home\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'blockbestsellers_home\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'blockbestsellers_home\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'blockbestsellers_home\', \'rightClick\', \'No\', \'No\', 0, 0), (\'blockbestsellers_home\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers_home\', \'show-message\', \'No\', \'No\', 0, 0), (\'blockbestsellers_home\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'blockbestsellers_home\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockbestsellers_home\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'blockbestsellers_home\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers_home\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers_home\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'blockbestsellers_home\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'blockbestsellers_home\', \'expand\', \'window\', \'window\', 0, 0), (\'blockbestsellers_home\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockbestsellers_home\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'blockbestsellers_home\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers_home\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'blockbestsellers_home\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'blockbestsellers_home\', \'hint\', \'once\', \'once\', 0, 0), (\'blockbestsellers_home\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'blockbestsellers_home\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'blockbestsellers_home\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'blockbestsellers_home\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'blockbestsellers_home\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'blockbestsellers_home\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'blockbestsellers_home\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'blockbestsellers_home\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'blockbestsellers_home\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'blockbestsellers_home\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'specialspage\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'specialspage\', \'selector-image\', \'small\', \'small\', 0, 0), (\'specialspage\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'specialspage\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'specialspage\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'specialspage\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'specialspage\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'specialspage\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'specialspage\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'specialspage\', \'rightClick\', \'No\', \'No\', 0, 0), (\'specialspage\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'specialspage\', \'show-message\', \'No\', \'No\', 0, 0), (\'specialspage\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'specialspage\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'specialspage\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'specialspage\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'specialspage\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'specialspage\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'specialspage\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'specialspage\', \'expand\', \'window\', \'window\', 0, 0), (\'specialspage\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'specialspage\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'specialspage\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'specialspage\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'specialspage\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'specialspage\', \'hint\', \'once\', \'once\', 0, 0), (\'specialspage\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'specialspage\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'specialspage\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'specialspage\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'specialspage\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'specialspage\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'specialspage\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'specialspage\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'specialspage\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'specialspage\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'blockspecials\', \'thumb-image\', \'medium\', \'medium\', 1, 1), (\'blockspecials\', \'selector-image\', \'small\', \'small\', 0, 0), (\'blockspecials\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'blockspecials\', \'zoomWidth\', \'150\', \'150\', 1, 1), (\'blockspecials\', \'zoomHeight\', \'150\', \'150\', 1, 1), (\'blockspecials\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'blockspecials\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'blockspecials\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'blockspecials\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'blockspecials\', \'rightClick\', \'No\', \'No\', 0, 0), (\'blockspecials\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials\', \'show-message\', \'No\', \'No\', 0, 0), (\'blockspecials\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'blockspecials\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockspecials\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'blockspecials\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'blockspecials\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'blockspecials\', \'expand\', \'window\', \'window\', 0, 0), (\'blockspecials\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockspecials\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'blockspecials\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'blockspecials\', \'hint\', \'once\', \'once\', 0, 0), (\'blockspecials\', \'textHoverZoomHint\', \'\', \'\', 1, 1), (\'blockspecials\', \'textClickZoomHint\', \'\', \'\', 1, 1), (\'blockspecials\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'blockspecials\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'blockspecials\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'blockspecials\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'blockspecials\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'blockspecials\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'blockspecials\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'blockspecials\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'blockspecials_home\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'blockspecials_home\', \'selector-image\', \'small\', \'small\', 0, 0), (\'blockspecials_home\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'blockspecials_home\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'blockspecials_home\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'blockspecials_home\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'blockspecials_home\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'blockspecials_home\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'blockspecials_home\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'blockspecials_home\', \'rightClick\', \'No\', \'No\', 0, 0), (\'blockspecials_home\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials_home\', \'show-message\', \'No\', \'No\', 0, 0), (\'blockspecials_home\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'blockspecials_home\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockspecials_home\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'blockspecials_home\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials_home\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials_home\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'blockspecials_home\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'blockspecials_home\', \'expand\', \'window\', \'window\', 0, 0), (\'blockspecials_home\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockspecials_home\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'blockspecials_home\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials_home\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'blockspecials_home\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'blockspecials_home\', \'hint\', \'once\', \'once\', 0, 0), (\'blockspecials_home\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'blockspecials_home\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'blockspecials_home\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'blockspecials_home\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'blockspecials_home\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'blockspecials_home\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'blockspecials_home\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'blockspecials_home\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'blockspecials_home\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'blockspecials_home\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'blockviewed\', \'thumb-image\', \'medium\', \'medium\', 1, 1), (\'blockviewed\', \'selector-image\', \'small\', \'small\', 0, 0), (\'blockviewed\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'blockviewed\', \'zoomWidth\', \'150\', \'150\', 1, 1), (\'blockviewed\', \'zoomHeight\', \'150\', \'150\', 1, 1), (\'blockviewed\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'blockviewed\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'blockviewed\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'blockviewed\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'blockviewed\', \'rightClick\', \'No\', \'No\', 0, 0), (\'blockviewed\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'blockviewed\', \'show-message\', \'No\', \'No\', 0, 0), (\'blockviewed\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'blockviewed\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockviewed\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'blockviewed\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'blockviewed\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'blockviewed\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'blockviewed\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'blockviewed\', \'expand\', \'window\', \'window\', 0, 0), (\'blockviewed\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'blockviewed\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'blockviewed\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'blockviewed\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'blockviewed\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'blockviewed\', \'hint\', \'once\', \'once\', 0, 0), (\'blockviewed\', \'textHoverZoomHint\', \'\', \'\', 1, 1), (\'blockviewed\', \'textClickZoomHint\', \'\', \'\', 1, 1), (\'blockviewed\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'blockviewed\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'blockviewed\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'blockviewed\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'blockviewed\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'blockviewed\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'blockviewed\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'blockviewed\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'homefeatured\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'homefeatured\', \'selector-image\', \'small\', \'small\', 0, 0), (\'homefeatured\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'homefeatured\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'homefeatured\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'homefeatured\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'homefeatured\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'homefeatured\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'homefeatured\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'homefeatured\', \'rightClick\', \'No\', \'No\', 0, 0), (\'homefeatured\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'homefeatured\', \'show-message\', \'No\', \'No\', 0, 0), (\'homefeatured\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'homefeatured\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'homefeatured\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'homefeatured\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'homefeatured\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'homefeatured\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'homefeatured\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'homefeatured\', \'expand\', \'window\', \'window\', 0, 0), (\'homefeatured\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'homefeatured\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'homefeatured\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'homefeatured\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'homefeatured\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'homefeatured\', \'hint\', \'once\', \'once\', 0, 0), (\'homefeatured\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'homefeatured\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'homefeatured\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'homefeatured\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'homefeatured\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'homefeatured\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'homefeatured\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'homefeatured\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'homefeatured\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'homefeatured\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0), (\'search\', \'thumb-image\', \'home\', \'home\', 1, 1), (\'search\', \'selector-image\', \'small\', \'small\', 0, 0), (\'search\', \'large-image\', \'thickbox\', \'thickbox\', 0, 0), (\'search\', \'zoomWidth\', \'auto\', \'auto\', 0, 0), (\'search\', \'zoomHeight\', \'auto\', \'auto\', 0, 0), (\'search\', \'zoomPosition\', \'right\', \'right\', 0, 0), (\'search\', \'zoomDistance\', \'15\', \'15\', 0, 0), (\'search\', \'lazyZoom\', \'No\', \'No\', 0, 0), (\'search\', \'enable-effect\', \'No\', \'No\', 1, 1), (\'search\', \'rightClick\', \'No\', \'No\', 0, 0), (\'search\', \'link-to-product-page\', \'Yes\', \'Yes\', 0, 0), (\'search\', \'show-message\', \'No\', \'No\', 0, 0), (\'search\', \'message\', \'Move your mouse over image or click to enlarge\', \'Move your mouse over image or click to enlarge\', 0, 0), (\'search\', \'zoomMode\', \'zoom\', \'zoom\', 0, 0), (\'search\', \'zoomOn\', \'hover\', \'hover\', 0, 0), (\'search\', \'upscale\', \'Yes\', \'Yes\', 0, 0), (\'search\', \'smoothing\', \'Yes\', \'Yes\', 0, 0), (\'search\', \'variableZoom\', \'No\', \'No\', 0, 0), (\'search\', \'zoomCaption\', \'off\', \'off\', 0, 0), (\'search\', \'expand\', \'window\', \'window\', 0, 0), (\'search\', \'expandZoomMode\', \'zoom\', \'zoom\', 0, 0), (\'search\', \'expandZoomOn\', \'click\', \'click\', 0, 0), (\'search\', \'expandCaption\', \'Yes\', \'Yes\', 0, 0), (\'search\', \'closeOnClickOutside\', \'Yes\', \'Yes\', 0, 0), (\'search\', \'cssClass\', \'blurred\', \'blurred\', 0, 0), (\'search\', \'hint\', \'once\', \'once\', 0, 0), (\'search\', \'textHoverZoomHint\', \'Hover to zoom\', \'Hover to zoom\', 0, 0), (\'search\', \'textClickZoomHint\', \'Click to zoom\', \'Click to zoom\', 0, 0), (\'search\', \'textExpandHint\', \'Click to expand\', \'Click to expand\', 0, 0), (\'search\', \'textBtnClose\', \'Close\', \'Close\', 0, 0), (\'search\', \'textBtnNext\', \'Next\', \'Next\', 0, 0), (\'search\', \'textBtnPrev\', \'Previous\', \'Previous\', 0, 0), (\'search\', \'zoomModeForMobile\', \'zoom\', \'zoom\', 0, 0), (\'search\', \'textHoverZoomHintForMobile\', \'Touch to zoom\', \'Touch to zoom\', 0, 0), (\'search\', \'textClickZoomHintForMobile\', \'Double tap to zoom\', \'Double tap to zoom\', 0, 0), (\'search\', \'textExpandHintForMobile\', \'Tap to expand\', \'Tap to expand\', 0, 0)'; if (!$this->isPrestaShop16x) { $sql = preg_replace('/\r\n\s*..(?:blockbestsellers_home|blocknewproducts_home|blockspecials_home)\b[^\r]*+/i', '', $sql); $sql = rtrim($sql, ','); } return Db::getInstance()->Execute($sql); } public function getBlocks() { $blocks = array( 'default' => 'Default settings', 'product' => 'Product page', 'category' => 'Category page', 'manufacturer' => 'Manufacturers page', 'newproductpage' => 'New products page', 'blocknewproducts' => 'New products sidebar', 'blocknewproducts_home' => 'New products block', 'bestsellerspage' => 'Bestsellers page', 'blockbestsellers' => 'Bestsellers sidebar', 'blockbestsellers_home' => 'Bestsellers block', 'specialspage' => 'Specials page', 'blockspecials' => 'Specials sidebar', 'blockspecials_home' => 'Specials block', 'blockviewed' => 'Viewed sidebar', 'homefeatured' => 'Featured block', 'search' => 'Search page' ); if (!$this->isPrestaShop16x) { unset($blocks['blockbestsellers_home'], $blocks['blocknewproducts_home'], $blocks['blockspecials_home']); } return $blocks; } public function getMessages() { return array( 'default' => array( 'textHoverZoomHint' => array( 'title' => 'Default settings zoom hint text (on hover)', 'translate' => $this->l('Default settings zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Default settings zoom hint text (on click)', 'translate' => $this->l('Default settings zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Default settings zoom hint text for mobile (on hover)', 'translate' => $this->l('Default settings zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Default settings zoom hint text for mobile (on click)', 'translate' => $this->l('Default settings zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Default settings expand hint text', 'translate' => $this->l('Default settings expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Default settings expand hint text for mobile', 'translate' => $this->l('Default settings expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Default settings close button text', 'translate' => $this->l('Default settings close button text') ), 'textBtnNext' => array( 'title' => 'Default settings next button text', 'translate' => $this->l('Default settings next button text') ), 'textBtnPrev' => array( 'title' => 'Default settings prev button text', 'translate' => $this->l('Default settings prev button text') ), 'message' => array( 'title' => 'Default settings message (under Magic Zoom Plus)', 'translate' => $this->l('Default settings message (under Magic Zoom Plus)') ) ), 'product' => array( 'textHoverZoomHint' => array( 'title' => 'Product page zoom hint text (on hover)', 'translate' => $this->l('Product page zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Product page zoom hint text (on click)', 'translate' => $this->l('Product page zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Product page zoom hint text for mobile (on hover)', 'translate' => $this->l('Product page zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Product page zoom hint text for mobile (on click)', 'translate' => $this->l('Product page zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Product page expand hint text', 'translate' => $this->l('Product page expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Product page expand hint text for mobile', 'translate' => $this->l('Product page expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Product page close button text', 'translate' => $this->l('Product page close button text') ), 'textBtnNext' => array( 'title' => 'Product page next button text', 'translate' => $this->l('Product page next button text') ), 'textBtnPrev' => array( 'title' => 'Product page prev button text', 'translate' => $this->l('Product page prev button text') ), 'message' => array( 'title' => 'Product page message (under Magic Zoom Plus)', 'translate' => $this->l('Product page message (under Magic Zoom Plus)') ) ), 'category' => array( 'textHoverZoomHint' => array( 'title' => 'Category page zoom hint text (on hover)', 'translate' => $this->l('Category page zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Category page zoom hint text (on click)', 'translate' => $this->l('Category page zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Category page zoom hint text for mobile (on hover)', 'translate' => $this->l('Category page zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Category page zoom hint text for mobile (on click)', 'translate' => $this->l('Category page zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Category page expand hint text', 'translate' => $this->l('Category page expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Category page expand hint text for mobile', 'translate' => $this->l('Category page expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Category page close button text', 'translate' => $this->l('Category page close button text') ), 'textBtnNext' => array( 'title' => 'Category page next button text', 'translate' => $this->l('Category page next button text') ), 'textBtnPrev' => array( 'title' => 'Category page prev button text', 'translate' => $this->l('Category page prev button text') ), 'message' => array( 'title' => 'Category page message (under Magic Zoom Plus)', 'translate' => $this->l('Category page message (under Magic Zoom Plus)') ) ), 'manufacturer' => array( 'textHoverZoomHint' => array( 'title' => 'Manufacturers page zoom hint text (on hover)', 'translate' => $this->l('Manufacturers page zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Manufacturers page zoom hint text (on click)', 'translate' => $this->l('Manufacturers page zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Manufacturers page zoom hint text for mobile (on hover)', 'translate' => $this->l('Manufacturers page zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Manufacturers page zoom hint text for mobile (on click)', 'translate' => $this->l('Manufacturers page zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Manufacturers page expand hint text', 'translate' => $this->l('Manufacturers page expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Manufacturers page expand hint text for mobile', 'translate' => $this->l('Manufacturers page expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Manufacturers page close button text', 'translate' => $this->l('Manufacturers page close button text') ), 'textBtnNext' => array( 'title' => 'Manufacturers page next button text', 'translate' => $this->l('Manufacturers page next button text') ), 'textBtnPrev' => array( 'title' => 'Manufacturers page prev button text', 'translate' => $this->l('Manufacturers page prev button text') ), 'message' => array( 'title' => 'Manufacturers page message (under Magic Zoom Plus)', 'translate' => $this->l('Manufacturers page message (under Magic Zoom Plus)') ) ), 'newproductpage' => array( 'textHoverZoomHint' => array( 'title' => 'New products page zoom hint text (on hover)', 'translate' => $this->l('New products page zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'New products page zoom hint text (on click)', 'translate' => $this->l('New products page zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'New products page zoom hint text for mobile (on hover)', 'translate' => $this->l('New products page zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'New products page zoom hint text for mobile (on click)', 'translate' => $this->l('New products page zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'New products page expand hint text', 'translate' => $this->l('New products page expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'New products page expand hint text for mobile', 'translate' => $this->l('New products page expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'New products page close button text', 'translate' => $this->l('New products page close button text') ), 'textBtnNext' => array( 'title' => 'New products page next button text', 'translate' => $this->l('New products page next button text') ), 'textBtnPrev' => array( 'title' => 'New products page prev button text', 'translate' => $this->l('New products page prev button text') ), 'message' => array( 'title' => 'New products page message (under Magic Zoom Plus)', 'translate' => $this->l('New products page message (under Magic Zoom Plus)') ) ), 'blocknewproducts' => array( 'textHoverZoomHint' => array( 'title' => 'New products sidebar zoom hint text (on hover)', 'translate' => $this->l('New products sidebar zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'New products sidebar zoom hint text (on click)', 'translate' => $this->l('New products sidebar zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'New products sidebar zoom hint text for mobile (on hover)', 'translate' => $this->l('New products sidebar zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'New products sidebar zoom hint text for mobile (on click)', 'translate' => $this->l('New products sidebar zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'New products sidebar expand hint text', 'translate' => $this->l('New products sidebar expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'New products sidebar expand hint text for mobile', 'translate' => $this->l('New products sidebar expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'New products sidebar close button text', 'translate' => $this->l('New products sidebar close button text') ), 'textBtnNext' => array( 'title' => 'New products sidebar next button text', 'translate' => $this->l('New products sidebar next button text') ), 'textBtnPrev' => array( 'title' => 'New products sidebar prev button text', 'translate' => $this->l('New products sidebar prev button text') ), 'message' => array( 'title' => 'New products sidebar message (under Magic Zoom Plus)', 'translate' => $this->l('New products sidebar message (under Magic Zoom Plus)') ) ), 'blocknewproducts_home' => array( 'textHoverZoomHint' => array( 'title' => 'New products block zoom hint text (on hover)', 'translate' => $this->l('New products block zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'New products block zoom hint text (on click)', 'translate' => $this->l('New products block zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'New products block zoom hint text for mobile (on hover)', 'translate' => $this->l('New products block zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'New products block zoom hint text for mobile (on click)', 'translate' => $this->l('New products block zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'New products block expand hint text', 'translate' => $this->l('New products block expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'New products block expand hint text for mobile', 'translate' => $this->l('New products block expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'New products block close button text', 'translate' => $this->l('New products block close button text') ), 'textBtnNext' => array( 'title' => 'New products block next button text', 'translate' => $this->l('New products block next button text') ), 'textBtnPrev' => array( 'title' => 'New products block prev button text', 'translate' => $this->l('New products block prev button text') ), 'message' => array( 'title' => 'New products block message (under Magic Zoom Plus)', 'translate' => $this->l('New products block message (under Magic Zoom Plus)') ) ), 'bestsellerspage' => array( 'textHoverZoomHint' => array( 'title' => 'Bestsellers page zoom hint text (on hover)', 'translate' => $this->l('Bestsellers page zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Bestsellers page zoom hint text (on click)', 'translate' => $this->l('Bestsellers page zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Bestsellers page zoom hint text for mobile (on hover)', 'translate' => $this->l('Bestsellers page zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Bestsellers page zoom hint text for mobile (on click)', 'translate' => $this->l('Bestsellers page zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Bestsellers page expand hint text', 'translate' => $this->l('Bestsellers page expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Bestsellers page expand hint text for mobile', 'translate' => $this->l('Bestsellers page expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Bestsellers page close button text', 'translate' => $this->l('Bestsellers page close button text') ), 'textBtnNext' => array( 'title' => 'Bestsellers page next button text', 'translate' => $this->l('Bestsellers page next button text') ), 'textBtnPrev' => array( 'title' => 'Bestsellers page prev button text', 'translate' => $this->l('Bestsellers page prev button text') ), 'message' => array( 'title' => 'Bestsellers page message (under Magic Zoom Plus)', 'translate' => $this->l('Bestsellers page message (under Magic Zoom Plus)') ) ), 'blockbestsellers' => array( 'textHoverZoomHint' => array( 'title' => 'Bestsellers sidebar zoom hint text (on hover)', 'translate' => $this->l('Bestsellers sidebar zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Bestsellers sidebar zoom hint text (on click)', 'translate' => $this->l('Bestsellers sidebar zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Bestsellers sidebar zoom hint text for mobile (on hover)', 'translate' => $this->l('Bestsellers sidebar zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Bestsellers sidebar zoom hint text for mobile (on click)', 'translate' => $this->l('Bestsellers sidebar zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Bestsellers sidebar expand hint text', 'translate' => $this->l('Bestsellers sidebar expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Bestsellers sidebar expand hint text for mobile', 'translate' => $this->l('Bestsellers sidebar expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Bestsellers sidebar close button text', 'translate' => $this->l('Bestsellers sidebar close button text') ), 'textBtnNext' => array( 'title' => 'Bestsellers sidebar next button text', 'translate' => $this->l('Bestsellers sidebar next button text') ), 'textBtnPrev' => array( 'title' => 'Bestsellers sidebar prev button text', 'translate' => $this->l('Bestsellers sidebar prev button text') ), 'message' => array( 'title' => 'Bestsellers sidebar message (under Magic Zoom Plus)', 'translate' => $this->l('Bestsellers sidebar message (under Magic Zoom Plus)') ) ), 'blockbestsellers_home' => array( 'textHoverZoomHint' => array( 'title' => 'Bestsellers block zoom hint text (on hover)', 'translate' => $this->l('Bestsellers block zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Bestsellers block zoom hint text (on click)', 'translate' => $this->l('Bestsellers block zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Bestsellers block zoom hint text for mobile (on hover)', 'translate' => $this->l('Bestsellers block zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Bestsellers block zoom hint text for mobile (on click)', 'translate' => $this->l('Bestsellers block zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Bestsellers block expand hint text', 'translate' => $this->l('Bestsellers block expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Bestsellers block expand hint text for mobile', 'translate' => $this->l('Bestsellers block expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Bestsellers block close button text', 'translate' => $this->l('Bestsellers block close button text') ), 'textBtnNext' => array( 'title' => 'Bestsellers block next button text', 'translate' => $this->l('Bestsellers block next button text') ), 'textBtnPrev' => array( 'title' => 'Bestsellers block prev button text', 'translate' => $this->l('Bestsellers block prev button text') ), 'message' => array( 'title' => 'Bestsellers block message (under Magic Zoom Plus)', 'translate' => $this->l('Bestsellers block message (under Magic Zoom Plus)') ) ), 'specialspage' => array( 'textHoverZoomHint' => array( 'title' => 'Specials page zoom hint text (on hover)', 'translate' => $this->l('Specials page zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Specials page zoom hint text (on click)', 'translate' => $this->l('Specials page zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Specials page zoom hint text for mobile (on hover)', 'translate' => $this->l('Specials page zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Specials page zoom hint text for mobile (on click)', 'translate' => $this->l('Specials page zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Specials page expand hint text', 'translate' => $this->l('Specials page expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Specials page expand hint text for mobile', 'translate' => $this->l('Specials page expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Specials page close button text', 'translate' => $this->l('Specials page close button text') ), 'textBtnNext' => array( 'title' => 'Specials page next button text', 'translate' => $this->l('Specials page next button text') ), 'textBtnPrev' => array( 'title' => 'Specials page prev button text', 'translate' => $this->l('Specials page prev button text') ), 'message' => array( 'title' => 'Specials page message (under Magic Zoom Plus)', 'translate' => $this->l('Specials page message (under Magic Zoom Plus)') ) ), 'blockspecials' => array( 'textHoverZoomHint' => array( 'title' => 'Specials sidebar zoom hint text (on hover)', 'translate' => $this->l('Specials sidebar zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Specials sidebar zoom hint text (on click)', 'translate' => $this->l('Specials sidebar zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Specials sidebar zoom hint text for mobile (on hover)', 'translate' => $this->l('Specials sidebar zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Specials sidebar zoom hint text for mobile (on click)', 'translate' => $this->l('Specials sidebar zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Specials sidebar expand hint text', 'translate' => $this->l('Specials sidebar expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Specials sidebar expand hint text for mobile', 'translate' => $this->l('Specials sidebar expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Specials sidebar close button text', 'translate' => $this->l('Specials sidebar close button text') ), 'textBtnNext' => array( 'title' => 'Specials sidebar next button text', 'translate' => $this->l('Specials sidebar next button text') ), 'textBtnPrev' => array( 'title' => 'Specials sidebar prev button text', 'translate' => $this->l('Specials sidebar prev button text') ), 'message' => array( 'title' => 'Specials sidebar message (under Magic Zoom Plus)', 'translate' => $this->l('Specials sidebar message (under Magic Zoom Plus)') ) ), 'blockspecials_home' => array( 'textHoverZoomHint' => array( 'title' => 'Specials block zoom hint text (on hover)', 'translate' => $this->l('Specials block zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Specials block zoom hint text (on click)', 'translate' => $this->l('Specials block zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Specials block zoom hint text for mobile (on hover)', 'translate' => $this->l('Specials block zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Specials block zoom hint text for mobile (on click)', 'translate' => $this->l('Specials block zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Specials block expand hint text', 'translate' => $this->l('Specials block expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Specials block expand hint text for mobile', 'translate' => $this->l('Specials block expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Specials block close button text', 'translate' => $this->l('Specials block close button text') ), 'textBtnNext' => array( 'title' => 'Specials block next button text', 'translate' => $this->l('Specials block next button text') ), 'textBtnPrev' => array( 'title' => 'Specials block prev button text', 'translate' => $this->l('Specials block prev button text') ), 'message' => array( 'title' => 'Specials block message (under Magic Zoom Plus)', 'translate' => $this->l('Specials block message (under Magic Zoom Plus)') ) ), 'blockviewed' => array( 'textHoverZoomHint' => array( 'title' => 'Viewed sidebar zoom hint text (on hover)', 'translate' => $this->l('Viewed sidebar zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Viewed sidebar zoom hint text (on click)', 'translate' => $this->l('Viewed sidebar zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Viewed sidebar zoom hint text for mobile (on hover)', 'translate' => $this->l('Viewed sidebar zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Viewed sidebar zoom hint text for mobile (on click)', 'translate' => $this->l('Viewed sidebar zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Viewed sidebar expand hint text', 'translate' => $this->l('Viewed sidebar expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Viewed sidebar expand hint text for mobile', 'translate' => $this->l('Viewed sidebar expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Viewed sidebar close button text', 'translate' => $this->l('Viewed sidebar close button text') ), 'textBtnNext' => array( 'title' => 'Viewed sidebar next button text', 'translate' => $this->l('Viewed sidebar next button text') ), 'textBtnPrev' => array( 'title' => 'Viewed sidebar prev button text', 'translate' => $this->l('Viewed sidebar prev button text') ), 'message' => array( 'title' => 'Viewed sidebar message (under Magic Zoom Plus)', 'translate' => $this->l('Viewed sidebar message (under Magic Zoom Plus)') ) ), 'homefeatured' => array( 'textHoverZoomHint' => array( 'title' => 'Featured block zoom hint text (on hover)', 'translate' => $this->l('Featured block zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Featured block zoom hint text (on click)', 'translate' => $this->l('Featured block zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Featured block zoom hint text for mobile (on hover)', 'translate' => $this->l('Featured block zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Featured block zoom hint text for mobile (on click)', 'translate' => $this->l('Featured block zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Featured block expand hint text', 'translate' => $this->l('Featured block expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Featured block expand hint text for mobile', 'translate' => $this->l('Featured block expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Featured block close button text', 'translate' => $this->l('Featured block close button text') ), 'textBtnNext' => array( 'title' => 'Featured block next button text', 'translate' => $this->l('Featured block next button text') ), 'textBtnPrev' => array( 'title' => 'Featured block prev button text', 'translate' => $this->l('Featured block prev button text') ), 'message' => array( 'title' => 'Featured block message (under Magic Zoom Plus)', 'translate' => $this->l('Featured block message (under Magic Zoom Plus)') ) ), 'search' => array( 'textHoverZoomHint' => array( 'title' => 'Search page zoom hint text (on hover)', 'translate' => $this->l('Search page zoom hint text (on hover)') ), 'textClickZoomHint' => array( 'title' => 'Search page zoom hint text (on click)', 'translate' => $this->l('Search page zoom hint text (on click)') ), 'textHoverZoomHintForMobile' => array( 'title' => 'Search page zoom hint text for mobile (on hover)', 'translate' => $this->l('Search page zoom hint text for mobile (on hover)') ), 'textClickZoomHintForMobile' => array( 'title' => 'Search page zoom hint text for mobile (on click)', 'translate' => $this->l('Search page zoom hint text for mobile (on click)') ), 'textExpandHint' => array( 'title' => 'Search page expand hint text', 'translate' => $this->l('Search page expand hint text') ), 'textExpandHintForMobile' => array( 'title' => 'Search page expand hint text for mobile', 'translate' => $this->l('Search page expand hint text for mobile') ), 'textBtnClose' => array( 'title' => 'Search page close button text', 'translate' => $this->l('Search page close button text') ), 'textBtnNext' => array( 'title' => 'Search page next button text', 'translate' => $this->l('Search page next button text') ), 'textBtnPrev' => array( 'title' => 'Search page prev button text', 'translate' => $this->l('Search page prev button text') ), 'message' => array( 'title' => 'Search page message (under Magic Zoom Plus)', 'translate' => $this->l('Search page message (under Magic Zoom Plus)') ) ) ); } public function getParamsMap() { $map = array( 'default' => array( 'General' => array( 'include-headers-on-all-pages' => true ), 'Image type' => array( 'thumb-image' => true, 'selector-image' => true, 'large-image' => true ), 'Positioning and Geometry' => array( 'zoomWidth' => true, 'zoomHeight' => true, 'zoomPosition' => true, 'zoomDistance' => true ), 'Miscellaneous' => array( 'lazyZoom' => true, 'rightClick' => true, 'link-to-product-page' => true, 'show-message' => true, 'message' => true ), 'Zoom mode' => array( 'zoomMode' => true, 'zoomOn' => true, 'upscale' => true, 'smoothing' => true, 'variableZoom' => true, 'zoomCaption' => true ), 'Expand mode' => array( 'expand' => true, 'expandZoomMode' => true, 'expandZoomOn' => true, 'expandCaption' => true, 'closeOnClickOutside' => true, 'cssClass' => true ), 'Hint' => array( 'hint' => true, 'textHoverZoomHint' => true, 'textClickZoomHint' => true, 'textExpandHint' => true, 'textBtnClose' => true, 'textBtnNext' => true, 'textBtnPrev' => true ), 'Mobile' => array( 'zoomModeForMobile' => true, 'textHoverZoomHintForMobile' => true, 'textClickZoomHintForMobile' => true, 'textExpandHintForMobile' => true ) ), 'product' => array( 'Enable effect' => array( 'enable-effect' => true ), 'General' => array( 'template' => true, 'magicscroll' => true ), 'Image type' => array( 'thumb-image' => false, 'selector-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Multiple images' => array( 'selectorTrigger' => true, 'transitionEffect' => true ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ), 'Scroll' => array( 'width' => true, 'height' => true, 'mode' => true, 'items' => true, 'speed' => true, 'autoplay' => true, 'loop' => true, 'step' => true, 'arrows' => true, 'pagination' => true, 'easing' => true, 'scrollOnWheel' => true, 'lazy-load' => true, 'scroll-extra-styles' => true, 'show-image-title' => true ) ), 'category' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'manufacturer' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'newproductpage' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'blocknewproducts' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'blocknewproducts_home' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'bestsellerspage' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'blockbestsellers' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'blockbestsellers_home' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'specialspage' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'blockspecials' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'blockspecials_home' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'blockviewed' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'homefeatured' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ), 'search' => array( 'Enable effect' => array( 'enable-effect' => true ), 'Image type' => array( 'thumb-image' => false, 'large-image' => false ), 'Positioning and Geometry' => array( 'zoomWidth' => false, 'zoomHeight' => false, 'zoomPosition' => false, 'zoomDistance' => false ), 'Miscellaneous' => array( 'lazyZoom' => false, 'rightClick' => false, 'link-to-product-page' => false, 'show-message' => false, 'message' => false ), 'Zoom mode' => array( 'zoomMode' => false, 'zoomOn' => false, 'upscale' => false, 'smoothing' => false, 'variableZoom' => false, 'zoomCaption' => false ), 'Expand mode' => array( 'expand' => false, 'expandZoomMode' => false, 'expandZoomOn' => false, 'expandCaption' => false, 'closeOnClickOutside' => false, 'cssClass' => false ), 'Hint' => array( 'hint' => false, 'textHoverZoomHint' => false, 'textClickZoomHint' => false, 'textExpandHint' => false, 'textBtnClose' => false, 'textBtnNext' => false, 'textBtnPrev' => false ), 'Mobile' => array( 'zoomModeForMobile' => false, 'textHoverZoomHintForMobile' => false, 'textClickZoomHintForMobile' => false, 'textExpandHintForMobile' => false ) ) ); if (!$this->isPrestaShop16x) { unset($map['blockbestsellers_home'], $map['blocknewproducts_home'], $map['blockspecials_home']); } return $map; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractProductAuctionBidResult', false)) return; abstract class AbstractProductAuctionBidResult { const INVALID = 0; const VALID_TOO_LOW = 1; const VALID_ALREADY_EXIST = 2; const VALID = 3; const LEADER_MIN_NOT_REACHED = 4; const LEADER = 5; /** * * @var integer */ protected $result = 0; /** * * @var float */ protected $bid_price; /** * * @var float */ protected $previous_price; /** * * @var float */ protected $current_price; /** * * @var ProductAuction */ protected $product_auction; /** * * @var Customer */ protected $customer; /** * * @var ProductAuctionOffer */ protected $previous_product_auction_offer; /** * * @var ProductAuctionOffer */ protected $current_product_auction_offer; /** * * @return array */ public static function getSmartyResults() { return array( 'offer_invalid' => self::INVALID, 'offer_too_low' => self::VALID_TOO_LOW, 'offer_already_placed' => self::VALID_ALREADY_EXIST, 'offer_placed' => self::VALID, 'offer_not_reached' => self::LEADER_MIN_NOT_REACHED, 'offer_highest' => self::LEADER ); } /** * * @param ProductAuction $product_auction * @param Customer $customer */ public function __construct(ProductAuction $product_auction, Customer $customer) { $this->setProductAuction($product_auction); $this->setCustomer($customer); } /** * * @return boolean */ public function isWinner() { $customer = $this->getCustomer(); $product_auction_offer = $this->getProductAuction()->getProductAuctionOffer(); return $customer && $product_auction_offer && $product_auction_offer->id_customer > 0 && $product_auction_offer->id_customer == $customer->id; } /** * * @return integer */ public function getResult() { return (int)$this->result; } /** * * @return float */ public function getBidPrice() { return $this->bid_price; } /** * * @return float */ public function getPreviousPrice() { return $this->previous_price; } /** * * @return float */ public function getCurrentPrice() { return $this->current_price; } /** * * @return ProductAuction */ public function getProductAuction() { return $this->product_auction; } /** * * @return Customer */ public function getCustomer() { return $this->customer; } /** * * @return ProductAuctionOffer */ public function getPreviousProductAuctionOffer() { if (!Validate::isLoadedObject($this->previous_product_auction_offer)) return new ProductAuctionOffer(); return $this->previous_product_auction_offer; } /** * * @return ProductAuctionOffer */ public function getCurrentProductAuctionOffer() { if (!Validate::isLoadedObject($this->current_product_auction_offer)) return new ProductAuctionOffer(); return $this->current_product_auction_offer; } /** * * @param integer $result */ public function setResult($result) { $this->result = (int)$result; } /** * * @param float $price */ public function setBidPrice($price) { $this->bid_price = $price; } /** * * @param float $price */ public function setPreviousPrice($price) { $this->previous_price = $price; } /** * * @param float $price */ public function setCurrentPrice($price) { $this->current_price = $price; } /** * * @param ProductAuction $product_auction */ public function setProductAuction(ProductAuction $product_auction) { $this->product_auction = $product_auction; } /** * * @param Customer $customer */ public function setCustomer(Customer $customer) { $this->customer = $customer; } /** * * @param ProductAuctionOffer $product_auction_offer */ public function setPreviousProductAuctionOffer(ProductAuctionOffer $product_auction_offer) { $this->previous_product_auction_offer = $product_auction_offer; } /** * * @param ProductAuctionOffer $product_auction_offer */ public function setCurrentProductAuctionOffer(ProductAuctionOffer $product_auction_offer) { $this->current_product_auction_offer = $product_auction_offer; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AdminAuctionsViewController', false)) return; class AdminAuctionsViewController extends ModuleAdminController { protected $auction_identifier; protected $auction_table; protected $auction_class_name; protected $product_identifier; protected $product_table; protected $product_class_name; /** * * @var ProductAuctionItem */ protected $product_auction_item; protected $id_product_auction; protected $id_product; protected $id_lang; protected $tabAccessCustomers; public function __construct() { $this->bootstrap = true; $this->auction_identifier = 'id_product_auction'; $this->auction_table = 'product_auction'; $this->auction_class_name = 'ProductAuction'; $this->product_identifier = 'id_product'; $this->product_table = 'product'; $this->product_class_name = 'Product'; $this->identifier = 'id_product_auction_offer'; $this->table = 'product_auction_offer'; $this->className = 'ProductAuctionOffer'; $this->lang = false; $this->list_no_link = true; $this->allow_export = true; parent::__construct(); $auctions_tab_id = Tab::getIdFromClassName('AdminAuctions'); $this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, $auctions_tab_id); $this->tabAccessCustomers = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminCustomers')); $this->id_product_auction = (int)Tools::getValue($this->auction_identifier); $this->id_lang = $this->context->language->id; $this->_defaultOrderBy = 'a.customer_price'; $this->_defaultOrderWay = 'DESC'; $bid_status = array(); $bid_status_icon = array(); $bid_status_icon[0] = 'icon-2x icon-question'; foreach (ProductAuctionOffer::getStatusList($this->module) as $id => $label) { $bid_status_icon[$id] = "icon-2x auction-bid-icon-{$id}"; $bid_status[$id] = $label; } $this->fields_list = array(); $this->fields_list['id_product_auction_offer'] = array( 'title' => $this->l('ID'), 'align' => 'center', 'width' => 50 ); $this->fields_list['customer_name'] = array( 'title' => $this->l('Customer name'), 'align' => 'center', 'filter_key' => 'jc!customer_name' ); $this->fields_list['email'] = array( 'title' => $this->l('Customer email'), 'align' => 'center', 'filter_key' => 'jc!email' ); $this->fields_list['customer_price'] = array( 'title' => $this->l('Customer max offer'), 'type' => 'price', 'align' => 'right' ); $this->fields_list['previous_price'] = array( 'title' => $this->l('Previous price'), 'type' => 'price', 'align' => 'right' ); $this->fields_list['date_add'] = array( 'title' => $this->l('Offer date'), 'type' => 'datetime', 'align' => 'right' ); $this->fields_list['status'] = array( 'title' => $this->l('Bid status'), 'align' => 'center', 'type' => 'select', 'icon' => $bid_status_icon, 'list' => $bid_status, 'filter_key' => 'a!status' ); $this->_select = 'jc.`email`, jc.`customer_name`'; $this->_join = ' LEFT JOIN ( SELECT DISTINCT c.`id_customer`, CONCAT(c.`firstname`, " ", c.`lastname`) AS customer_name, c.`email` FROM `'._DB_PREFIX_.'customer` c ) jc ON (jc.`id_customer` = a.`id_customer`) JOIN `'._DB_PREFIX_.'product_auction` pa ON (pa.id_product_auction = a.id_product_auction) JOIN `'._DB_PREFIX_.'product` p ON (pa.id_product = p.id_product) '.Shop::addSqlAssociation('product', 'p').' '; $this->_where .= ' AND a.id_product_auction = '.$this->id_product_auction; $this->loadObject(true); if (Validate::isLoadedObject($this->object)) $this->id_product_auction = $this->object->id_product_auction; $this->object->setCustomer(new Customer($this->object->id_customer)); if ($this->id_product_auction > 0) { $product_auction = new ProductAuction($this->id_product_auction, true, $this->id_lang); $this->object->setProductAuction($product_auction); $this->id_product = $product_auction->id_product; $this->product_auction_item = ProductAuctionItemFactory::getInstance($this->module)->makeBackOfficeItem($product_auction); } } public function init() { parent::init(); self::$currentIndex = self::$currentIndex."&id_product_auction={$this->id_product_auction}"; } public function initPageHeaderToolbar() { parent::initPageHeaderToolbar(); unset($this->page_header_toolbar_btn['new']); $back = Tools::getValue('back', $this->context->link->getAdminLink('AdminAuctions')); if (!Validate::isCleanHtml($back)) die(Tools::displayError()); $current_url = urlencode(self::$currentIndex."&conf=4&token={$this->token}"); if ($this->id_product_auction > 0) { $restart_auction = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_RESTART_AUCTION); $finish_auction = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_FINISH_AUCTION); $accept_auction = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_ACCEPT_AUCTION); $remind_auction = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_REMIND_AUCTION); $watch_auction = $this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_WATCH_AUCTION); if ($restart_auction && !$this->product_auction_item->isStatus(array( ProductAuction::STATUS_IDLE, ProductAuction::STATUS_CLOSED ))) { $this->page_header_toolbar_btn['restart'] = array( 'href' => $this->context->link->getAdminLink('AdminAuctions')."&restart{$this->auction_table}&{$this->auction_identifier}={$this->product_auction_item->getId()}&back={$current_url}", 'desc' => $this->l('Restart auction'), 'confirm' => 1, 'js' => 'if (confirm(\''.$this->l('Are you sure you want to restart auction? All bids will be removed and auction will start over. You might need to adjust start and end dates.').'\')){return true;}else{event.preventDefault();}' ); } if ($finish_auction && $this->product_auction_item->isStatus(ProductAuction::STATUS_RUNNING)) { $this->page_header_toolbar_btn['finish'] = array( 'href' => $this->context->link->getAdminLink('AdminAuctions')."&finish{$this->auction_table}&{$this->auction_identifier}={$this->product_auction_item->getId()}&back={$current_url}", 'desc' => $this->l('Finish auction'), 'confirm' => 1, 'js' => 'if (confirm(\''.$this->l('Are you sure you want to finish auction and make the highest bidder a winner?').'\')){return true;}else{event.preventDefault();}' ); } else { if ($this->product_auction_item->hasWinner() && $this->product_auction_item->isStatus(ProductAuction::STATUS_FINISHED)) { if ($accept_auction && !$this->product_auction_item->isMinimalPriceReached() && $this->product_auction_item->hasWinner() && $this->product_auction_item->getWinnerStatus() != ProductAuctionOffer::STATUS_WINNER) { $this->page_header_toolbar_btn['accept-winner'] = array( 'href' => $this->context->link->getAdminLink('AdminAuctions')."&accept_winner{$this->auction_table}&{$this->auction_identifier}={$this->product_auction_item->getId()}&back={$current_url}", 'desc' => $this->l('Accept winner'), 'confirm' => 1, 'js' => 'if (confirm(\''.$this->l('Are you sure you want to accept the highest offer as a winning?').'\')){return true;}else{event.preventDefault();}' ); } if ($remind_auction) { $this->page_header_toolbar_btn['remind'] = array( 'href' => $this->context->link->getAdminLink('AdminAuctions')."&remind_winner{$this->auction_table}&{$this->auction_identifier}={$this->product_auction_item->getId()}&back={$current_url}", 'desc' => $this->l('Remind winner') ); } } } if ($watch_auction) { $watchers = (int)ProductAuctionDataManager::getWatchingCustomersCountByAuction($this->product_auction_item->getId(), $this->context->shop->id); $this->page_header_toolbar_btn['watchers'] = array( 'href' => $this->context->link->getAdminLink('AdminAuctionsSubscriptions')."&{$this->auction_identifier}={$this->product_auction_item->getId()}", 'desc' => $this->l('Watchers')." ({$watchers})" ); } // adding button for preview this product if ($url_preview = $this->getPreviewUrl($this->product_auction_item->getProduct())) { $this->page_header_toolbar_btn['preview'] = array( 'short' => 'Preview', 'href' => $url_preview, 'desc' => $this->l('Preview'), 'target' => true, 'class' => 'previewUrl' ); } if ($this->tabAccess['edit']) { $this->page_header_toolbar_btn['edit'] = array( 'short' => 'Edit', 'href' => $this->context->link->getAdminLink('AdminProducts').'&id_product='.$this->product_auction_item->getProductId().'&updateproduct&key_tab=ModuleAuctions&back='.urlencode($back), 'desc' => $this->l('Edit') ); } // adding button for delete this auction if ($this->tabAccess['delete'] && $this->display != 'add') { $this->page_header_toolbar_btn['delete'] = array( 'short' => 'Delete', 'href' => $this->context->link->getAdminLink('AdminAuctions').'&id_product_auction='.$this->id_product_auction.'&deleteproduct_auction', 'desc' => $this->l('Delete'), 'confirm' => 1, 'js' => 'if (confirm(\''.$this->l('Are you sure you want to permanently delete the selected auction?').'\')){return true;}else{event.preventDefault();}' ); } } } public function initToolbar() { parent::initToolbar(); unset($this->toolbar_btn['new']); $back = Tools::getValue('back', $this->context->link->getAdminLink('AdminAuctions')); if (!Validate::isCleanHtml($back)) die(Tools::displayError()); $this->toolbar_btn['back'] = array( 'href' => $back, 'desc' => $this->l('Back to list') ); } public function initToolbarTitle() { parent::initToolbarTitle(); if ($this->id_product_auction > 0 && isset($this->toolbar_title[0])) $this->toolbar_title[0] = $this->product_auction_item->getProductName(); } public function initBreadcrumbs($tab_id = null, $tabs = null) { $display = $this->display; $this->display = 'view'; parent::initBreadcrumbs($tab_id, $tabs); $this->display = $display; } public function renderList() { if (!$this->id_product_auction) Tools::redirectAdmin($this->context->link->getAdminLink('AdminAuctions')); $this->tpl_list_vars['product_auction_item'] = array( 'current_price' => $this->product_auction_item->getCurrentPrice(), 'initial_price' => $this->product_auction_item->getInitialPrice(), 'buynow_price' => $this->product_auction_item->getBuyNowPrice(), 'minimal_price' => $this->product_auction_item->getMinimalPrice(), 'start_date' => $this->product_auction_item->getStartDate(), 'end_date' => $this->product_auction_item->getEndDate(), 'duration' => $this->product_auction_item->getDuration(), 'time_to_finish' => $this->product_auction_item->getTimeToFinish(), 'time_to_start' => $this->product_auction_item->getTimeToStart(), 'status' => array( 'is_started' => $this->product_auction_item->isStarted(), 'is_finished' => $this->product_auction_item->isFinished(), 'id' => $this->product_auction_item->getStatus(), 'name' => $this->product_auction_item->getStatusName($this->module) ), 'reserve' => array( 'has_reserve' => $this->product_auction_item->hasMinimalPrice(), 'reached' => $this->product_auction_item->isMinimalPriceReached() ), 'offers' => array( 'has_offers' => $this->product_auction_item->hasOffers(), 'has_winner' => $this->product_auction_item->hasWinner(), 'has_access_to_customers' => $this->tabAccessCustomers['view'], 'count' => $this->product_auction_item->getOffersCount(), 'winner' => array( 'id' => $this->product_auction_item->getWinnerId(), 'name' => $this->product_auction_item->getWinnerName(), 'name_full' => $this->product_auction_item->getWinnerNameFull() ) ) ); $this->addRowAction('markinvalid'); $this->addRowAction('markvalid'); $this->addRowAction('markwinner'); $this->addRowAction('rejectwinner'); return parent::renderList(); } public function getPreviewUrl(Product $product) { $id_lang = Configuration::get('PS_LANG_DEFAULT', null, null, Context::getContext()->shop->id); if (!ShopUrl::getMainShopDomain()) return false; $is_rewrite_active = (bool)Configuration::get('PS_REWRITING_SETTINGS'); $preview_url = $this->context->link->getProductLink( $product, $this->getFieldValue($product, 'link_rewrite'), Category::getLinkRewrite($this->getFieldValue($product, 'id_category_default'), $this->context->language->id), null, $id_lang, (int)Context::getContext()->shop->id, 0, $is_rewrite_active ); if (!$product->active) { $admin_dir = dirname($_SERVER['PHP_SELF']); $admin_dir = Tools::substr($admin_dir, strrpos($admin_dir, '/') + 1); $preview_url .= ((strpos($preview_url, '?') === false) ? '?' : '&').'adtoken='.$this->token.'&ad='.$admin_dir.'&id_employee='.(int)$this->context->employee->id; } return $preview_url; } public function initProcess() { parent::initProcess(); if (Tools::isSubmit('change_status'.$this->table)) { if ($this->tabAccess['edit'] === '1') $this->action = 'change_status'; } else if (Tools::isSubmit('mark_winner'.$this->table)) { if ($this->tabAccess['edit'] === '1') $this->action = 'mark_winner'; } else if (Tools::isSubmit('reject_winner'.$this->table)) { if ($this->tabAccess['edit'] === '1') $this->action = 'reject_winner'; } } public function processChangeStatus() { if (Validate::isLoadedObject($this->object)) { if ($this->product_auction_item->isStatus(ProductAuction::STATUS_RUNNING)) { $status = (int)Tools::getValue('status'); if (in_array($status, array( ProductAuctionOffer::STATUS_INVALID, ProductAuctionOffer::STATUS_VALID ))) { $this->object->setOfferStatus($status); $this->redirect_after = self::$currentIndex.'&conf=4&token='.$this->token; } else $this->errors[] = Tools::displayError('An error occurred while changing status of the auction offer.'); } else $this->errors[] = Tools::displayError('An error occurred while changing status of the auction offer.'); } else $this->errors[] = Tools::displayError('An error occurred while changing status of the auction offer.'); return $this->object; } public function processMarkWinner() { if (Validate::isLoadedObject($this->object)) { if ($this->product_auction_item->isStatus(ProductAuction::STATUS_FINISHED)) { $product_auction_type = $this->object->product_auction->getProductAuctionType(); $product_auction_type->markWinner($this->object); $this->redirect_after = self::$currentIndex.'&conf=4&token='.$this->token; } else $this->errors[] = Tools::displayError('An error occurred while marking as winner.'); } else $this->errors[] = Tools::displayError('An error occurred while marking as winner.'); return $this->object; } public function processRejectWinner() { if (Validate::isLoadedObject($this->object)) { if ($this->product_auction_item->isStatus(ProductAuction::STATUS_FINISHED)) { $product_auction_type = $this->object->product_auction->getProductAuctionType(); $product_auction_mailing = $product_auction_type->getProductAuctionMailingManager($this->module); $product_auction_mailing->notifyParticipants($this->object->getCustomer()); $product_auction_mailing->notifyEmployees($this->getAdministratorsToNotify($this->object)); $product_auction_type->notify($product_auction_mailing); $product_auction_type->rejectWinner($this->object); $this->redirect_after = self::$currentIndex.'&conf=4&token='.$this->token; } else $this->errors[] = Tools::displayError('An error occurred while rejecting as winner.'); } else $this->errors[] = Tools::displayError('An error occurred while rejecting as winner.'); return $this->object; } public function displayMarkInvalidLink($token, $id, $name) { if (!$this->product_auction_item->isStatus(ProductAuction::STATUS_RUNNING)) return; foreach ($this->_list as $element) { if ($id == $element['id_product_auction_offer'] && $element['status'] != ProductAuctionOffer::STATUS_INVALID) { $tpl = $this->createTemplate('helpers/list/list_action_auctions_mark_invalid.tpl'); $tpl->assign(array( 'href' => $this->context->link->getAdminLink('AdminAuctionsView').'&change_status'.$this->table.'&status='.ProductAuctionOffer::STATUS_INVALID.'&'.$this->identifier.'='.$id, 'action' => $this->l('Mark as invalid'), 'id' => $id, 'mod_path' => $this->module->getPathUri() )); return $tpl->fetch(); } } } public function displayMarkValidLink($token, $id, $name) { if (!$this->product_auction_item->isStatus(ProductAuction::STATUS_RUNNING)) return; foreach ($this->_list as $element) { if ($id == $element['id_product_auction_offer'] && $element['status'] == ProductAuctionOffer::STATUS_INVALID) { $tpl = $this->createTemplate('helpers/list/list_action_auctions_mark_valid.tpl'); $tpl->assign(array( 'href' => $this->context->link->getAdminLink('AdminAuctionsView').'&change_status'.$this->table.'&status='.ProductAuctionOffer::STATUS_VALID.'&'.$this->identifier.'='.$id, 'action' => $this->l('Mark as valid'), 'id' => $id, 'mod_path' => $this->module->getPathUri() )); return $tpl->fetch(); } } } public function displayMarkWinnerLink($token, $id, $name) { } public function displayRejectWinnerLink($token, $id, $name) { } protected function getAdministratorsToNotify(ProductAuction $product_auction) { $mailing_settings = $this->module->getSettings('AuctionsMailingSettings'); $employees = new Collection('Employee'); $employees->where('active', '=', 1); $employees->where('id_employee', 'IN', $mailing_settings->getValue(AuctionsMailingSettings::AUCTION_BACKOFFICE_EMPLOYEES)); return $employees->getResults(); } public function viewAccess($disable = false) { if (!Module::isInstalled('agilemultipleseller')) return parent::viewAccess($disable); $eaccess = AgileSellerManager::get_entity_access($this->product_table); if ($this->is_seller && $this->id_product) { $id_owner = AgileSellerManager::getObjectOwnerID($this->product_table, $this->id_product); if ($id_owner > 0 || $eaccess['is_exclusive']) if (!AgileSellerManager::hasOwnership($this->product_table, $this->id_product)) return false; } if ($disable) return true; if ($this->tabAccess['view'] === '1') return true; return false; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionCreateEnglish', false)) return; class ProductAuctionCreateEnglish extends AbstractProductAuctionCreate { public function getFieldsForm() { $module = $this->module; $currency = $this->currency; $templates = ProductAuctionTemplate::getTemplatesList($module); if (count($templates) > 1) { $template_inputs = array(); $template_inputs[] = array( 'type' => 'select', 'label' => 'Template', 'name' => 'id_product_auction_template', 'options' => array( 'query' => $templates, 'id' => 'id', 'name' => 'name' ), 'desc' => $this->l('Select template for the current auction') ); } $settings_inputs = array(); $settings_inputs[] = array( 'type' => 'hidden', 'name' => 'submitted_tabs[]', 'default_value' => self::MODULE_TAB_NAME ); $settings_inputs[] = array( 'type' => 'hidden', 'name' => 'id_product_auction_type' ); $settings_inputs[] = array( 'type' => 'switch', 'label' => $this->l('Activate auction'), 'name' => 'enable_auction', 'required' => true, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'default_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'default_off', 'value' => 0, 'label' => $this->l('No') ), ), 'desc' => $this->l('Switch to enable auction on the current product') ); $dates_inputs = array(); $dates_inputs[] = array( 'type' => 'auctions_datetime', 'range' => true, 'label' => $this->l('Starts at:'), 'desc' => $this->l('Date when the auction starts'), 'name' => 'from', 'required' => true, 'disabled' => !$module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SET_START_DATE), 'autocomplete' => false, 'size' => 24, 'default_value' => date('Y-m-d H:i:s') ); $dates_inputs[] = array( 'type' => 'auctions_datetime', 'range' => true, 'label' => $this->l('Ends at:'), 'desc' => $this->l('Date when the auction ends'), 'name' => 'to', 'required' => true, 'disabled' => !$module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SET_END_DATE), 'autocomplete' => false, 'size' => 24, 'shortcuts' => array( array( 'value' => 1, 'label' => $this->l('1d') ), array( 'value' => 2, 'label' => $this->l('2d') ), array( 'value' => 5, 'label' => $this->l('5d') ), array( 'value' => 7, 'label' => $this->l('7d') ), array( 'value' => 10, 'label' => $this->l('10d') ), array( 'value' => 14, 'label' => $this->l('14d') ), array( 'value' => 30, 'label' => $this->l('30d') ) ) ); $prices_inputs = array(); $prices_inputs[] = array( 'type' => 'text', 'label' => $this->l('Starting price:'), 'name' => 'initial_price', 'size' => 10, 'required' => true, 'price' => true, 'prefix' => $currency->getSign('left'), 'suffix' => $currency->getSign('right'), 'desc' => $this->l('Initial price at which the auction will start'), 'string_format' => '%.2f' ); $prices_inputs[] = array( 'type' => 'text', 'label' => $this->l('Reserve price:'), 'desc' => $this->l('Minimal price at which you are able to sell the product'), 'name' => 'minimal_price', 'size' => 10, 'required' => false, 'price' => true, 'prefix' => $currency->getSign('left'), 'suffix' => $currency->getSign('right'), 'string_format' => '%.2f' ); if ($module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SET_BUY_NOW)) { $prices_inputs[] = array( 'type' => 'text', 'label' => $this->l('Buy now price:'), 'name' => 'buynow_price', 'size' => 10, 'required' => false, 'price' => true, 'prefix' => $currency->getSign('left'), 'suffix' => $currency->getSign('right'), 'desc' => $this->l('Buy now price at which you are able to sell the product without auction'), 'string_format' => '%.2f' ); $prices_inputs[] = array( 'type' => 'switch', 'label' => $this->l('Buy now after first bid'), 'name' => 'buynow_after_bid', 'required' => true, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'default_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'default_off', 'value' => 0, 'label' => $this->l('No') ), ), 'desc' => $this->l('Define if you want "Buy now" option to be still available after the first bid is placed'), ); } $increment_rules_inputs = array(); if ($module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SET_INCREMENT_RULES)) $increment_rules_inputs[] = array( 'type' => 'bid_range', 'label' => $this->l('Bidding range:'), 'desc' => $this->l('Define ranges of prices and belonging to them bid increments that will be considered as valid bids.'), 'name' => 'bidding_increment_array', 'size' => 15, 'price' => true, 'prefix' => $currency->getSign('left'), 'suffix' => $currency->getSign('right'), 'string_format' => '%.2f' ); $proxy_inputs = array(); if ($module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SET_PROXY_BIDDING)) $proxy_inputs[] = array( 'type' => 'switch', 'label' => $this->l('Activate proxy bidding'), 'name' => 'proxy_bidding', 'required' => true, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => 'default_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'default_off', 'value' => 0, 'label' => $this->l('No') ), ), 'desc' => $this->l('Enable automatic bidding on the current auction'), ); $popcorn_inputs = array(); if ($module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SET_POPCORN_BIDDING)) { $popcorn_inputs[] = array( 'type' => 'text', 'label' => $this->l('Extend the bid deadline within:'), 'desc' => $this->l('Extend the bid deadline when bid is made within given amount of seconds before the auction ends'), 'name' => 'extend_threshold', 'suffix' => $this->l('seconds'), 'size' => 24 ); $popcorn_inputs[] = array( 'type' => 'text', 'range' => true, 'label' => $this->l('Extend the bid deadline by:'), 'desc' => $this->l('Extend the bid deadline by given amount of seconds'), 'name' => 'extend_by', 'suffix' => $this->l('seconds'), 'size' => 24 ); } $fields_form = array(); if (!empty($template_inputs)) $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Template') ), 'description' => $this->l('If you change template, all not saved values will be lost and replaced with default values defined in the selected template.'), 'input' => $template_inputs ) ); if (!empty($settings_inputs)) $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Settings') ), 'input' => $settings_inputs ) ); if (!empty($dates_inputs)) $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Dates') ), 'input' => $dates_inputs ) ); if (!empty($prices_inputs)) $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Prices') ), 'description' => $this->l('All prices should be pre-tax. Tax will be calculated automatically based on the tax defined in "prices" tab and shop settings.'), 'input' => $prices_inputs ) ); if (!empty($increment_rules_inputs)) $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Bidding Increment Rules') ), 'description' => $this->l('Set the minimum amount by which the bid will be raised. You can create a number of bidding ranges (increment rules.)'), 'input' => $increment_rules_inputs ) ); if (!empty($proxy_inputs)) $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Proxy bidding') ), 'description' => $this->l('Proxy bidding enables the customer to place the maximum amount he/she is willing to pay for the item. That price is not visible for other users and the customer\'s bid is automatically raised when someone places higher offer until the maximum amount defined by the customer is reached. The customer can get the product for less than his/her actual bid.'), 'input' => $proxy_inputs ) ); if (!empty($popcorn_inputs)) $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Popcorn bidding') ), 'description' => $this->l('Popcorn Bidding gives all bidders an equal chance of winning an auction by extending the end time of the auction if a last minute bid is placed. It is used to simulate a live auction and prevents other bidders from "sniping" an auction at the last second without giving all interested bidders a chance to win.'), 'input' => $popcorn_inputs, ) ); $fields_form[] = array( 'form' => array( 'submit' => array( 'title' => $this->l('Save'), 'name' => 'submitAddproduct', 'stay' => true, ), ), ); return $fields_form; } /** * * @param Product $product */ public function setProductDefaults(Product $product) { $product->show_price = 1; $product->on_sale = 0; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionSubscriptionDataManager', false)) return; class ProductAuctionSubscriptionDataManager { const ADD = 'add'; const REMOVE = 'remove'; const CLEAR = 'clear'; public static function addProductAuctionSubscription($customer_id, array $product_auction_ids) { $customer_id = (int)$customer_id; $product_auction_ids = array_map('intval', $product_auction_ids); if ($customer_id > 0 && $product_auction_ids > 0) { $current_datetime = date('Y-m-d H:i:s'); $query = null; foreach ($product_auction_ids as $product_auction_id) $query .= ' INSERT IGNORE INTO `'._DB_PREFIX_.'product_auction_subscriptions` (id_product_auction, id_customer, date_add, date_upd) VALUES('.$product_auction_id.', '.$customer_id.', "'.$current_datetime.'", "'.$current_datetime.'"); '; return Db::getInstance()->Execute($query); } return false; } public static function removeProductAuctionSubscription($customer_id, array $product_auction_ids) { $customer_id = (int)$customer_id; $product_auction_ids = array_map('intval', $product_auction_ids); if ($customer_id > 0 && count($product_auction_ids) > 0) { return Db::getInstance()->Execute(' DELETE FROM `'._DB_PREFIX_.'product_auction_subscriptions` WHERE 1 AND id_product_auction IN('.implode(',', $product_auction_ids).') AND id_customer = '.$customer_id.' '); } return false; } public static function clearProductAuctionSubscription($customer_id) { $customer_id = (int)$customer_id; if ($customer_id > 0) { return Db::getInstance()->Execute(' DELETE FROM `'._DB_PREFIX_.'product_auction_subscriptions` WHERE 1 AND id_customer = '.$customer_id.' '); } return false; } public static function isSubscribed($customer_id, $product_auction_id) { $customer_id = (int)$customer_id; $product_auction_id = (int)$product_auction_id; $result = Db::getInstance()->getRow(' SELECT count(id_product_auction) AS count FROM `'._DB_PREFIX_.'product_auction_subscriptions` WHERE 1 AND id_product_auction = '.$product_auction_id.' AND id_customer = '.$customer_id.' '); if ($result) return (bool)$result['count']; return false; } public static function getSubscribedProductAuctionIdsForCustomer(Customer $customer) { $customer_id = (int)$customer->id; if (!$customer_id) return array(); $result = Db::getInstance()->executeS(' SELECT id_product_auction FROM `'._DB_PREFIX_.'product_auction_subscriptions` WHERE id_customer = '.$customer_id.' '); $ids = array(); if (!empty($result)) foreach ($result as $row) $ids[] = $row['id_product_auction']; return $ids; } /** * * @param ProductAuction $product_auction * @return Customers[] */ public static function getSubscribersCustomersCollectionByProductAuction(ProductAuction $product_auction, $exclude_participants = true, $language_id = null) { $customer_fields = CoreModuleTools::convertFields(Customer::$definition, array( 'prefix' => 'c' )); $query = ' SELECT DISTINCT '.implode(', ', $customer_fields).' FROM `'._DB_PREFIX_.'customer` c INNER JOIN `'._DB_PREFIX_.'product_auction_subscriptions` pas ON (c.id_customer = pas.id_customer) LEFT JOIN `'._DB_PREFIX_.'product_auction_offer` pao ON (pas.id_product_auction = pao.id_product_auction AND c.id_customer = pao.id_customer) WHERE pas.id_product_auction = '.(int)$product_auction->id.' '; if ($exclude_participants) $query .= ' AND pao.id_product_auction_offer IS null '; $result = Db::getInstance()->executeS($query); $customer_collection = array(); if (!empty($result)) { $classes = array( 'Customer' ); $result = CoreModuleTools::hydrateCollection($classes, $result, $language_id); foreach ($result['Customer'] as $customer) $customer_collection[] = $customer; } return $customer_collection; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionOffer', false)) return; class ProductAuctionOffer extends ObjectModelCore { const STATUS_VALID = 1; const STATUS_INVALID = 2; const STATUS_WINNER = 3; const STATUS_RETIRED = 4; /** * @var integer ProductAuctionOffer id */ public $id_product_auction_offer; /** * @var integer ProductAuction id */ public $id_product_auction; /** * @var integer Customer id */ public $id_customer; /** * @var float customer price in euros */ public $customer_price = 0.000000; /** * @var float previous price in euros */ public $previous_price = 0.000000; /** * @var boolean ProductAuctionOffer status */ public $status = 1; /** * @var string Object creation date */ public $date_add; /** * @var string Object last modification date */ public $date_upd; public static $definition = array( 'table' => 'product_auction_offer', 'primary' => 'id_product_auction_offer', 'fields' => array( 'id_product_auction' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true ), 'id_customer' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true ), 'customer_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true ), 'previous_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'status' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'date_add' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ), 'date_upd' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ) ), 'associations' => array( 'product_auction' => array( 'type' => self::HAS_ONE ), 'customer' => array( 'type' => self::HAS_ONE ) ) ); /** * * @var Customer */ public $customer; /** * * @var ProductAuction */ public $product_auction; public function __construct($id = null, $full = false, $id_lang = null, $id_shop = null) { parent::__construct($id, null, $id_shop); if ($full) $this->setCustomer(new Customer($this->id_customer, null, null)); } public static function getStatusList(Module $module) { return array( self::STATUS_VALID => $module->l('Valid', __CLASS__), self::STATUS_INVALID => $module->l('Invalid', __CLASS__), self::STATUS_WINNER => $module->l('Winner', __CLASS__), self::STATUS_RETIRED => $module->l('Retired', __CLASS__) ); } /** * * @return ProductAuction */ public function getProductAuction() { return $this->product_auction; } /** * * @return Customer */ public function getCustomer() { return $this->customer; } /** * * @param integer $status * @throws PrestaShopException * @return ProductAuctionOffer */ public function setOfferStatus($status) { if (!array_key_exists('status', $this)) throw new PrestaShopException('property "status" is missing in object '.get_class($this)); // Update only status field $this->setFieldsToUpdate(array( 'status' => true )); // Update active status on object switch ($status) { case self::STATUS_INVALID: $this->status = self::STATUS_INVALID; break; case self::STATUS_VALID: $this->status = self::STATUS_VALID; break; case self::STATUS_WINNER: $this->status = self::STATUS_WINNER; break; case self::STATUS_RETIRED: $this->status = self::STATUS_RETIRED; break; } // Change status to active/inactive if ($this->update(true)) $this->product_auction->calculateCurrentLeader(); return $this; } /** * * @param Customer $customer * @return ProductAuctionOffer */ public function setCustomer(Customer $customer) { if ($customer->id == $this->id_customer) $this->customer = $customer; return $this; } /** * * @param ProductAuction $product_auction * @return ProductAuctionOffer */ public function setProductAuction(ProductAuction $product_auction) { if ($product_auction->id == $this->id_product_auction) $this->product_auction = $product_auction; return $this; } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_34c869c542dee932ef8cd96d2f91cae6'] = 'Nossas lojas'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_a82be0f551b8708bc08eb33cd9ded0cf'] = 'Informações'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_d1aa22a3126f04664e0fe3f598994014'] = 'Promoções'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_9ff0635f5737513b1a6f559ac2bff745'] = 'Novos produtos'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_3cb29f0ccc5fd220a97df89dafe46290'] = 'Mais vendidos'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_02d4482d332e1aef3437cd61c9bcc624'] = 'Contacte-nos'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_e1da49db34b0bdfdddaba2ad6552f848'] = 'mapa do Site'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_5813ce0ec7196c492c97596718f71969'] = 'Mapa do Site'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_7a52e36bf4a1caa031c75a742fb9927a'] = 'Alimentado por'; <file_sep><?php header("Pragma: no-cache"); header("Expires: 0"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); $currentDir = dirname(__FILE__); $PS_ROOT_DIR=realpath($currentDir.'/../..'); require($PS_ROOT_DIR.'/config/config.inc.php'); $cd_ean13=Tools::getValue('cd_ean13'); $USER_ID_LANG=Tools::getValue('lang'); $url=Tools::getValue('url'); $url_logo=Tools::getValue('url').'img/logo.jpg'; $url=$url.'modules/yourbarcode_gp/ean13.php'; //echo $url.'<BR>'; function png2jpg($originalFile, $outputFile, $quality) { $array= getImageSize($originalFile); //test si l'image envoyé est bien une image png et pas un jpg cammouflé $pos = strripos($array['mime'], 'png'); if ($pos !== false) { $image = imagecreatefrompng($originalFile); if(check_transparent($image)) { $image = imagetranstowhite($image); imagejpeg($image, $outputFile, $quality); imagedestroy($image); } } } //converti les parties transparente en blanc function imagetranstowhite($trans) { // Create a new true color image with the same size $w = imagesx($trans); $h = imagesy($trans); $white = imagecreatetruecolor($w, $h); // Fill the new image with white background $bg = imagecolorallocate($white, 255, 255, 255); imagefill($white, 0, 0, $bg); // Copy original transparent image onto the new image imagecopy($white, $trans, 0, 0, 0, 0, $w, $h); return $white; } //verifie si une image contient des zone transparente function check_transparent($im) { $width = imagesx($im); // Get the width of the image $height = imagesy($im); // Get the height of the image // We run the image pixel by pixel and as soon as we find a transparent pixel we stop and return true. for($i = 0; $i < $width; $i++) { for($j = 0; $j < $height; $j++) { $rgba = imagecolorat($im, $i, $j); if(($rgba & 0x7F000000) >> 24) { return true; } } } // If we dont find any pixel the function will return false. return false; } //echo _PS_ROOT_DIR_; $version=substr(str_replace('.','',_PS_VERSION_),0,3); if ($version<143) { include_once(_PS_ROOT_DIR_.'/modules/yourbarcode_gp/class/Imagegp.php'); } require('fpdf.php'); //suppression de toutes les tables temporaire ayant pu être généré et non effacé a cause d'un timeout $sql='show tables where Tables_in_'._DB_NAME_.' like \''._DB_PREFIX_.'yourstock_gp_concat_attr%\''; $resultat=Db::getInstance()->ExecuteS($sql); foreach ($resultat as $row){ $sql='drop table '.$row['Tables_in_'._DB_NAME_]; Db::getInstance()->Execute($sql); } //////////////////////////////////////////////////////////////////////////////////// //creation table temporaire pour concatener les combinaisons des differents attribut //////////////////////////////////////////////////////////////////////////////////// $sql='show tables where Tables_in_'._DB_NAME_.' like \''._DB_PREFIX_.'yourstock_gp_concat_attr%\''; $resultat=Db::getInstance()->ExecuteS($sql); foreach ($resultat as $row){ $sql='drop table '.$row['Tables_in_'._DB_NAME_]; Db::getInstance()->Execute($sql); } $table_tmp=_DB_PREFIX_.'yourstock_gp_concat_attr'.time(); Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS '.$table_tmp.' ( `id_product_attribute` int(11) NOT NULL , `name` varchar(256), PRIMARY KEY (`id_product_attribute`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;'); //insert les combinaisons dans la table temporaire $sql='select distinct id_product_attribute from '._DB_PREFIX_.'product_attribute_combination'; $result = Db::getInstance()->ExecuteS($sql); foreach($result as $row){ $sql='select '._DB_PREFIX_.'product_attribute_combination.id_product_attribute, '._DB_PREFIX_.'attribute_lang.name from '._DB_PREFIX_.'product_attribute_combination, '._DB_PREFIX_.'attribute_lang where '._DB_PREFIX_.'attribute_lang.id_attribute='._DB_PREFIX_.'product_attribute_combination.id_attribute and '._DB_PREFIX_.'product_attribute_combination.id_product_attribute='.$row['id_product_attribute'].' and '._DB_PREFIX_.'attribute_lang.id_lang='.$USER_ID_LANG; $result1 = Db::getInstance()->ExecuteS($sql); //echo $sql; $concat_attr=''; foreach ($result1 as $row1) { $concat_attr=$concat_attr.addslashes($row1['name']).'\n'; } $query='INSERT INTO '.$table_tmp.' (`id_product_attribute`, `name`) VALUES (\''.$row['id_product_attribute'].'\',\''.$concat_attr.'\')'; //echo $query; Db::getInstance()->Execute($query); } //execute la requete permettant de recuperer les informations pour generer le PDF de l'article $sql='select '._DB_PREFIX_.'product.id_product, '._DB_PREFIX_.'product.active, '._DB_PREFIX_.'supplier.name as supplier, if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),0,'._DB_PREFIX_.'product_attribute.id_product_attribute) as id_product_attribute, if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),'._DB_PREFIX_.'product.supplier_reference,'._DB_PREFIX_.'product_attribute.supplier_reference) as supplier_reference, CONCAT(CONCAT('._DB_PREFIX_.'product_lang.name,\':<BR>\'),'._DB_PREFIX_.'product_lang.description_short) as description_short, '.$table_tmp.'.name as combination, if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),'._DB_PREFIX_.'product.ean13,'._DB_PREFIX_.'product_attribute.ean13) as barcode, if(isnull('._DB_PREFIX_.'product_attribute_image.id_image),'._DB_PREFIX_.'image.id_image,'._DB_PREFIX_.'product_attribute_image.id_image) as id_image from '._DB_PREFIX_.'product JOIN '._DB_PREFIX_.'product_lang ON ('._DB_PREFIX_.'product_lang.id_product='._DB_PREFIX_.'product.id_product) LEFT OUTER JOIN '._DB_PREFIX_.'product_attribute ON ('._DB_PREFIX_.'product_attribute.id_product='._DB_PREFIX_.'product.id_product) LEFT OUTER JOIN '.$table_tmp.' ON ('.$table_tmp.'.id_product_attribute='._DB_PREFIX_.'product_attribute.id_product_attribute) LEFT OUTER JOIN '._DB_PREFIX_.'product_attribute_image ON ('._DB_PREFIX_.'product_attribute_image.id_product_attribute='._DB_PREFIX_.'product_attribute.id_product_attribute and '._DB_PREFIX_.'product_attribute_image.id_image<>0) LEFT OUTER JOIN '._DB_PREFIX_.'image ON ('._DB_PREFIX_.'image.id_product='._DB_PREFIX_.'product.id_product and '._DB_PREFIX_.'image.cover=1) LEFT OUTER JOIN '._DB_PREFIX_.'supplier ON ('._DB_PREFIX_.'supplier.id_supplier='._DB_PREFIX_.'product.id_supplier) where '._DB_PREFIX_.'product_lang.id_lang='.$USER_ID_LANG. ' and '._DB_PREFIX_.'product.active=1 and if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),'._DB_PREFIX_.'product.ean13,'._DB_PREFIX_.'product_attribute.ean13)=\''.$cd_ean13.'\' order by '._DB_PREFIX_.'product.id_product, if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),0,'._DB_PREFIX_.'product_attribute.id_product_attribute) '; $result = Db::getInstance()->ExecuteS($sql); //echo $sql; foreach ($result as $row) { $id_image=$row['id_image']; $code_article=$row['id_product'].'-'.$row['id_product_attribute']; $description_short=$row['description_short']; $supplier=$row['supplier']; $supplier_reference=$row['supplier_reference']; $description_short=utf8_decode($description_short); $combination=utf8_decode($row['combination']); //remplacement des <BR> par des sauts de ligne $tab_description_short=explode('<BR>',$description_short); $description_short=""; foreach ($tab_description_short as $element) { $description_short=$description_short."\n".$element; } $description_short=strip_tags($description_short); $description_short=strval($description_short); } //echo '<BR>images:'.$id_image.'<BR>'; if ($id_image==''){ $stat_images=0; } else { $stat_images=1; //creation d'un objet image pour recuperer le chemin de image en fonction de la version de prestashop if ($version<143) { $image = new Imagegp($id_image); } else { $image = new Image($id_image); } } //suppression de la table temporaire Db::getInstance()->Execute('DROP TABLE IF EXISTS '.$table_tmp.';'); //recuperer l'image de l'article //echo addslashes($_GET['url'].'/img/p/'.$image->getExistingImgPath()).'-large.jpg'; $format_pg='A4'; //A3, A4, A5, Letter, Legal sont possible $orientation='P'; //P-> portrait et L-> Landscape $marge_haut=0; $marge_gauche=150; $largeur_cd=60; $hauteur_cd=25; //si 0 garde les proportions $nb_img_lg=5; $nb_lig=19; $esp_lg_lg=0; $esp_cl_cl=0; $pdf = new FPDF(); $pdf->AliasNbPages(); $pdf->AddPage($orientation,$format_pg); $pdf->SetFont('Times','',12); $abs_c_gh_cd=$marge_gauche; $ord_c_gh_cd=$marge_haut; //gere les saut de ligne //dessine les cd sur la ligne //curl pour charger le logo $curlHandler=curl_init(); curl_setopt($curlHandler, CURLOPT_URL, $url_logo); curl_setopt($curlHandler, CURLOPT_HEADER,0); curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); $output =curl_exec($curlHandler); curl_close($curlHandler); file_put_contents("test_tmp.jpg",$output); //$pdf->Image($url_logo,10,0,60,0,'jpg'); //echo 'alpha:'.is_alpha_png("test_tmp.jpg"); png2jpg("test_tmp.jpg", "test_tmp.jpg", 100); $pdf->Image("test_tmp.jpg",10,0,60,0,'jpg'); //curl pour charger le code barre $curlHandler=curl_init(); curl_setopt($curlHandler, CURLOPT_URL, $url.'?numero='.$cd_ean13.'&dimension=5'.'&rotation=0'); curl_setopt($curlHandler, CURLOPT_HEADER,0); curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); $output2 =curl_exec($curlHandler); curl_close($curlHandler); file_put_contents("test_tmp2.jpg",$output2); //$pdf->Image($url.'?numero='.$cd_ean13.'&dimension=5',$abs_c_gh_cd,$ord_c_gh_cd,$largeur_cd,$hauteur_cd,'png'); png2jpg("test_tmp2.jpg", "test_tmp2.jpg", 100); $pdf->Image("test_tmp2.jpg",$abs_c_gh_cd,$ord_c_gh_cd,$largeur_cd,$hauteur_cd,'png'); $url_images_prod=''; //generation de l'url permettant de trouver l'image du produit if ($stat_images==1) { if ($version<150) { $url_images_prod=addslashes($_GET['url'].'/img/p/'.$image->getExistingImgPath()).'-large.jpg'; } else { $url_images_prod=addslashes($_GET['url'].'/img/p/'.$image->getExistingImgPath()).'-large_default.jpg'; } //echo $url_images_prod; } else { //mettre une image qui indique que l'article n'as pas d'image dispo $url_images_prod=addslashes($_GET['url'].'/modules/yourbarcode_gp/img/indisponible.gif'); } //curl pour charger l'image produit $curlHandler=curl_init(); curl_setopt($curlHandler, CURLOPT_URL, $url_images_prod); curl_setopt($curlHandler, CURLOPT_HEADER,0); curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); $output3 =curl_exec($curlHandler); curl_close($curlHandler); if ($stat_images==1) { file_put_contents("test_tmp3.jpg",$output3); png2jpg("test_tmp3.jpg", "test_tmp3.jpg", 100); $pdf->Image(addslashes("test_tmp3.jpg"),125,70,80,0,'jpg'); } else { file_put_contents("test_tmp3.gif",$output3); $pdf->Image(addslashes("test_tmp3.gif"),150,50,50,0,'gif'); } /* if ($stat_images==1) { $pdf->Image(addslashes($_GET['url'].'/img/p/'.$image->getExistingImgPath()).'-large.jpg',125,70,80,0,'jpg'); } else { //mettre une image qui indique que l'article n'as pas d'image dispo $pdf->Image(addslashes($_GET['url'].'/modules/yourbarcode_gp/img/indisponible.gif'),150,50,50,0,'gif'); } if ($stat_images==1) { $pdf->Image(addslashes($_GET['url'].'/img/p/'.$image->getExistingImgPath()).'-large.jpg',125,70,80,0,'jpg'); } else { //mettre une image qui indique que l'article n'as pas d'image dispo $pdf->Image(addslashes($_GET['url'].'/modules/yourbarcode_gp/img/indisponible.gif'),150,50,50,0,'gif'); }*/ $pdf->SetY(30); $pdf->SetFont('Arial','B',12); $pdf->MultiCell(120,5,"Fournisseur:",0,'L',false); $pdf->SetXY(37,30); $pdf->SetFont('Arial','',12); $pdf->MultiCell(120,5,$supplier,0,'L',false); $pdf->SetY(40); $pdf->SetFont('Arial','B',12); $pdf->MultiCell(120,5,"Référence fournisseur:",0,'L',false); $pdf->SetXY(57,40); $pdf->SetFont('Arial','',12); $pdf->MultiCell(120,5,$supplier_reference,0,'L',false); $pdf->SetY(50); $pdf->SetFont('Arial','B',12); $pdf->MultiCell(120,5,"Code article:",0,'L',false); $pdf->SetXY(37,50); $pdf->SetFont('Arial','',12); $pdf->MultiCell(120,5,$code_article,0,'L',false); $pdf->SetY(60); $pdf->SetFont('Arial','BU',20); $pdf->MultiCell(120,5,"Description:",0,'L',false); $pdf->SetY(80); $pdf->SetFont('Arial','',12); $pdf->MultiCell(120,5,$description_short,0,'L',false); $pdf->SetY($pdf->GetY()+10); $pdf->SetFont('Arial','B',12); $pdf->SetTextColor(237,37,37); $pdf->MultiCell(120,5,$combination,0,'L',false); //$pdf->MultiCell(120,5,"toto\ntiti",0,'L',false); $pdf->Output(); ?><file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_20351b3328c35ab617549920f5cb4939'] = 'Personnalisation #'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ed6e9a09a111035684bb23682561e12d'] = 'supprimer ce produit de mon panier'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_c6995d6cc084c192bc2e742f052a5c74'] = 'Livraison gratuite!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_e7a6ca4e744870d455a57b644f696457'] = 'Gratuit!'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f2a6c498fb90ee345d997f888fce3b18'] = 'Effacer'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_a85eba4c6c699122b2bb1387ea4813ad'] = 'Chariot'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_86024cad1e83101d97359d7351051156'] = 'produits'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_f5bf48aa40cad7891eb709fcf1fde128'] = 'produit'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_9e65b51e82f2a9b9f72ebe3e083582bb'] = '(Vide)'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b7d496eedb665d0b5f589f2f874e7cb'] = 'Voir la fiche produit'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_3d9e3bae9905a12dae384918ed117a26'] = 'Personnalisation #% d:'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_09dc02ecbb078868a3a86dded030076d'] = 'Aucun produit'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ea9cf7e47ff33b2be14e6dd07cbcefc6'] = 'Transport maritime'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_ba794350deb07c0c96fe73bd12239059'] = 'Emballage'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_4b78ac8eb158840e9638a3aeb26c4a9d'] = 'Impôt'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_96b0141273eabab320119c467cdcaf17'] = 'Total'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_0d11c2b75cf03522c8d97938490466b2'] = 'Les prix sont TTC'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_41202aa6b8cf7ae885644717dab1e8b4'] = 'Les prix sont HT'; $_MODULE['<{blockcart}touchmenot1.0.3>blockcart_377e99e7404b414341a9621f7fb3f906'] = 'Commander'; <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class AdminPowaTagLogsController extends ModuleAdminController { public function __construct() { $this->table = 'powatag_logs'; $this->className = 'PowaTagLogs'; $this->lang = false; $this->_select = null; //If needed you can add informations to select issued from other databases $this->_join = null; //Join the databases here parent::__construct(); $this->fields_list = array( 'subject' => array( 'title' => $this->l('Subject'), 'width' => 120, ), 'status' => array( 'title' => $this->l('Status'), 'width' => 120, ), 'message' => array( 'title' => $this->l('Message'), 'width' => 120, ), 'date_add' => array( 'title' => $this->l('Date'), 'width' => 120, 'type' => 'datetime', ), ); $this->bootstrap = true; $this->fieldImageSettings = array( ); $this->list_no_link = true; } public static function install($menu_id, $module_name, $lang_id, $module) { $tab = new Tab(); $tab->name[$lang_id] = $module->l('Logs'); $tab->class_name = 'AdminPowaTagLogs'; $tab->module = $module_name; $tab->id_parent = $menu_id; if(!$tab->save()) { return false; } return true; } public function renderList() { $this->toolbar_btn = $this->module->initToolbar(); return parent::renderList(); } private function getSelectedCategories($name) { return array($this->object->{$name}); } private function getRootCategory() { $root_category = Category::getRootCategory(); $root_category = array('id_category' => $root_category->id, 'name' => $root_category->name); return $root_category; } public function initPageHeaderToolbar() { $this->page_header_toolbar_btn = $this->module->initToolbar(); parent::initPageHeaderToolbar(); } } <file_sep><?php /** * 2007-2014 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class PrediggoConfig { public $categoryPageName = 'category'; public $manufacturerPageName = 'manufacturer'; public $attNameCategory = 'genre'; public $attNameManufacturer = 'supplierid'; public $optionsHooksHomePage = array ( array( 'id_option' => 'displayHome', 'name' => 'Hook: displayHome - Called at the center of the homepage' ), array( 'id_option' => 'displayOrderConfirmation', 'name' => 'Hook: displayOrderConfirmation - This hook is called on order confirmation page.' ), ); public $optionsHooksAllPage = array ( array( 'id_option' => 'displayHeader', 'name' => 'Hook: displayHeader - Called within the HTML <head> tags. Ideal location for adding JavaScript and CSS files.' ), array( 'id_option' => 'displayTop', 'name' => 'Hook: displayTop - Called in the page\'s header.' ), array( 'id_option' => 'displayLeftColumn', 'name' => 'Hook: displayLeftColumn - Called when loading the left column.' ), array( 'id_option' => 'displayRightColumn', 'name' => 'Hook: displayRightColumn - Called when loading the right column.' ), array( 'id_option' => 'displayFooter', 'name' => 'Hook: displayFooter - Called in the page\'s footer.' ), ); public $optionsHooksBlocklayeredPage = array ( array( 'id_option' => 'displayHeader', 'name' => 'Hook: displayHeader - Called within the HTML <head> tags. Ideal location for adding JavaScript and CSS files.' ), array( 'id_option' => 'displayTop', 'name' => 'Hook: displayTop - Called in the page\'s header.' ), array( 'id_option' => 'displayLeftColumn', 'name' => 'Hook: displayLeftColumn - Called when loading the left column.' ), array( 'id_option' => 'displayRightColumn', 'name' => 'Hook: displayRightColumn - Called when loading the right column.' ), array( 'id_option' => 'displayFooter', 'name' => 'Hook: displayFooter - Called in the page\'s footer.' ), ); public $optionsHooksProductPage = array ( array( 'id_option' => 'displayLeftColumnProduct', 'name' => 'Hook: displayLeftColumnProduct - Called right before the "Print" link, under the picture.' ), array( 'id_option' => 'displayRightColumnProduct', 'name' => 'Hook: displayRightColumnProduct - Called right after the block for the "Add to Cart" button.' ), array( 'id_option' => 'displayProductButtons', 'name' => 'Hook: displayProductButtons - Called inside the block for the "Add to Cart" button, right after that button.' ), array( 'id_option' => 'actionProductOutOfStock', 'name' => 'Hook: actionProductOutOfStock - Called inside the block for the "Add to Cart" button, right after the "Availability" information.' ), array( 'id_option' => 'displayFooterProduct', 'name' => 'Hook: displayFooterProduct - Called right before the tabs.' ), array( 'id_option' => 'displayProductTab', 'name' => 'Hook: displayProductTab - Called in tabs list, such as "More info", "Data sheet", "Accessories", etc.' ), array( 'id_option' => 'displayProductTabContent', 'name' => 'Hook: displayProductTabContent - Called when a tab is clicked.' ), ); public $optionsHooksBasketPage = array ( array( 'id_option' => 'displayShoppingCart', 'name' => 'Hook: displayShoppingCart - Called after the cart\'s table of items, right above the navigation buttons.' ), array( 'id_option' => 'displayShoppingCartFooter', 'name' => 'Hook: displayShoppingCartFooter - Called right below the cart items table.' ), array( 'id_option' => 'displayOrderDetail', 'name' => 'Hook: displayOrderDetail - Displayed on order detail on front office.' ), array( 'id_option' => 'displayBeforeCarrier', 'name' => 'Hook: displayBeforeCarrier - This hook is display before the carrier list on Front office.' ), array( 'id_option' => 'displayCarrierList', 'name' => 'Hook: displayCarrierList - This hook is display during the carrier list on Front office.' ), ); public $optionsHooksCategoryPage = array ( array( 'id_option' => 'displayHeadercategory', 'name' => 'Hook: displayHeaderCategory - Called within the HTML <head> tags. Ideal location for adding JavaScript and CSS files.' ), array( 'id_option' => 'displayTopcategory', 'name' => 'Hook: displayTopCategory - Called in the page\'s header on a category page, before the displayTop hook.' ), array( 'id_option' => 'displayLeftColumncategory', 'name' => 'Hook: displayLeftColumnCategory - Called when loading the left column on a category page, before the displayLeftColumn hook.' ), array( 'id_option' => 'displayRightColumncategory', 'name' => 'Hook: displayRightColumnCategory - Called when loading the right column on a category page, before the displayRightColumn hook.' ), array( 'id_option' => 'displayFootercategory', 'name' => 'Hook: displayFooterCategory - Called in the page\'s footer on a category page, before the displayFooter hook.' ), array( 'id_option' => 'displayHeadermanufacturer', 'name' => 'Hook: displayHeaderManufacturer - Called within the HTML <head> tags on a manufacturer page. Ideal location for adding JavaScript and CSS files.' ), array( 'id_option' => 'displayTopmanufacturer', 'name' => 'Hook: displayTopManufacturer - Called in the page\'s header on a manufacturer page, before the displayTop hook.' ), array( 'id_option' => 'displayLeftColumnmanufacturer', 'name' => 'Hook: displayLeftColumnManufacturer - Called when loading the left column on a manufacturer page, before the displayLeftColumn hook.' ), array( 'id_option' => 'displayRightColumnmanufacturer', 'name' => 'Hook: displayRightColumnManufacturer - Called when loading the right column on a manufacturer page, before the displayRightColumn hook.' ), array( 'id_option' => 'displayFootermanufacturer', 'name' => 'Hook: displayFooterManufacturer - Called in the page\'s footer on a manufacturer page, before the displayFooter hook.' ), ); public $optionsHooksCustomerPage = array ( array( 'id_option' => 'displayCustomerAccount', 'name' => 'Hook: displayCustomerAccount - Called on the client account homepage, after the list of available links. Ideal location to add a link to this list.' ), array( 'id_option' => 'displayMyAccountBlock', 'name' => 'Hook: displayMyAccountBlock - Called within the "My account" block, in the left column, below the list of available links. This is the ideal location to add a link to this list.' ), array( 'id_option' => 'displayMyAccountBlockfooter', 'name' => 'Hook: displayMyAccountBlockfooter - Displays extra information inside the "My account" block.' ), ); /** @var ImportConfig Singleton Object */ private static $instance; /** @var Context Singleton Object */ private $oContext; /** @var array list of configuration variables */ private $aConfs = array( 'web_site_id' => array( 'name' => 'PREDIGGO_WEB_SITE_ID', 'type' => 'text', 'val' => 'web_site_ID', 'multilang' => false, 'multishopgroup' => false, 'multishop' => false, ), 'web_site_id_checked' => array( 'name' => 'PREDIGGO_WEB_SITE_ID_CHECKED', 'type' => 'int', 'val' => '0', 'multilang' => false, 'multishopgroup' => false, 'multishop' => false, ), 'shop_name' => array( 'name' => 'PREDIGGO_SHOP_NAME', 'type' => 'text', 'val' => 'Shop_name', 'multilang' => false, 'multishopgroup' => false, 'multishop' => false, ), 'token_id' => array( 'name' => 'PREDIGGO_TOKEN_ID', 'type' => 'text', 'val' => 'Token_ID', 'multilang' => false, 'multishopgroup' => false, 'multishop' => false, ), 'server_url_recommendations' => array( 'name' => 'PREDIGGO_SERVER_URL_RECO', 'type' => 'text', 'val' => 'http://monshop.prediggo.com', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_recommendations' => array( 'name' => 'PREDIGGO_HOME_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'product_recommendations' => array( 'name' => 'PREDIGGO_PRODUCT_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_recommendations' => array( 'name' => 'PREDIGGO_CATEGORY_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'blocklayered_recommendations' => array( 'name' => 'PREDIGGO_LAYERED_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'gateway_profil_id' => array( 'name' => 'PREDIGGO_PROFIL_ID', 'type' => 'text', 'val' => 'Profil_ID', 'multilang' => false, 'multishopgroup' => false, 'multishop' => false, ), 'server_url_check' => array( 'name' => 'PREDIGGO_SERVER_URL_CHECK', 'type' => 'text', 'val' => 'http://www.prediggo.com/prestakeys/', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), /* EXPORT CONFIGURATION */ /* The FG Corresponds to FILE_GENERATION */ 'products_file_generation' => array( 'name' => 'PREDIGGO_PRODUCTS_FG', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'orders_file_generation' => array( 'name' => 'PREDIGGO_ORDERS_FG', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customers_file_generation' => array( 'name' => 'PREDIGGO_CUSTOMERS_FG', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'export_product_image' => array( 'name' => 'PREDIGGO_EXPORT_PRODUCT_IMG', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'export_product_description' => array( 'name' => 'PREDIGGO_EXPORT_PRODUCT_DESC', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'export_product_active' => array( 'name' => 'PREDIGGO_EXPORT_PRODUCT_ACTIVE', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'export_product_price' => array( 'name' => 'PREDIGGO_EXPORT_PRODUCT_PRICE', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'export_product_min_quantity' => array( 'name' => 'PREDIGGO_EXPORT_PRODUCT_MIN_QTY', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'nb_days_order_valide' => array( 'name' => 'PREDIGGO_NB_DAYS_ORDER', 'type' => 'int', 'val' => 180, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'nb_days_customer_last_visit_valide' => array( 'name' => 'PREDIGGO_NB_DAYS_CUSTOMER', 'type' => 'int', 'val' => 180, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'attributes_groups_ids' => array( 'name' => 'PREDIGGO_ATTRIBUTES_GROUPS_IDS', 'type' => 'array', 'val' => '', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'features_ids' => array( 'name' => 'PREDIGGO_FEATURES_IDS', 'type' => 'array', 'val' => '', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'products_ids_not_recommendable' => array( 'name' => 'PREDIGGO_PRODUCTS_NOT_RECO', 'type' => 'array', 'val' => '', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'products_ids_not_searchable' => array( 'name' => 'PREDIGGO_PRODUCTS_NOT_SEARCH', 'type' => 'array', 'val' => '', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), /* PROTECTION CONFIGURATION */ 'htpasswd_user' => array( 'name' => 'PREDIGGO_HTPASSWD_USER', 'type' => 'text', 'val' => 'user', 'multilang' => false, 'multishopgroup' => false, 'multishop' => false, ), 'htpasswd_pwd' => array( 'name' => 'PREDIGGO_<PASSWORD>', 'type' => 'text', 'val' => 'pwd', 'multilang' => false, 'multishopgroup' => false, 'multishop' => false, ), /* LOG CONFIGURATION */ 'logs_generation' => array( 'name' => 'PREDIGGO_LOGS', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), /*'logs_reco_file_generation' => array( 'name' => 'PREDIGGO_RECO_LOGS', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'logs_search_file_generation' => array( 'name' => 'PREDIGGO_SEARCH_LOGS_FG', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'logs_file_generation' => array( 'name' => 'PREDIGGO_LOGS_FG', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => false, ),*/ /* RECOMMENDATIONS CONFIGURATION */ 'hook_left_column' => array( 'name' => 'PREDIGGO_HOOK_LEFT_C', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_right_column' => array( 'name' => 'PREDIGGO_HOOK_RIGHT_C', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_footer' => array( 'name' => 'PREDIGGO_HOOK_HEADER_FOOTER', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_home' => array( 'name' => 'PREDIGGO_HOOK_HOME', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_footer_product' => array( 'name' => 'PREDIGGO_HOOK_FOOT_PROD', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_left_column_product' => array( 'name' => 'PREDIGGO_HOOK_LEFT_C_PROD', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_right_column_product' => array( 'name' => 'PREDIGGO_HOOK_RIGHT_C_PROD', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_shopping_cart_footer' => array( 'name' => 'PREDIGGO_HOOK_SHOP_CART_FOOT', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_shopping_cart' => array( 'name' => 'PREDIGGO_HOOK_SHOP_CART', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_order_detail' => array( 'name' => 'PREDIGGO_HOOK_ORDER_DET', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_product_tab' => array( 'name' => 'PREDIGGO_HOOK_PROD_TAB', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_before_carrier' => array( 'name' => 'PREDIGGO_HOOK_BEF_CAR', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'hook_carrier_list' => array( 'name' => 'PREDIGGO_HOOK_CAR_LIST', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), /* HOME PAGE CONFIGURATION - Block 0*/ 'home_0_activated' => array( 'name' => 'PREDIGGO_HOME_0_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_0_nb_items' => array( 'name' => 'PREDIGGO_HOME_0_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_0_variant_id' => array( 'name' => 'PREDIGGO_HOME_0_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_0_hook_name' => array( 'name' => 'PREDIGGO_HOME_0_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_0_template_name' => array( 'name' => 'PREDIGGO_HOME_0_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_0_block_label' => array( 'name' => 'PREDIGGO_HOME_0_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* HOME PAGE CONFIGURATION - Block 1*/ 'home_1_activated' => array( 'name' => 'PREDIGGO_HOME_1_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_1_nb_items' => array( 'name' => 'PREDIGGO_HOME_1_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_1_variant_id' => array( 'name' => 'PREDIGGO_HOME_1_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_1_hook_name' => array( 'name' => 'PREDIGGO_HOME_1_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_1_template_name' => array( 'name' => 'PREDIGGO_HOME_1_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_1_block_label' => array( 'name' => 'PREDIGGO_HOME_1_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* ALL PAGE CONFIGURATION - Block 0 */ 'allpage_0_activated' => array( 'name' => 'PREDIGGO_ALLPAGE_0_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_0_nb_items' => array( 'name' => 'PREDIGGO_ALLPAGE_0_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_0_variant_id' => array( 'name' => 'PREDIGGO_ALLPAGE_0_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_0_hook_name' => array( 'name' => 'PREDIGGO_ALLPAGE_0_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_0_template_name' => array( 'name' => 'PREDIGGO_ALLPAGE_0_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_0_block_label' => array( 'name' => 'PREDIGGO_ALLPAGE_0_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* ALL PAGE CONFIGURATION - Block 0 */ 'allpage_1_activated' => array( 'name' => 'PREDIGGO_ALLPAGE_1_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_1_nb_items' => array( 'name' => 'PREDIGGO_ALLPAGE_1_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_1_variant_id' => array( 'name' => 'PREDIGGO_ALLPAGE_1_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_1_hook_name' => array( 'name' => 'PREDIGGO_ALLPAGE_1_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_1_template_name' => array( 'name' => 'PREDIGGO_ALLPAGE_1_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_1_block_label' => array( 'name' => 'PREDIGGO_ALLPAGE_1_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* ALL PAGE CONFIGURATION - Block 2*/ 'allpage_2_activated' => array( 'name' => 'PREDIGGO_ALLPAGE2_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_2_nb_items' => array( 'name' => 'PREDIGGO_ALLPAGE_2_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_2_variant_id' => array( 'name' => 'PREDIGGO_ALLPAGE_2_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_2_hook_name' => array( 'name' => 'PREDIGGO_ALLPAGE_2_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_2_template_name' => array( 'name' => 'PREDIGGO_ALLPAGE_2_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'allpage_2_block_label' => array( 'name' => 'PREDIGGO_ALLPAGE_2_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* PRODUCT PAGE CONFIGURATION - Block 0*/ 'productpage_0_activated' => array( 'name' => 'PREDIGGO_PRODPG_0_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_0_nb_items' => array( 'name' => 'PREDIGGO_PRODPG_0_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_0_variant_id' => array( 'name' => 'PREDIGGO_PRODPG_0_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_0_hook_name' => array( 'name' => 'PREDIGGO_PRODPG_0_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_0_template_name' => array( 'name' => 'PREDIGGO_PRODPG_0_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_0_block_label' => array( 'name' => 'PREDIGGO_PRODPG_0_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* PRODUCT PAGE CONFIGURATION - Block 1*/ 'productpage_1_activated' => array( 'name' => 'PREDIGGO_PRODPG_1_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_1_nb_items' => array( 'name' => 'PREDIGGO_PRODPG_1_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_1_variant_id' => array( 'name' => 'PREDIGGO_PRODPG_1_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_1_hook_name' => array( 'name' => 'PREDIGGO_PRODPG_1_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_1_template_name' => array( 'name' => 'PREDIGGO_PRODPG_1_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_1_block_label' => array( 'name' => 'PREDIGGO_PRODPG_1_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* PRODUCT PAGE CONFIGURATION - Block 2*/ 'productpage_2_activated' => array( 'name' => 'PREDIGGO_PRODPG_2_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_2_nb_items' => array( 'name' => 'PREDIGGO_PRODPG_2_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_2_variant_id' => array( 'name' => 'PREDIGGO_PRODPG_2_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_2_hook_name' => array( 'name' => 'PREDIGGO_PRODPG_2_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_2_template_name' => array( 'name' => 'PREDIGGO_PRODPG_2_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'productpage_2_block_label' => array( 'name' => 'PREDIGGO_PRODPG_2_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* BASKET PAGE CONFIGURATION - Block 0*/ 'basket_0_activated' => array( 'name' => 'PREDIGGO_BASKET_0_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_0_nb_items' => array( 'name' => 'PREDIGGO_BASKET_0_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_0_variant_id' => array( 'name' => 'PREDIGGO_BASKET_0_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_0_hook_name' => array( 'name' => 'PREDIGGO_BASKET_0_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_0_template_name' => array( 'name' => 'PREDIGGO_BASKET_0_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_0_block_label' => array( 'name' => 'PREDIGGO_BASKET_0_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* HOME PAGE CONFIGURATION - Block 1*/ 'basket_1_activated' => array( 'name' => 'PREDIGGO_BASKET_1_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_1_nb_items' => array( 'name' => 'PREDIGGO_BASKET_1_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_1_variant_id' => array( 'name' => 'PREDIGGO_BASKET_1_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_1_hook_name' => array( 'name' => 'PREDIGGO_BASKET_1_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_1_template_name' => array( 'name' => 'PREDIGGO_BASKET_1_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_1_block_label' => array( 'name' => 'PREDIGGO_BASKET_1_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* BASKET PAGE CONFIGURATION - Block 2*/ 'basket_2_activated' => array( 'name' => 'PREDIGGO_BASKET_2_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_2_nb_items' => array( 'name' => 'PREDIGGO_BASKET_2_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_2_variant_id' => array( 'name' => 'PREDIGGO_BASKET_2_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_2_hook_name' => array( 'name' => 'PREDIGGO_BASKET_2_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_2_template_name' => array( 'name' => 'PREDIGGO_BASKET_2_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_2_block_label' => array( 'name' => 'PREDIGGO_BASKET_2_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* HOME PAGE CONFIGURATION - Block 3*/ 'basket_3_activated' => array( 'name' => 'PREDIGGO_BASKET_3_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_3_nb_items' => array( 'name' => 'PREDIGGO_BASKET_3_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_3_variant_id' => array( 'name' => 'PREDIGGO_BASKET_3_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_3_hook_name' => array( 'name' => 'PREDIGGO_BASKET_3_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_3_template_name' => array( 'name' => 'PREDIGGO_BASKET_3_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_3_block_label' => array( 'name' => 'PREDIGGO_BASKET_3_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* BASKET PAGE CONFIGURATION - Block 4*/ 'basket_4_activated' => array( 'name' => 'PREDIGGO_BASKET_4_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_4_nb_items' => array( 'name' => 'PREDIGGO_BASKET_4_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_4_variant_id' => array( 'name' => 'PREDIGGO_BASKET_4_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_4_hook_name' => array( 'name' => 'PREDIGGO_BASKET_4_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_4_template_name' => array( 'name' => 'PREDIGGO_BASKET_4_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_4_block_label' => array( 'name' => 'PREDIGGO_BASKET_4_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* HOME PAGE CONFIGURATION - Block 5*/ 'basket_5_activated' => array( 'name' => 'PREDIGGO_BASKET_5_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_5_nb_items' => array( 'name' => 'PREDIGGO_BASKET_5_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_5_variant_id' => array( 'name' => 'PREDIGGO_BASKET_5_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_5_hook_name' => array( 'name' => 'PREDIGGO_BASKET_5_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_5_template_name' => array( 'name' => 'PREDIGGO_BASKET_5_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'basket_5_block_label' => array( 'name' => 'PREDIGGO_BASKET_5_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* CATEGORY PAGE CONFIGURATION - Block 0 */ 'category_0_activated' => array( 'name' => 'PREDIGGO_CATPG_0_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_0_nb_items' => array( 'name' => 'PREDIGGO_CATPG_0_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_0_variant_id' => array( 'name' => 'PREDIGGO_CATPG_0_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_0_hook_name' => array( 'name' => 'PREDIGGO_CATPG_0_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_0_template_name' => array( 'name' => 'PREDIGGO_CATPG_0_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_0_block_label' => array( 'name' => 'PREDIGGO_CATPG_0_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* CATEGORY PAGE CONFIGURATION - Block 0 */ 'category_1_activated' => array( 'name' => 'PREDIGGO_CATPG_1_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_1_nb_items' => array( 'name' => 'PREDIGGO_CATPG_1_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_1_variant_id' => array( 'name' => 'PREDIGGO_CATPG_1_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_1_hook_name' => array( 'name' => 'PREDIGGO_CATPG_1_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_1_template_name' => array( 'name' => 'PREDIGGO_CATPG_1_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_1_block_label' => array( 'name' => 'PREDIGGO_CATPG_1_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* CATEGORY PAGE CONFIGURATION - Block 2*/ 'category_2_activated' => array( 'name' => 'PREDIGGO_ALLPAGE2_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_2_nb_items' => array( 'name' => 'PREDIGGO_CATPG_2_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_2_variant_id' => array( 'name' => 'PREDIGGO_CATPG_2_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_2_hook_name' => array( 'name' => 'PREDIGGO_CATPG_2_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_2_template_name' => array( 'name' => 'PREDIGGO_CATPG_2_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_2_block_label' => array( 'name' => 'PREDIGGO_CATPG_2_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* CUSTOMER PAGE CONFIGURATION - Block 0 */ 'customer_0_activated' => array( 'name' => 'PREDIGGO_CUST_0_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_0_nb_items' => array( 'name' => 'PREDIGGO_CUST_0_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_0_variant_id' => array( 'name' => 'PREDIGGO_CUST_0_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_0_hook_name' => array( 'name' => 'PREDIGGO_CUST_0_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_0_template_name' => array( 'name' => 'PREDIGGO_CUST_0_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_0_block_label' => array( 'name' => 'PREDIGGO_CUST_0_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* CUSTOMER PAGE CONFIGURATION - Block 1 */ 'customer_1_activated' => array( 'name' => 'PREDIGGO_CUST_1_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_1_nb_items' => array( 'name' => 'PREDIGGO_CUST_1_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_1_variant_id' => array( 'name' => 'PREDIGGO_CUST_1_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_1_hook_name' => array( 'name' => 'PREDIGGO_CUST_1_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_1_template_name' => array( 'name' => 'PREDIGGO_CUST_1_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_1_block_label' => array( 'name' => 'PREDIGGO_CUST_1_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* CUSTOMER PAGE CONFIGURATION - Block 2 */ 'customer_2_activated' => array( 'name' => 'PREDIGGO_CUST_2_ACTIVATED', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_2_nb_items' => array( 'name' => 'PREDIGGO_CUST_2_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_2_variant_id' => array( 'name' => 'PREDIGGO_CUST_2_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_2_hook_name' => array( 'name' => 'PREDIGGO_CUST_2_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_2_template_name' => array( 'name' => 'PREDIGGO_CUST_2_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_2_block_label' => array( 'name' => 'PREDIGGO_CUST_2_BLOCK_LABEL', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), 'home_footer_recommendations' => array( 'name' => 'PREDIGGO_HOME_FOOTER_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_footer_nb_items' => array( 'name' => 'PREDIGGO_HOME_FOOTER_NB_RECO', 'type' => 'int', 'val' => 5, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'home_sales_block_title' => array( 'name' => 'PREDIGGO_HOME_SALES_BLOCK_TITLE', 'type' => 'html', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), 'home_views_block_title' => array( 'name' => 'PREDIGGO_HOME_VIEWS_BLOCK_TITLE', 'type' => 'html', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), 'error_recommendations' => array( 'name' => 'PREDIGGO_ERROR_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'error_nb_items' => array( 'name' => 'PREDIGGO_ERROR_NB_RECO', 'type' => 'int', 'val' => 6, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'error_block_title' => array( 'name' => 'PREDIGGO_ERROR_BLOCK_TITLE', 'type' => 'text', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), 'customer_recommendations' => array( 'name' => 'PREDIGGO_CUSTOMER_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_nb_items' => array( 'name' => 'PREDIGGO_CUSTOMER_NB_RECO', 'type' => 'int', 'val' => 6, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'customer_block_title' => array( 'name' => 'PREDIGGO_CUSTOMER_BLOCK_TITLE', 'type' => 'text', 'val' => 0, 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), 'cart_recommendations' => array( 'name' => 'PREDIGGO_CART_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'cart_nb_items' => array( 'name' => 'PREDIGGO_CART_NB_RECO', 'type' => 'int', 'val' => 6, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'cart_block_title' => array( 'name' => 'PREDIGGO_CART_BLOCK_TITLE', 'type' => 'text', 'val' => 0, 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), 'best_sales_recommendations' => array( 'name' => 'PREDIGGO_BEST_SALES_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'best_sales_nb_items' => array( 'name' => 'PREDIGGO_BEST_SALES_NB_RECO', 'type' => 'int', 'val' => 6, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'best_sales_block_title' => array( 'name' => 'PREDIGGO_BEST_SALES_BLOCK_TITLE', 'type' => 'text', 'val' => 0, 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), 'blocklayered_0_recommendations' => array( 'name' => 'PREDIGGO_LAY_0_RECO', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'blocklayered_0_nb_items' => array( 'name' => 'PREDIGGO_LAY_0_NB_RECO', 'type' => 'int', 'val' => 3, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'blocklayered_0_variant_id' => array( 'name' => 'PREDIGGO_LAY_0_VARIANT_ID', 'type' => 'int', 'val' => 0, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'blocklayered_0_block_title' => array( 'name' => 'PREDIGGO_LAY_0_BLOCK_TITLE', 'type' => 'text', 'val' => 0, 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), 'blocklayered_0_hook_name' => array( 'name' => 'PREDIGGO_LAY_0_HOOK_NAME', 'type' => 'select', 'val' => array(1 => 'Prediggo', 2 => 'Prediggo', 3 => 'Prediggo', 4 => 'Prediggo', 5 => 'Prediggo'), 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'blocklayered_0_template_name' => array( 'name' => 'PREDIGGO_LAY_0_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'list_recommendations.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), /* SEARCHS CONFIGURATION */ 'search_active' => array( 'name' => 'PREDIGGO_SEARCH_ACTIVE', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'search_nb_items' => array( 'name' => 'PREDIGGO_SEARCH_NB_ITEMS', 'type' => 'int', 'val' => 10, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'search_nb_min_chars' => array( 'name' => 'PREDIGGO_SEARCH_NB_MIN_CHARS', 'type' => 'int', 'val' => 3, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'pagination_template_name' => array( 'name' => 'PREDIGGO_PAGI_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'pagination.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'search_filters_sort_by_template_name' => array( 'name' => 'PREDIGGO_SFSB_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'search_filters_sort_by.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'search_filter_block_template_name' => array( 'name' => 'PREDIGGO_SFB_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'search_filters_block.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'prod_compare_template_name' => array( 'name' => 'PREDIGGO_PCOMP_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'product_compare.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'prod_list_template_name' => array( 'name' => 'PREDIGGO_PLIST_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'product-list.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'searchandizing_active' => array( 'name' => 'PREDIGGO_SEARCHANDIZING_ACTIVE', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'layered_navigation_active' => array( 'name' => 'PREDIGGO_LAYERED_NAV_ACTIVE', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'autocompletion_active' => array( 'name' => 'PREDIGGO_AUTOCOMPLETION_ACTIVE', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'autocompletion_nb_items' => array( 'name' => 'PREDIGGO_AUTOCOMPLETION_NB_ITEMS', 'type' => 'int', 'val' => 6, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'search_0_template_name' => array( 'name' => 'PREDIGGO_SERCH_0_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'search_block.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'search_main_template_name' => array( 'name' => 'PREDIGGO_SCHMAIN_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'search.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'autoc_template_name' => array( 'name' => 'PREDIGGO_AUTOC_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'autocomplete_dum.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'autop_template_name' => array( 'name' => 'PREDIGGO_AUTOP_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'autocomplete_product.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'autos_template_name' => array( 'name' => 'PREDIGGO_AUTOS_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'autocomplete_suggest.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'autocat_template_name' => array( 'name' => 'PREDIGGO_AUTOCAT_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'autocomplete_attributes.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'suggest_active' => array( 'name' => 'PREDIGGO_SUGGEST_ACTIVE', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'suggest_words' => array( 'name' => 'PREDIGGO_SUGGEST_WORDS', 'type' => 'text', 'val' => array(1 => 'iPad 2, iPhone 4S, iPhone', 2 => 'iPad 2, iPhone 4S, iPhone', 3 => 'iPad 2, iPhone 4S, iPhone', 4 => 'iPad 2, iPhone 4S, iPhone', 5 => 'iPad 2, iPhone 4S, iPhone'), 'multilang' => true, 'multishopgroup' => false, 'multishop' => true, ), /* Category */ 'category_active' => array( 'name' => 'PREDIGGO_CAT_ACTIVE', 'type' => 'int', 'val' => 1, 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), 'category_0_template_name' => array( 'name' => 'PREDIGGO_CAT_0_TEMPLATE_NAME', 'type' => 'text', 'size' => 100, 'val' => 'category.tpl', 'multilang' => false, 'multishopgroup' => false, 'multishop' => true, ), ); /** * Initialise the object variables * */ public function __construct($oContext = false) { if (is_object($oContext) && get_class($oContext) == 'Context') $this->oContext = $oContext; $aLanguages = Language::getLanguages(false); foreach ($this->aConfs as $var => $aConf) { $aParams = array( 0 => $aConf['name'], 1 => false, 2 => false, 3 => false, ); if ($this->oContext) { if ((int)$aConf['multishopgroup']) $aParams[2] = (int)$this->oContext->shop->id_shop_group; if ((int)$aConf['multishop']) $aParams[3] = (int)$this->oContext->shop->id; } switch ($aConf['type']) { case 'int' : $this->{$var} = (int)call_user_func_array(array('Configuration', 'get'), $aParams); break; default : if ($this->oContext && (int)$aConf['multilang']) { // Set the multilingual configurations foreach ($aLanguages as $aLanguage) { $aParams[1] = (int)$aLanguage['id_lang']; $this->{$var}[(int)$aLanguage['id_lang']] = pSQL(call_user_func_array(array('Configuration', 'get'), $aParams)); } } else $this->{$var} = pSQL(call_user_func_array(array('Configuration', 'get'), $aParams)); break; } } } /** * Set the Import Configuration vars, executed by the main module object once its installation * * @return bool success or false */ public function install() { foreach ($this->aConfs as $aConf) { $aParams = array( 0 => $aConf['name'], 1 => $aConf['val'], 2 => false, 3 => false, 4 => false, ); if ($this->oContext) { if ((int)$aConf['multishopgroup']) $aParams[3] = (int)$this->oContext->shop->id_shop_group; if ((int)$aConf['multishop']) $aParams[4] = (int)$this->oContext->shop->id; } if (!call_user_func_array(array('Configuration', 'updateValue'), $aParams)) return false; } return true; } /** * Delete the Import Configuration vars, executed by the main module object once its uninstallation * * @return bool success or false */ public function uninstall() { foreach ($this->aConfs as $aConf) if (!Configuration::deleteByName($aConf['name'])) return false; return true; } /** * Update the Import Configuration vars, executed by the main module object once its uninstallation * * @return bool success or false */ public function save() { foreach ($this->aConfs as $var => $aConf) { $aParams = array( 0 => $aConf['name'], 1 => $this->{$var}, 2 => $aConf['type'] == 'html' ? true : false, 3 => false, 4 => false, ); if ($this->oContext) { if ((int)$aConf['multishopgroup']) $aParams[3] = (int)$this->oContext->shop->id_shop_group; if ((int)$aConf['multishop']) $aParams[4] = (int)$this->oContext->shop->id; } switch ($aConf['type']) { case 'int' : $aParams[1] = (int)$this->{$var}; if (!call_user_func_array(array('Configuration', 'updateValue'), $aParams)) return false; break; default : if (!call_user_func_array(array('Configuration', 'updateValue'), $aParams)) return false; break; } } return true; } public function getContext() { return $this->oContext; } public function imgType() { return (Tools::version_compare(_PS_VERSION_, '1.5', '>=')?'home_default':'home'); } }<file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractProductAuctionMailingItem', false)) return; abstract class AbstractProductAuctionMailingItem extends AbstractProductAuctionObjectItem { protected $frontoffice_templates = array( ProductAuctionMailing::TEMPLATE_FRONTOFFICE_ACCEPT, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_LEADER, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NEW_OFFER, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NOT_WON, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_OUTBID, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_REMIND, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_RESTART, ProductAuctionMailing::TEMPLATE_FRONTOFFICE_WON ); protected $backoffice_templates = array( ProductAuctionMailing::TEMPLATE_BACKOFFICE_NEW_OFFER, ProductAuctionMailing::TEMPLATE_BACKOFFICE_FINISHED ); /** * * @var AbstractProductAuctionPermissions */ protected $permissions; /** * * @return AbstractProductAuctionPermissions */ public function getPermissions($type) { if ($this->permissions) $this->permissions->setType($type); return $this->permissions; } /** * * @param AbstractProductAuctionPermissions $permissions */ public function setPermissions(AbstractProductAuctionPermissions $permissions) { $this->permissions = $permissions; } /** * * @return ProductCore */ public function getProduct() { return $this->getObjectModel()->product; } public function getTemplate() { switch ($this->getObjectModel()->template) { case ProductAuctionMailing::TEMPLATE_BACKOFFICE_FINISHED: return 'backoffice_finished'; case ProductAuctionMailing::TEMPLATE_BACKOFFICE_NEW_OFFER: return 'backoffice_new_offer'; case ProductAuctionMailing::TEMPLATE_FRONTOFFICE_LEADER: return 'customer_leader'; case ProductAuctionMailing::TEMPLATE_FRONTOFFICE_OUTBID: return 'customer_outbid'; case ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NEW_OFFER: return 'customer_new_offer'; case ProductAuctionMailing::TEMPLATE_FRONTOFFICE_WON: return 'customer_won'; case ProductAuctionMailing::TEMPLATE_FRONTOFFICE_NOT_WON: return 'customer_not_won'; case ProductAuctionMailing::TEMPLATE_FRONTOFFICE_FINISHED: return 'customer_finished'; case ProductAuctionMailing::TEMPLATE_FRONTOFFICE_ACCEPT: return 'customer_accept'; case ProductAuctionMailing::TEMPLATE_FRONTOFFICE_REMIND: return 'customer_remind'; case ProductAuctionMailing::TEMPLATE_FRONTOFFICE_RESTART: return 'customer_restart'; } return null; } public function getValidLanguageId(Auctions $module) { if ($this->hasTemplate($module, $this->getLanguageIso())) return $this->getLanguageId(); if ($this->hasTemplate($module, $this->getEnglishLanguageIso())) return $this->getEnglishLanguageId(); return null; } public function getLanguageId() { return (int)$this->getObjectModel()->language->id; } public function getLanguageIso() { return $this->getObjectModel()->language->iso_code; } public function getEnglishLanguageId() { $english_language_id = Language::getIdByIso($this->getEnglishLanguageIso()); return !empty($english_language_id) ? (int)$english_language_id : null; } public function getEnglishLanguageIso() { return 'en'; } public function getMailDir(Auctions $module) { return $module->getLocalPath().'mails/'; } public function getTemplatePath(Auctions $module, $language_iso) { return $this->getMailDir($module).$language_iso.DIRECTORY_SEPARATOR; } public function hasTemplate(Auctions $module, $language_iso) { $template_name = $this->getTemplate(); $template_path = $this->getTemplatePath($module, $language_iso); return file_exists("{$template_path}{$template_name}.txt") && file_exists("{$template_path}{$template_name}.txt"); } public function canSend(Auctions $module) { return $this->hasTemplate($module, $this->getLanguageIso()) || $this->hasTemplate($module, $this->getEnglishLanguageIso()); } public function getRecipientEmail() { return $this->getObjectModel()->recipient_email; } public function getRecipientName() { return $this->getObjectModel()->recipient_name; } public function getSenderEmail() { return $this->getObjectModel()->sender_email; } public function getSenderName() { return $this->getObjectModel()->sender_name; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (!class_exists('CoreModuleEventDispatcher', false)) { class CoreModuleEventDispatcher { protected $event_listeners = array(); /** * * @param string $event * @param CoreModuleEventCallback $callback */ public function listen($event, CoreModuleEventCallback $callback) { $this->event_listeners[$event][] = $callback; } /** * * @param CoreModuleEventListenerInterface $listener */ public function register(CoreModuleEventListenerInterface $listener) { $events = $listener->getEvents(); foreach ($events as $event => $callback) $this->listen($event, $this->getCallback($listener, $callback)); } /** * * @param CoreModuleEventInterface $event */ public function dispatch(CoreModuleEventInterface $event) { $event_name = $event->getEvent(); if (!empty($this->event_listeners[$event_name])) foreach ($this->event_listeners[$event_name] as $callback) $callback->call($event); } public function clear() { $this->event_listeners = array(); } /** * * @param CoreModuleEventListenerInterface $listener * @param string $callback * @return CoreModuleEventCallback */ protected function getCallback(CoreModuleEventListenerInterface $listener, $callback) { return new CoreModuleEventCallback($listener, $callback); } } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionItemEnglish', false)) return; class ProductAuctionItemEnglish extends AbstractProductAuctionItem { public function getId() { return $this->getObjectModel()->id; } public function getProductId() { return $this->getObjectModel()->id_product; } public function getImageId() { return $this->getObjectModel()->id_image; } public function getProductName() { return $this->getProduct()->name; } public function getProductShortDescription() { return $this->getProduct()->description_short; } public function getProductLink() { $context = Context::getContext(); $product = $this->getProduct(); $category = Category::getLinkRewrite($product->id_category_default, $context->language->id); return $context->link->getProductLink($product, $product->link_rewrite, $category); } public function getProductLinkRewrite() { return $this->getProduct()->link_rewrite; } public function getProductCoverImage($language_id) { $image = array(); $image['id_image'] = $this->getImageId(); $image['id_product'] = $this->getProductId(); return Product::defineProductImage($image, (int)$language_id); } public function getInitialPrice() { return $this->price_calculator->getPrice($this->getObjectModel()->initial_price); } public function getMinimalPrice() { return $this->price_calculator->getPrice($this->getObjectModel()->minimal_price); } public function getBidPrice() { $bid_price = 0; $bid_price += $this->getSpecificPrice()->price; $bid_price += $this->getObjectModel()->calculateIncrement($this->getSpecificPrice()->price); return $this->price_calculator->getPrice($bid_price); } public function canBuyNow(Customer $customer) { if (!$this->isRunning()) return false; if (!$this->hasBuyNow()) return false; if (!$this->isBuyNowVisible()) return false; if (!$this->isAvailable()) return false; if ($this->hasOffers() && !$this->isBuyNowAfterBid()) return false; if ($this->getCurrentPrice() > $this->getBuyNowPrice()) return false; return true; } public function hasBuyNow() { return $this->getObjectModel()->buynow_price > 0; } public function isBuyNowVisible() { return $this->getObjectModel()->buynow_visible; } public function isBuyNowAfterBid() { return $this->getObjectModel()->buynow_after_bid; } public function getBuyNowPrice() { return $this->price_calculator->getPrice($this->getObjectModel()->buynow_price); } public function isAvailable() { return $this->getProduct()->checkQty(1); } public function getCurrentPrice() { return $this->price_calculator->getPrice($this->getSpecificPrice()->price); } public function getCurrentStep() { return $this->price_calculator->getPrice($this->getObjectModel()->calculateIncrement($this->getSpecificPrice()->price)); } public function hasMinimalPrice() { return $this->getObjectModel()->minimal_price > 0; } public function isMinimalPriceReached() { if ($this->hasMinimalPrice()) return $this->getSpecificPrice()->price >= $this->getObjectModel()->minimal_price; return true; } public function getStartDate() { return $this->getObjectModel()->from; } public function getStartTimestamp() { return strtotime($this->getObjectModel()->from); } public function getEndDate() { return $this->getObjectModel()->to; } public function getEndTimestamp() { return strtotime($this->getObjectModel()->to); } public function getDuration($raw = false) { $this->date_time_formatter->setStartTimestamp($this->getStartTimestamp()); $this->date_time_formatter->setEndTimestamp($this->getEndTimestamp()); $this->date_time_formatter->setBehaviour(FormattedAuctionsDateTime::ZEROS_TRIM_BOTH); if ($raw) return $this->date_time_formatter->get(); return $this->date_time_formatter->format(); } public function getTimeToStart($raw = false) { $this->date_time_formatter->setStartTimestamp(time()); $this->date_time_formatter->setEndTimestamp($this->getStartTimestamp()); $this->date_time_formatter->setBehaviour(FormattedAuctionsDateTime::ZEROS_TRIM_BOTH); if ($raw) return $this->date_time_formatter->get(); return $this->date_time_formatter->format(); } public function getTimeToFinish($raw = false) { $this->date_time_formatter->setStartTimestamp(time()); $this->date_time_formatter->setEndTimestamp($this->getEndTimestamp()); $this->date_time_formatter->setBehaviour(FormattedAuctionsDateTime::ZEROS_TRIM_NONE); if ($raw) return $this->date_time_formatter->get(); return $this->date_time_formatter->format(); } public function isStarted() { return !$this->isStatus(array( ProductAuction::STATUS_IDLE )); } public function isRunning() { return $this->isStatus(array( ProductAuction::STATUS_RUNNING )); } public function isFinished() { return $this->isStatus(array( ProductAuction::STATUS_PROCESSING, ProductAuction::STATUS_FINISHED, ProductAuction::STATUS_CLOSED )); } public function isProcessed() { return $this->isStatus(array( ProductAuction::STATUS_FINISHED, ProductAuction::STATUS_CLOSED )); } public function isCheckedOut() { return $this->isStatus(array( ProductAuction::STATUS_CLOSED )); } public function isStatus($status) { return in_array($this->getStatus(), (array)$status); } public function getStatus() { $status = $this->getObjectModel()->status; if ($status == ProductAuction::STATUS_RUNNING && $this->getTimeToStart(true) > 0) $status = ProductAuction::STATUS_IDLE; if ($status == ProductAuction::STATUS_RUNNING && $this->getTimeToFinish(true) < 1) $status = ProductAuction::STATUS_PROCESSING; return $status; } public function getStatusName(Module $module) { $status = $this->getStatus(); $statuses = ProductAuction::getStatusList($module); return isset($statuses[$status]) ? $statuses[$status] : null; } public function isWinner(Customer $customer) { if ($this->hasWinner()) return $this->getWinnerId() == $customer->id; return false; } public function canBid(Customer $customer) { if (!$this->isRunning()) return false; if (!$this->isAvailable()) return false; return true; } public function canCheckOut(Customer $customer) { if (!$this->isWinner($customer)) return false; if (!$this->isProcessed()) return false; if ($this->isCheckedOut()) return false; if ($this->getProductAuctionOffer()->status != ProductAuctionOffer::STATUS_WINNER) return false; return true; } public function getWinnerId() { if (!$this->hasWinner()) return null; return $this->getProductAuctionOffer()->id_customer; } public function getWinnerName() { if (!$this->hasWinner()) return null; return $this->customer_name_formatter->getName($this->getProductAuctionOffer()->getCustomer()); } public function getWinnerNameFull() { if (!$this->hasWinner()) return null; return $this->customer_name_formatter->getFullName($this->getProductAuctionOffer()->getCustomer()); } public function getWinnerEmail() { if (!$this->hasWinner()) return null; return $this->getProductAuctionOffer()->getCustomer()->email; } public function getWinnerStatus() { if (!$this->hasWinner()) return null; return $this->getProductAuctionOffer()->status; } public function hasWinner() { return $this->getObjectModel()->id_product_auction_offer > 0; } public function getLastOfferDate() { return $this->getProductAuctionOffer()->date_upd; } public function hasOffers() { return $this->getObjectModel()->offers > 0; } public function getOffersCount() { return $this->getObjectModel()->offers; } public function getCustomerHighestPrice() { return $this->price_calculator->getPrice($this->getCustomerProductAuctionOffer()->customer_price); } public function getCustomerHighestOfferStatus() { return $this->getCustomerProductAuctionOffer()->status; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionArchive', false)) return; class ProductAuctionArchive extends ObjectModel { /** * @var integer Product id */ public $id_product_auction_archive; /** * @var integer Product id */ public $id_product; /** * @var string Name */ public $name; /** * @var float Reserve price in euros */ public $minimal_price; /** * @var float Initial Price in euros */ public $initial_price; /** * @var float Buy Now Price in euros */ public $buynow_price; /** * @var float Final Price in euros */ public $final_price; /** * @var string Object creation date */ public $offers; /** * @var string Lastname */ public $lastname; /** * @var string Firstname */ public $firstname; /** * @var string e-mail */ public $email; /** * @var string Object creation date */ public $from; /** * @var string Object last modification date */ public $to; /** * @var integer Object status */ public $status; /** * @var string Object creation date */ public $date_add; /** * @var string Object last modification date */ public $date_upd; public static $definition = array( 'table' => 'product_auction_archive', 'primary' => 'id_product_auction_archive', 'multilang' => true, 'fields' => array( 'id_product' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true ), 'name' => array( 'type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCatalogName', 'required' => true, 'size' => 128 ), 'minimal_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'initial_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true ), 'buynow_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'final_price' => array( 'type' => self::TYPE_FLOAT, 'validate' => 'isPrice' ), 'from' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat', 'required' => true ), 'to' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat', 'required' => true ), 'offers' => array( 'type' => self::TYPE_INT, 'validate' => 'isUnsignedId' ), 'lastname' => array( 'type' => self::TYPE_STRING, 'validate' => 'isName', 'size' => 32 ), 'firstname' => array( 'type' => self::TYPE_STRING, 'validate' => 'isName', 'size' => 32 ), 'email' => array( 'type' => self::TYPE_STRING, 'validate' => 'isEmail', 'size' => 128 ), 'status' => array( 'type' => self::TYPE_INT, 'validate' => 'isInt' ), 'date_add' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ), 'date_upd' => array( 'type' => self::TYPE_DATE, 'validate' => 'isDateFormat' ) ) ); /** * * @var ProductAuctionDateTime */ protected $date_time_formatter; public function __construct($id = null, $id_lang = null, $id_shop = null, $module = null) { parent::__construct($id, null, $id_shop); if ($module) $this->setDateTimeFormatter(new NullAuctionsDateTime($module)); } public function getStartDate() { return $this->from; } public function getEndDate() { return $this->to; } public function getDuration() { $this->date_time_formatter->setStartTimestamp(strtotime($this->from)); $this->date_time_formatter->setEndTimestamp(strtotime($this->to)); $this->date_time_formatter->setBehaviour(FormattedAuctionsDateTime::ZEROS_TRIM_BOTH); return $this->date_time_formatter->format(); } public function getMinimalPrice() { return $this->minimal_price; } public function getInitialPrice() { return $this->initial_price; } public function getBuyNowPrice() { return $this->buynow_price; } public function getFinalPrice() { return $this->final_price; } public function getWinnerName() { if ($this->firstname && $this->lastname) return $this->firstname.' '.$this->lastname; return $this->email; } public function hasWinner() { return $this->status == 4 && (($this->firstname && $this->lastname) || $this->email); } public function getWinnerEmail() { return $this->email; } public function hasMinimalPrice() { return $this->minimal_price > 0; } public function isMinimalPriceReached() { if ($this->hasMinimalPrice()) return $this->final_price >= $this->minimal_price; return true; } public function hasOffers() { return $this->offers > 0; } public function getOffersCount() { return $this->offers; } public function getArchiveDate() { return $this->date_upd; } public function getStatus() { return $this->status; } public function getStatusName(Module $module) { $status = $this->getStatus(); $statuses = ProductAuction::getStatusList($module); return isset($statuses[$status]) ? $statuses[$status] : null; } /** * * @param ProductAuctionDateTime $oProductAuctionDateTime */ public function setDateTimeFormatter(AbstractAuctionsDateTime $date_time_formatter) { $this->date_time_formatter = $date_time_formatter; } } <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class PowaTagProductHelper { public static function getProductSKU($product) { $product_sku = false; $powatag_sku = Configuration::get('POWATAG_SKU'); switch ($powatag_sku) { case Powatag::EAN: $product_sku = $product->ean13; break; case Powatag::UPC: $product_sku = $product->upc; break; case Powatag::REFERENCE: $product_sku = $product->reference; break; default: $product_sku = $product->id; break; } return $product_sku; } /** * Get Product object by code. * * @param string $code Code * * @return Product Product object */ public static function getProductByCode($code, $id_lang) { $powatag_sku = Configuration::get('POWATAG_SKU'); switch ($powatag_sku) { case Powatag::EAN: $id_product = (int) self::getProductIdByEan13($code); break; case Powatag::UPC: $id_product = (int) self::getProductIdByUPC($code); break; case Powatag::REFERENCE: $id_product = (int) self::getProductIdByReference($code); break; default: $id_product = (int) self::getProductIdByIdProduct($code); break; } $product = new Product($id_product, true, (int) $id_lang); //Check if multishop is enabled if (Shop::isFeatureActive() && $product) { //Check that product exists in current shop $id_shops = Product::getShopsByProduct($product->id); $product_exists = false; foreach ($id_shops as $id_shop) { if ($id_shop['id_shop'] == Context::getContext()->shop->id) { $product_exists = true; break; } } if (!$product_exists) { $product = false; } } return $product; } private static function getProductIdByIdProduct($code) { if ((string) (int) $code !== $code) { return false; } return $code; } private static function getProductIdByReference($reference) { if (empty($reference)) { return 0; } if (!Validate::isReference($reference)) { return 0; } $query = new DbQuery(); $query->select('p.id_product'); $query->from('product', 'p'); $query->where('p.reference = \''.pSQL($reference).'\''); return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query); } private static function getProductIdByEan13($code) { return Product::getIdByEan13($code); } private static function getProductIdByUPC($upc) { if (empty($upc)) { return 0; } if (!Validate::isUpc($upc)) { return 0; } $query = new DbQuery(); $query->select('p.id_product'); $query->from('product', 'p'); $query->where('p.upc = \''.pSQL($upc).'\''); return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (!class_exists('CoreModuleEventCallback', false)) { class CoreModuleEventCallback { /** * * @var CoreModuleEventListenerInterface */ protected $listener; /** * * @var string */ protected $callback; /** * * @param CoreModuleEventListenerInterface $listener * @param string $callback */ public function __construct(CoreModuleEventListenerInterface $listener, $callback) { $this->listener = $listener; $this->callback = $callback; } /** * * @param CoreModuleEventInterface $event */ public function call(CoreModuleEventInterface $event) { call_user_func_array(array( $this->listener, $this->callback ), array( $event )); } } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AdminAuctionsSettingsController', false)) return; class AdminAuctionsSettingsController extends ModuleAdminController { public function __construct() { $this->bootstrap = true; $this->identifier = 'id_product_auction'; $this->table = 'product_auction'; $this->className = 'ProductAuction'; $this->lang = false; $this->list_no_link = false; parent::__construct(); $this->_defaultOrderBy = $this->identifier; $this->fields_list = array( 'id_product_auction' => array( 'title' => $this->l('ID'), 'align' => 'center', 'width' => 10 ), 'name' => array( 'title' => $this->l('Name'), 'align' => 'center' ) ); } public function renderList() { $this->addRowAction('view'); return parent::renderList(); } public function renderForm() { $this->addJqueryPlugin(array( 'autocomplete' )); return parent::renderForm(); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AbstractProductAuctionMailingManager', false)) return; abstract class AbstractProductAuctionMailingManager extends CoreModuleObject implements CoreModuleEventListenerInterface { /** * * @var Auctions */ protected $module; /** * * @var array */ protected $product_auction_mailing = array(); /** * * @param Auctions $module */ public function __construct(Auctions $module) { parent::__construct(); $this->setModule($module); } /** * * @return Auctions */ public function getModule() { return $this->module; } /** * * @param Auctions $module */ public function setModule(Auctions $module) { $this->module = $module; } /** * * @param string $setting_name * @return mixed */ public function getSetting($setting_name) { return $this->module->getSettings('AuctionsMailingSettings')->getValue($setting_name); } /** * * @param integer $template * @param ProductAuction $product_auction * @param AbstractProductAuctionMailingRecipient $recipient */ public function addRecord($mailing_settings, $template, ProductAuction $product_auction, AbstractProductAuctionMailingRecipient $recipient) { $product_auction_mailing = new ProductAuctionMailing(); $product_auction_mailing->product_auction = $product_auction; $product_auction_mailing->customer = $recipient->getCustomer(); $product_auction_mailing->employee = $recipient->getEmployee(); $product_auction_mailing->product = $product_auction->product; $product_auction_mailing->language = $recipient->getLanguage(); $product_auction_mailing->template = $template; $product_auction_mailing->id_product_auction = $product_auction->id; $product_auction_mailing->id_product_auction_type = $product_auction->id_product_auction_type; $product_auction_mailing->id_product = $product_auction->id_product; $product_auction_mailing->id_customer = $recipient->getCustomerId(); $product_auction_mailing->id_employee = $recipient->getEmployeeId(); $product_auction_mailing->id_lang = $recipient->getLanguageId(); $product_auction_mailing->id_shop = $recipient->getShopId(); $product_auction_mailing->id_cart = $recipient->getCartId(); $product_auction_mailing->id_currency = $recipient->getCurrencyId(); $product_auction_mailing->sender_email = Configuration::get('PS_SHOP_EMAIL', null, null, $recipient->getShopId()); $product_auction_mailing->sender_name = Configuration::get('PS_SHOP_NAME', null, null, $recipient->getShopId()); $product_auction_mailing->recipient_email = $recipient->getEmail(); $product_auction_mailing->recipient_name = $recipient->getName(); $product_auction_mailing->data_current_price = $product_auction->specific_price->price; $product_auction_mailing->data_initial_price = $product_auction->initial_price; $product_auction_mailing->data_minimal_price = $product_auction->minimal_price; $product_auction_mailing->data_buynow_price = $product_auction->buynow_price; $product_auction_mailing->data_buynow_after_bid = $product_auction->buynow_after_bid; $product_auction_mailing->data_buynow_visible = $product_auction->buynow_visible; $product_auction_mailing->data_bidding_increment = $product_auction->bidding_increment; $product_auction_mailing->data_proxy_bidding = $product_auction->proxy_bidding; $product_auction_mailing->data_extend_threshold = $product_auction->extend_threshold; $product_auction_mailing->data_extend_by = $product_auction->extend_by; $product_auction_mailing->data_from = $product_auction->from; $product_auction_mailing->data_to = $product_auction->to; $product_auction_mailing->data_offers = $product_auction->offers; $product_auction_mailing->data_status = $product_auction->status; if ($product_auction->product_auction_offer) { $product_auction_mailing->data_winner_id_customer = $product_auction->product_auction_offer->id_customer; $product_auction_mailing->data_winner_price = $product_auction->product_auction_offer->customer_price; $product_auction_mailing->data_winner_status = $product_auction->product_auction_offer->status; $product_auction_mailing->winner = $product_auction->product_auction_offer->customer; } if ($this->getSetting($mailing_settings) == AuctionsMailingSettings::TYPE_CRON) $this->product_auction_mailing[] = $product_auction_mailing; else if ($this->getSetting($mailing_settings) == AuctionsMailingSettings::TYPE_INSTANT) $this->send($product_auction_mailing); } public function flushRecords() { foreach ($this->product_auction_mailing as $product_auction_mailing) $product_auction_mailing->save(true); $this->dispatcher()->clear(); } /** * * @param Customer[] $customers */ public function notifyParticipants(array $customers) { $recipient_type = AbstractProductAuctionMailingRecipient::RECIPIENT_TYPE_PARTICIPANT; foreach ($customers as $customer) $this->dispatcher()->register($this->getProductAuctionMailingRecipient($this, $customer, $recipient_type)); } /** * * @param Customer[] $customers */ public function notifySubscribers(array $customers) { $recipient_type = AbstractProductAuctionMailingRecipient::RECIPIENT_TYPE_SUBSCRIBER; foreach ($customers as $customer) $this->dispatcher()->register($this->getProductAuctionMailingRecipient($this, $customer, $recipient_type)); } /** * * @param Employee[] $employees */ public function notifyEmployees(array $employees) { $recipient_type = AbstractProductAuctionMailingRecipient::RECIPIENT_TYPE_EMPLOYEE; foreach ($employees as $employee) $this->dispatcher()->register($this->getProductAuctionMailingRecipient($this, $employee, $recipient_type)); } /** * * @return array */ public function getEvents() { return array( ProductAuctionEventBid::EVENT_NAME => 'onProductAuctionBidPlaced', ProductAuctionEventFinish::EVENT_NAME => 'onProductAuctionFinished', ProductAuctionEventReject::EVENT_NAME => 'onProductAuctionReject', ProductAuctionEventRemind::EVENT_NAME => 'onProductAuctionRemind', ProductAuctionEventRestart::EVENT_NAME => 'onProductAuctionRestart', ProductAuctionEventAcceptWinner::EVENT_NAME => 'onProductAuctionAccept' ); } /** * * @param ProductAuctionEventBid $event */ public function onProductAuctionBidPlaced(ProductAuctionEventBid $event) { $this->dispatcher()->dispatch($event); $this->flushRecords(); } /** * * @param ProductAuctionEvent $event */ public function onProductAuctionFinished(ProductAuctionEventFinish $event) { $this->dispatcher()->dispatch($event); $this->flushRecords(); } /** * * @param ProductAuctionEvent $event */ public function onProductAuctionReject(ProductAuctionEventReject $event) { $this->dispatcher()->dispatch($event); $this->flushRecords(); } /** * * @param ProductAuctionEvent $event */ public function onProductAuctionAccept(ProductAuctionEventAcceptWinner $event) { $this->dispatcher()->dispatch($event); $this->flushRecords(); } /** * * @param ProductAuctionEvent $event */ public function onProductAuctionRemind(ProductAuctionEventRemind $event) { $this->dispatcher()->dispatch($event); $this->flushRecords(); } /** * * @param ProductAuctionEvent $event */ public function onProductAuctionRestart(ProductAuctionEventRestart $event) { $this->dispatcher()->dispatch($event); $this->flushRecords(); } /** * * @param ProductAuctionMailing $product_auction_mailing */ public function send(ProductAuctionMailing $product_auction_mailing) { $product_auction_mailing_item_factory = ProductAuctionMailingItemFactory::getInstance($this->module); $module = $this->getModule(); $context = $module->getContext(); $original_shop = $context->shop; $original_customer = $context->customer; $original_employee = $context->employee; $original_cart = $context->cart; $original_currency = $context->currency; $original_language = $context->language; if ($product_auction_mailing->shop) { $context->shop = $product_auction_mailing->shop; $context->shop->setUrl(); } if ($product_auction_mailing->cart) $context->cart = $product_auction_mailing->cart; if ($product_auction_mailing->currency) $context->currency = $product_auction_mailing->currency; if ($product_auction_mailing->language) $context->language = $product_auction_mailing->language; if (!$context->currency) $context->currency = Currency::getDefaultCurrency(); $result = false; if ($product_auction_mailing->id_customer > 0) { $context->customer = $product_auction_mailing->customer; $context->employee = null; $product_auction_mailing_item = $product_auction_mailing_item_factory->makeFrontOfficeItem($product_auction_mailing); } else { $context->customer = null; $context->employee = $product_auction_mailing->employee; $product_auction_mailing_item = $product_auction_mailing_item_factory->makeBackOfficeItem($product_auction_mailing); } if ($product_auction_mailing_item->canSend($module)) { $lang_id = $product_auction_mailing_item->getValidLanguageId($module); $vars = $product_auction_mailing_item->getVars($module); $r_email = $product_auction_mailing_item->getRecipientEmail(); $r_name = $product_auction_mailing_item->getRecipientName(); $s_email = $product_auction_mailing_item->getSenderEmail(); $s_name = $product_auction_mailing_item->getSenderName(); $tpl = $product_auction_mailing_item->getTemplate(); $mail_dir = $product_auction_mailing_item->getMailDir($module); include_once ($module->getLocalPath().'/auctionsemailsender.php'); $result = AuctionsEmailSender::sendEmailEnglish($tpl, $lang_id, $vars, $r_email, $r_name, $s_email, $s_name, $mail_dir); } $context->shop = $original_shop; $context->customer = $original_customer; $context->employee = $original_employee; $context->cart = $original_cart; $context->currency = $original_currency; $context->language = $original_language; return $result; } } <file_sep>{ //Rajouter G. PREVEAUX fonctionnement yourmailing version 1.2 protected static $file_exists_cache = array(); static public function file_exists_cache($filename) { if (!isset(self::$file_exists_cache[$filename])) self::$file_exists_cache[$filename] = file_exists($filename); return self::$file_exists_cache[$filename]; } //fin de rajout G. PREVEAUX<file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_ca7d973c26c57b69e0857e7a0332d545'] = 'Ausgewählte Produkte'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_03c2e7e41ffc181a4e84080b4710e81e'] = 'Neu'; $_MODULE['<{homefeatured}touchmenot1.0.3>homefeatured_e0e572ae0d8489f8bf969e93d469e89c'] = 'Keine ähnlichen Artikel'; <file_sep><?php if (!defined('_CAN_LOAD_FILES_')) exit; class BlockPaymentLogoExtended extends Module { public function __construct() { $this->name = 'blockpaymentlogoextended'; $this->tab = 'front_office_features'; $this->module_key = "<KEY>"; $this->version = '1'; $this->author = 'Ixycom'; parent::__construct(); $this->displayName = $this->l('Block Payment Logo Extended'); $this->description = $this->l('This block will display all of your payment logos.'); } public function install() { if (!parent::install() || !$this->registerHook('header') || !$this->registerHook('footer')) return false; if (!Configuration::updateValue('BPAYMENTLOGOEXTENDED_ICONS', '')) return false; return true; } public function uninstall() { if (!parent::uninstall() || !Configuration::deleteByName('BPAYMENTLOGOEXTENDED_ICONS')) return false; return true; } public function hookDisplayHeader() { $this->context->controller->addCSS($this->_path . 'css/blockpaymentlogoextended.css', 'all'); $this->context->controller->addJS($this->_path . 'js/blockpaymentlogoextended.js'); } public function hookDisplayLeftColumn() { $this->smarty->assign('path', $this->_path); $this->smarty->assign('blockpaymentlogos', unserialize(Configuration::get('BPAYMENTLOGOEXTENDED_ICONS'))); return $this->display(__FILE__, 'blockpaymentlogoextended_columns.tpl'); } public function hookTop() { $this->smarty->assign('path', $this->_path); $this->smarty->assign('blockpaymentlogos', unserialize(Configuration::get('BPAYMENTLOGOEXTENDED_ICONS'))); return $this->display(__FILE__, 'blockpaymentlogoextended_top.tpl'); } public function hookDisplayFooter() { $this->smarty->assign('path', $this->_path); $this->smarty->assign('blockpaymentlogos', unserialize(Configuration::get('BPAYMENTLOGOEXTENDED_ICONS'))); return $this->display(__FILE__, 'blockpaymentlogoextended.tpl'); } public function getDoc() { global $cookie; $moncodeiso = LanguageCore::getIsoById($cookie->id_lang); $ladoc = '<fieldset style="float: left; width: 25%; margin-top: 2%;">'; $ladoc .= '<legend style="line-height: 32px;"><img src="' . _PS_BASE_URL_ . __PS_BASE_URI__ . 'modules/' . $this->name . '/logo.png" alt="" /> ' . $this->l('Documentation') . '</legend>'; if (isset($moncodeiso) && (!empty($moncodeiso))) { $ladoc .= '<a href="http://www.ixycom.com/doc-modules/' . $this->name . '/readme_' . $moncodeiso . '.pdf" title="' . $this->l('Documentation') . '" target="_blank">' . $this->l('Documentation') . '</a>'; } else { $ladoc .= '<a href="http://www.ixycom.com/doc-modules/' . $this->name . '/readme_fr.pdf" title="' . $this->l('Documentation fr') . '" target="_blank">' . $this->l('Documentation fr') . '</a><br />'; $ladoc .= '<a href="http://www.ixycom.com/doc-modules/' . $this->name . '/readme_en.pdf" title="' . $this->l('Documentation en') . '" target="_blank">' . $this->l('Documentation en') . '</a>'; } $ladoc .= '</fieldset>'; return $ladoc; } public function initToolbar() { $this->toolbar_btn['save'] = array( 'href' => '#', 'desc' => $this->l('Save') ); return $this->toolbar_btn; } private function initForm() { $helper = new HelperForm(); $helper->module = $this; $helper->name_controller = 'blockpaymentlogoextended'; $helper->identifier = $this->identifier; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex . '&configure=' . $this->name; $helper->toolbar_scroll = true; $helper->toolbar_btn = $this->initToolbar(); return $helper; } function getContent() { $this->_html = ''; $this->_postProcess(); $this->_html .= $this->displayForm(); $this->_html .= $this->getDoc(); $this->_html .= '<br class="clear" /><a href="http://www.ixycom.com" title="Agence web à Lille" target="_blank"><img style="display: block; margin: 20px auto;" src="http://www.ixycom.com/images/logo-300.jpg" alt="Logo Ixycom" width="300" height="134" /></a>'; return $this->_html; } protected function _postValidation() { $this->_errors = array(); if (Tools::isSubmit('submitBlockPaymentLogoExtended')) { $postComplete = $_POST; foreach ($postComplete as $key => $value) { if (strpos($key, "blockpaymentlogoextended_") !== false) { $bpaymentlogoextendedTab[] = str_replace("blockpaymentlogoextended_", "", $key); } } if (!Configuration::updateValue('BPAYMENTLOGOEXTENDED_ICONS', serialize($bpaymentlogoextendedTab))) $this->_errors[] = $this->l('Error during save'); } if (count($this->_errors)) { foreach ($this->_errors as $err) $this->_html .= '<div class="alert error">' . $err . '</div>'; return false; } return true; } private function _postProcess() { if ($this->_postValidation() == false) return false; $this->_errors = array(); if (Tools::isSubmit('submitBlockPaymentLogoExtended')) { $this->_html .= $this->displayConfirmation($this->l('Configuration saved.')); } } private function displayForm() { $this->fields_form[0]['form'] = array( 'legend' => array( 'title' => $this->l('Block Payment Logo Extended Configuration'), 'image' => $this->_path . 'logo.gif' ), 'input' => array( array( 'type' => 'checkbox', 'name' => 'blockpaymentlogoextended', 'values' => array( 'query' => array( array( 'id' => 'twocheckout', 'name' => '2Checkout', 'val' => '1' ), array( 'id' => 'american-express', 'name' => 'American Express', 'val' => '1' ), array( 'id' => 'bitcoin', 'name' => 'Bitcoin', 'val' => '1' ), array( 'id' => 'cirrus', 'name' => 'Cirrus', 'val' => '1' ), array( 'id' => 'credit-card', 'name' => 'Credit Card', 'val' => '1' ), array( 'id' => 'discover', 'name' => 'Discover', 'val' => '1' ), array( 'id' => 'google-wallet', 'name' => 'Google Wallet', 'val' => '1' ), array( 'id' => 'maestro', 'name' => 'Maestro', 'val' => '1' ), array( 'id' => 'mastercard', 'name' => 'Mastercard', 'val' => '1' ), array( 'id' => 'paypal', 'name' => 'Paypal', 'val' => '1' ), array( 'id' => 'skrill', 'name' => 'Skrill', 'val' => '1' ), array( 'id' => 'solo', 'name' => 'Solo', 'val' => '1' ), array( 'id' => 'square-up', 'name' => 'Square Up', 'val' => '1' ), array( 'id' => 'visa', 'name' => 'VISA', 'val' => '1' ), array( 'id' => 'western-union', 'name' => 'Western union', 'val' => '1' ), array( 'id' => 'wire-transfer', 'name' => $this->l('Wire Transfer'), 'val' => '1' ) ), 'id' => 'id', 'name' => 'name' ) ) ), 'submit' => array( 'name' => 'submitBlockPaymentLogoExtended', 'title' => $this->l('Save'), 'class' => 'button' ) ); $paymentLogoTab = unserialize(Configuration::get('BPAYMENTLOGOEXTENDED_ICONS')); foreach ($paymentLogoTab as $paymentLogo) { $this->fields_value['blockpaymentlogoextended_' . $paymentLogo] = 1; } $helper = $this->initForm(); $helper->submit_action = ''; $helper->title = $this->l('Block Payment Logo Extended Configuration'); $helper->fields_value = $this->fields_value; return $helper->generateForm($this->fields_form); } } ?> <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionMailingItemEnglish', false)) return; class ProductAuctionMailingItemEnglish extends AbstractProductAuctionMailingItem { public function getTemplate() { $template = parent::getTemplate(); if ($template) return "english_{$template}"; return null; } public function getId() { return $this->getObjectModel()->id; } public function getProductAuctionId() { return $this->getObjectModel()->id_product_auction; } public function getProductId() { return $this->getObjectModel()->id_product; } public function getProductName() { return $this->getProduct()->name; } public function getProductShortDescription() { return $this->getProduct()->description_short; } public function getProductLink() { $context = Context::getContext(); $product = $this->getProduct(); $category = Category::getLinkRewrite($product->id_category_default, $context->language->id); return $context->link->getProductLink($product, $product->link_rewrite, $category); } public function getProductLinkRewrite() { return $this->getProduct()->link_rewrite; } public function getInitialPrice() { return $this->price_calculator->getPrice($this->getObjectModel()->data_initial_price); } public function getMinimalPrice() { return $this->price_calculator->getPrice($this->getObjectModel()->data_minimal_price); } public function getBidPrice() { $bid_price = 0; $bid_price += $this->getObjectModel()->data_current_price; $bid_price += $this->getObjectModel()->calculateIncrement($this->getObjectModel()->data_current_price); return $this->price_calculator->getPrice($bid_price); } public function hasBuyNow() { return $this->getObjectModel()->data_buynow_price > 0; } public function isBuyNowVisible() { return $this->getObjectModel()->data_buynow_visible; } public function isBuyNowAfterBid() { return $this->getObjectModel()->data_buynow_after_bid; } public function getBuyNowPrice() { return $this->price_calculator->getPrice($this->getObjectModel()->data_buynow_price); } public function isAvailable() { return $this->getProduct()->checkQty(1); } public function getCurrentPrice() { return $this->price_calculator->getPrice($this->getObjectModel()->data_current_price); } public function getCurrentStep() { return $this->price_calculator->getPrice($this->getObjectModel()->calculateIncrement($this->getObjectModel()->data_current_price)); } public function hasMinimalPrice() { return $this->getObjectModel()->data_minimal_price > 0; } public function isMinimalPriceReached() { if ($this->hasMinimalPrice()) return $this->getObjectModel()->data_current_price >= $this->getObjectModel()->data_minimal_price; return true; } public function getStartDate() { return $this->getObjectModel()->data_from; } public function getEndDate() { return $this->getObjectModel()->data_to; } public function getDuration($raw = false) { $this->date_time_formatter->setStartTimestamp(strtotime($this->getObjectModel()->data_from)); $this->date_time_formatter->setEndTimestamp(strtotime($this->getObjectModel()->data_to)); $this->date_time_formatter->setBehaviour(FormattedAuctionsDateTime::ZEROS_TRIM_BOTH); if ($raw) return $this->date_time_formatter->get(); return $this->date_time_formatter->format(); } public function getTimeToStart($raw = false) { $this->date_time_formatter->setStartTimestamp(time()); $this->date_time_formatter->setEndTimestamp(strtotime($this->getObjectModel()->data_from)); $this->date_time_formatter->setBehaviour(FormattedAuctionsDateTime::ZEROS_TRIM_BOTH); if ($raw) return $this->date_time_formatter->get(); return $this->date_time_formatter->format(); } public function getTimeToFinish($raw = false) { $this->date_time_formatter->setStartTimestamp(time()); $this->date_time_formatter->setEndTimestamp(strtotime($this->getObjectModel()->data_to)); $this->date_time_formatter->setBehaviour(FormattedAuctionsDateTime::ZEROS_TRIM_NONE); if ($raw) return $this->date_time_formatter->get(); return $this->date_time_formatter->format(); } public function isStarted() { return !$this->isStatus(array( ProductAuction::STATUS_IDLE )); } public function isRunning() { return $this->isStatus(array( ProductAuction::STATUS_RUNNING )); } public function isFinished() { return $this->isStatus(array( ProductAuction::STATUS_PROCESSING, ProductAuction::STATUS_FINISHED, ProductAuction::STATUS_CLOSED )); } public function isProcessed() { return $this->isStatus(array( ProductAuction::STATUS_FINISHED, ProductAuction::STATUS_CLOSED )); } public function isCheckedOut() { return $this->isStatus(array( ProductAuction::STATUS_CLOSED )); } public function isStatus($status) { return in_array($this->getStatus(), (array)$status); } public function getStatus() { $status = $this->getObjectModel()->data_status; if ($status == ProductAuction::STATUS_RUNNING && $this->getTimeToStart(true) > 0) $status = ProductAuction::STATUS_IDLE; if ($status == ProductAuction::STATUS_RUNNING && $this->getTimeToFinish(true) < 1) $status = ProductAuction::STATUS_PROCESSING; return $status; } public function getStatusName(Module $module) { $status = $this->getStatus(); $statuses = ProductAuction::getStatusList($module); return isset($statuses[$status]) ? $statuses[$status] : null; } public function isWinner(Customer $customer) { if ($this->hasWinner()) return $this->getWinnerId() == $customer->id; return false; } public function getWinnerId() { if (!$this->hasWinner()) return null; return $this->getObjectModel()->data_winner_id_customer; } public function getWinnerName() { if (!$this->hasWinner()) return null; return $this->customer_name_formatter->getName($this->getObjectModel()->winner); } public function getWinnerNameFull() { if (!$this->hasWinner()) return null; return $this->customer_name_formatter->getFullName($this->getObjectModel()->winner); } public function getWinnerEmail() { if (!$this->hasWinner()) return null; return $this->getObjectModel()->winner->email; } public function getWinnerStatus() { if (!$this->hasWinner()) return null; return $this->getObjectModel()->data_winner_status; } public function hasWinner() { return $this->getObjectModel()->data_winner_id_customer > 0 && $this->getObjectModel()->winner; } public function hasOffers() { return $this->getObjectModel()->data_offers > 0; } public function getOffersCount() { return $this->getObjectModel()->data_offers; } public function getVars(Auctions $module) { if ($this->getObjectModel()->id_customer > 0) $type = ProductAuctionPermissionsEnglish::TYPE_EMAIL; else $type = ProductAuctionPermissionsEnglish::TYPE_ADMIN; $permissions = array( 'show_current_price' => $this->getPermissions($type)->showCurrentPrice(), 'show_start_time' => $this->getPermissions($type)->showStartTime(), 'show_close_time' => $this->getPermissions($type)->showCloseTime(), 'show_duration' => $this->getPermissions($type)->showDuration(), 'show_bids' => $this->getPermissions($type)->showBids(), 'show_bids_list' => $this->getPermissions($type)->showBidsList(), 'show_winner' => $this->getPermissions($type)->showWinner(), 'show_starting_price' => $this->getPermissions($type)->showStartingPrice(), 'show_countdown' => $this->getPermissions($type)->showCountdown() ); return array( '{id_product_auction}' => $this->getProductAuctionId(), '{id_product}' => $this->getProductId(), '{product_name}' => $this->getProductName(), '{current_price}' => $permissions['show_current_price'] ? Tools::displayPrice(Tools::convertPrice($this->getCurrentPrice())) : '', '{initial_price}' => $permissions['show_starting_price'] ? Tools::displayPrice(Tools::convertPrice($this->getInitialPrice())) : '', '{buynow_price}' => $this->hasBuyNow() && $this->isBuyNowVisible() ? Tools::displayPrice(Tools::convertPrice($this->getBuyNowPrice())) : '', '{minimal_price}' => Tools::displayPrice(Tools::convertPrice($this->getMinimalPrice())), '{bid_price}' => Tools::displayPrice(Tools::convertPrice($this->getBidPrice())), '{start_date}' => $permissions['show_start_time'] ? $this->getStartDate() : '', '{end_date}' => $permissions['show_close_time'] ? $this->getEndDate() : '', '{duration}' => $permissions['show_duration'] ? $this->getDuration() : '', '{time_to_start}' => $permissions['show_countdown'] ? $this->getTimeToStart() : '', '{time_to_finish}' => $permissions['show_countdown'] ? $this->getTimeToFinish() : '', '{has_reserve}' => $this->hasMinimalPrice(), '{reached}' => $this->isMinimalPriceReached(), '{offers_count}' => $permissions['show_bids'] ? $this->getOffersCount() : '', '{winner_id}' => $permissions['show_winner'] ? $this->getWinnerId() : '', '{winner_email}' => $permissions['show_winner'] ? $this->getWinnerEmail() : '', '{winner_name}' => $permissions['show_winner'] ? $this->getWinnerName() : '', '{winner_name_full}' => $permissions['show_winner'] ? $this->getWinnerNameFull() : '', '{winner_status}' => $permissions['show_winner'] ? $this->getWinnerStatus() : '', '{product_link}' => $this->getProductLink(), '{my_auctions_link}' => $module->getContext()->link->getModuleLink('auctions', 'mybids', array(), true), '{my_won_auctions_link}' => $module->getContext()->link->getModuleLink('auctions', 'mypayment', array(), true), '{my_account_link}' => $module->getContext()->link->getPageLink('my-account', true), '{recipient_email}' => $this->getObjectModel()->recipient_email, '{recipient_name}' => $this->getObjectModel()->recipient_name, '{sender_email}' => $this->getObjectModel()->sender_email, '{sender_name}' => $this->getObjectModel()->sender_name ); } } <file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_34c869c542dee932ef8cd96d2f91cae6'] = 'I nostri negozi'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_a82be0f551b8708bc08eb33cd9ded0cf'] = 'Informazioni'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_d1aa22a3126f04664e0fe3f598994014'] = 'Speciali'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_9ff0635f5737513b1a6f559ac2bff745'] = 'Nuovi prodotti'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_3cb29f0ccc5fd220a97df89dafe46290'] = 'I più venduti'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_02d4482d332e1aef3437cd61c9bcc624'] = 'Contattaci'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_e1da49db34b0bdfdddaba2ad6552f848'] = 'Mappa del sito'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_5813ce0ec7196c492c97596718f71969'] = 'Mappa del sito'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_7a52e36bf4a1caa031c75a742fb9927a'] = 'Powered by'; <file_sep><?php /** * admin-display_class.php file defines method to display content tabs of admin page */ class BT_AdminDisplay implements BT_IAdmin { /** * Magic Method __construct */ private function __construct() { } /** * Magic Method __destruct */ public function __destruct() { } /** * run() method display all configured data admin tabs * @param array $aParam * @return array */ public function run(array $aParam = null) { // set variables $aDisplayInfo = array(); // get type $aParam['sType'] = empty($aParam['sType'])? 'tabs' : $aParam['sType']; switch ($aParam['sType']) { case 'tabs' : // use case - display first page with all tabs case 'basic' : // use case - display basic settings page case 'connectors' : // use case - display connector settings page case 'connectorForm' : // use case - display connector form case 'hooks' : // use case - display hook settings page case 'hookForm' : // use case - display hook form case 'curlssl' : // use case - display curl ssl case 'SystemHealth' : // use case - display system health settings page // execute match function $aDisplayInfo = call_user_func_array(array($this, '_display' . ucfirst($aParam['sType'])), array($aParam)); break; default : break; } // use case - generic assign if (!empty($aDisplayInfo)) { $aDisplayInfo['assign'] = array_merge($aDisplayInfo['assign'], $this->_assign()); } return $aDisplayInfo; } /** * _assign() method assigns transverse data * * @return array */ private function _assign() { $bVersion15_16 = false; if (version_compare(_PS_VERSION_, '1.6', '>')) { $bVersion15_16 = true; } // set smarty variables return ( array( 'sURI' => BT_FPCModuleTools::truncateUri(array('&iPage', '&sAction')), 'aQueryParams' => $GLOBALS[_FPC_MODULE_NAME . '_REQUEST_PARAMS'], 'iDefaultLang' => intval(FacebookPsConnect::$iCurrentLang), 'sDefaultLang' => FacebookPsConnect::$sCurrentLang, 'sHeaderInclude' => BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_HEADER), 'sErrorInclude' => BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_ERROR), 'sConfirmInclude' => BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_CONFIRM), 'bVerion15_16' => $bVersion15_16, 'bTwitterActif' => (!empty($GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS']['twitter']['data']['activeConnector'])) ? 1 : 2, 'iApiRequestMethod' => FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_API_REQUEST_METHOD'], ) ); } /** * _displayTabs() method displays admin's first page with all tabs * * @param array $aPost * @return array */ private function _displayTabs(array $aPost) { // set smarty variables $aAssign = array( 'sDocUri' => _MODULE_DIR_ . _FPC_MODULE_SET_NAME . '/', 'sDocName' => 'readme_' . ((FacebookPsConnect::$sCurrentLang == 'fr')? 'fr' : 'en') . '.pdf', 'sCurrentIso' => Language::getIsoById(FacebookPsConnect::$iCurrentLang), 'sContactUs' => 'http://www.businesstech.fr/' . ((FacebookPsConnect::$sCurrentLang == 'fr')? 'fr/contactez-nous' : 'en/contact-us'), 'sTs' => time(), 'bAddJsCss' => true, 'bHideConfiguration'=> BT_FPCWarning::create()->bStopExecution, ); // use case - get display data of basic settings $aData = $this->_displayBasic($aPost); $aAssign = array_merge($aAssign, $aData['assign']); // use case - get display data of connector settings $aData = $this->_displayConnectors($aPost); $aAssign = array_merge($aAssign, $aData['assign']); // use case - get display data of hook settings $aData = $this->_displayHooks($aPost); $aAssign = array_merge($aAssign, $aData['assign']); // use case - get display data of stats settings $aData = $this->_displaySystemHealth($aPost); $aAssign = array_merge($aAssign, $aData['assign']); // use case - get display data of stats settings $aData = $this->_displayPrerequisitesCheck($aPost); $aAssign = array_merge($aAssign, $aData['assign']); // assign all included templates files $aAssign['sBasicsInclude'] = BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_ADMIN_PATH . _FPC_TPL_BASIC_SETTINGS); $aAssign['sConnectorInclude'] = BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_ADMIN_PATH . _FPC_TPL_CONNECTOR_SETTINGS); $aAssign['sHookInclude'] = BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_ADMIN_PATH . _FPC_TPL_HOOK_SETTINGS); $aAssign['sSystemHealthInclude']= BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_ADMIN_PATH . _FPC_TPL_SYS_HEALTH_SETTINGS); $aAssign['sPrerequisitesCheck'] = BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_ADMIN_PATH . _FPC_TPL_PREREQUISITES_CHECK_SETTINGS); $aAssign['iTestSsl'] = FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_SSL_TEST_TODO']; $aAssign['iCurlSslCheck'] = FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_TEST_CURl_SSL']; // set css and js use $GLOBALS[_FPC_MODULE_NAME . '_USE_JS_CSS']['bUseJqueryUI'] = true; return ( array( 'tpl' => _FPC_TPL_ADMIN_PATH . _FPC_TPL_BODY, 'assign' => array_merge($aAssign, $GLOBALS[_FPC_MODULE_NAME . '_USE_JS_CSS']), ) ); } /** * _displayBasic() method displays snippets settings * * @category admin collection * @see * * @param array $aPost * @return array */ private function _displayBasic(array $aPost) { $aAssign = array(); if (FacebookPsConnect::$sQueryMode == 'xhr') { // clean header @ob_end_clean(); } if (version_compare(_PS_VERSION_, '1.5', '>')) { $aAssign['bVerion15_16'] = true; } // set smarty variables $aAssign = array( 'bDisplayAskFacebook' => FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_DISPLAY_FB_POPIN'], 'bDisplayBlock' => FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_DISPLAY_BLOCK'], 'bDisplayBlockInfoAccount' => FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_DISPLAY_BLOCK_INFO_ACCOUNT'], 'bDisplayBlockInfoCart' => FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_DISPLAY_BLOCK_INFO_CART'], 'bOnePageCheckOut' => Configuration::get('PS_ORDER_PROCESS_TYPE'), 'iDefaultCustomerGroup' => FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_DEFAULT_CUSTOMER_GROUP'], 'sApiRequestType' => FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_API_REQUEST_METHOD'], 'aApiCallMethod' => array(array('type' => 'fopen', 'name' => FacebookPsConnect::$oModule->l('Native PHP file_get_contents', 'admin-display_class'),'active' => ini_get('allow_url_fopen')), array('type' => 'curl', 'name' => FacebookPsConnect::$oModule->l('PHP cURL library mode', 'admin-display_class'), 'active' => function_exists('curl_init'))), ); if (version_compare(_PS_VERSION_, '1.5', '>')) { $aAssign['aGroups'] = Group::getGroups(FacebookPsConnect::$iCurrentLang, FacebookPsConnect::$iShopId); } else { $aAssign['aGroups'] = Group::getGroups(FacebookPsConnect::$iCurrentLang); } return ( array( 'tpl' => _FPC_TPL_ADMIN_PATH . _FPC_TPL_BASIC_SETTINGS, 'assign' => $aAssign, ) ); } /** * _displayConnectors() method displays connectors list * * @category admin collection * @see * * @param array $aPost * @return array */ private function _displayConnectors(array $aPost) { // set $aAssign = array(); if (FacebookPsConnect::$sQueryMode == 'xhr') { // clean header @ob_end_clean(); } // unserialize connector data BT_FPCModuleTools::getConnectorData(true); // set smarty variables $aAssign = array( 'aConnectors' => $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS'], 'iDefaultLang' => intval(FacebookPsConnect::$iCurrentLang), 'aDefaultLang' => Language::getLanguage(intval(FacebookPsConnect::$iCurrentLang)), 'bVersion15_16' => (version_compare(_PS_VERSION_, '1.5', '>')? true : false), ); return ( array('tpl' => _FPC_TPL_ADMIN_PATH . _FPC_TPL_CONNECTOR_SETTINGS, 'assign' => $aAssign) ); } /** * _displayConnectorForm() method displays connector form * * @category admin collection * @see Language::getLanguage() * * @param array $aPost * @return array */ private function _displayConnectorForm(array $aPost) { // set $aAssign = array(); // clean header @ob_end_clean(); // get connector id $iConnectorId = Tools::getValue('iConnectorId'); // use case - only configure with good connector id if ($iConnectorId && array_key_exists($iConnectorId, $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS'])) { // get unserialized connector data BT_FPCModuleTools::unserializeData($iConnectorId, 'connector'); // set smarty variables $aAssign = array( 'iConnectorId' => $iConnectorId, 'iDefaultLang' => intval(FacebookPsConnect::$iCurrentLang), 'aDefaultLang' => Language::getLanguage(intval(FacebookPsConnect::$iCurrentLang)), 'aConnector' => $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS'][$iConnectorId], 'sCbkUri' => BT_FPCModuleTools::detectHttpUri(_FPC_MODULE_URL . $iConnectorId . '-callback.php'), 'iTestCurlSsl' => FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_TEST_CURl_SSL'], 'iApiRequestMethod' => FacebookPsConnect::$aConfiguration[_FPC_MODULE_NAME . '_API_REQUEST_METHOD'], ); // set tpl to include $aAssign['sTplToInclude'] = BT_FPCModuleTools::getTemplatePath(_FPC_PATH_TPL_NAME . _FPC_TPL_ADMIN_PATH . _FPC_TPL_CONNECTOR_PATH . $aAssign['aConnector']['adminTpl']); // clean footer FacebookPsConnect::$sQueryMode = 'xhr'; } return ( array('tpl' => _FPC_TPL_ADMIN_PATH . _FPC_TPL_CONNECTOR_BODY, 'assign' => $aAssign) ); } /** * _displayHooks() method displays hooks list * * @param array $aPost * @return array */ private function _displayHooks(array $aPost) { if (FacebookPsConnect::$sQueryMode == 'xhr') { // clean header @ob_end_clean(); } $bVersion15_16 = false; if (version_compare(_PS_VERSION_, '1.5', '>')) { $bVersion15_16 = true; } // unserialize hook data BT_FPCModuleTools::getHookData(); // set smarty variables $aAssign = array( 'aHooks' => $GLOBALS[_FPC_MODULE_NAME . '_ZONE'], 'iDefaultLang' => intval(FacebookPsConnect::$iCurrentLang), 'bVersion15_16' => $bVersion15_16, ); return ( array('tpl' => _FPC_TPL_ADMIN_PATH . _FPC_TPL_HOOK_SETTINGS, 'assign' => $aAssign) ); } /** * _displayHookForm() method displays hook form * * @param array $aPost * @return array */ private function _displayHookForm(array $aPost) { // set $aAssign = array(); // clean header @ob_end_clean(); // get hook id $sHookId = Tools::getValue('sHookId'); // use case - only configure with good connector id if ($sHookId && array_key_exists($sHookId, $GLOBALS[_FPC_MODULE_NAME . '_ZONE'])) { // get unserialized connector data BT_FPCModuleTools::unserializeData($sHookId, 'hook'); // set smarty variables $aAssign = array( 'sHookId' => $sHookId, 'iDefaultLang' => intval(FacebookPsConnect::$iCurrentLang), 'bOneSet' => BT_FPCModuleTools::getConnectorData(false, true), 'aHook' => $GLOBALS[_FPC_MODULE_NAME . '_ZONE'][$sHookId], 'aConnectors' => $GLOBALS[_FPC_MODULE_NAME . '_CONNECTORS'], ); // set current widget $aAssign['aHook'] = $GLOBALS[_FPC_MODULE_NAME . '_ZONE'][$sHookId]; // clean footer FacebookPsConnect::$sQueryMode = 'xhr'; } return ( array('tpl' => _FPC_TPL_ADMIN_PATH . _FPC_TPL_HOOK_FORM, 'assign' => $aAssign) ); } /** * _displaySystemHealth() method displays system health information * * @param array $aPost * @return array */ private function _displaySystemHealth(array $aPost) { $aAssign = array(); $aAssign['iCurrentLang'] = intval(FacebookPsConnect::$iCurrentLang); // set $sIsoCode = FacebookPsConnect::$sCurrentLang; if($sIsoCode !== 'fr') { $sIsoCode = 'en'; } $aModules = array( 'facebookpsshoptab' => array( 'active' => true, 'min' => '3.3.2', 'name' => 'Facebook Ps Shop Tab', 'img' => _FPC_URL_IMG . 'admin/fb-ps-shop-tab.jpg', 'addons' => 'http://addons.prestashop.com/'.$sIsoCode.'/social-commerce-facebook-prestashop-modules/1048-facebook-ps-shop-tab.html' ), 'facebookpsessentials' => array( 'active' => true, 'min' => '2.3.0', 'name' => 'Facebook Ps Essentials', 'img' => _FPC_URL_IMG . 'admin/fb-ps-essentials.jpg', 'addons' => 'http://addons.prestashop.com/'.$sIsoCode.'/social-commerce-facebook-prestashop-modules/5025-facebook-ps-essentials-facebook-like-twitter-etc.html' ), ); unset($sIsoCode); foreach ($aModules as $sName => $aModule) { $aParams = $aModule; if (($oModule = BT_FPCModuleTools::isInstalled($sName, array(), true)) !== false) { // installed ok + min version $aParams['installed'] = true; $aParams['minVersion'] = version_compare($oModule->version, $aModule['min'], '>=')? true : false; } else { $aParams['installed'] = false; } $aAssign['aModules'][$sName] = $aParams; } return ( array('tpl' => _FPC_TPL_ADMIN_PATH . _FPC_TPL_SYS_HEALTH_SETTINGS, 'assign' => $aAssign) ); } /** * _displayCurlSsl() method displays result test Curl with Ssl * Set Global for Test the result Curl SSL * * @category admin collection * @see * * @param array $aPost * @return array */ private function _displayCurlSsl(array $aPost) { //set $aAssign = array(); //clean header @ob_end_clean(); //init curl connexion $ch = curl_init('https://google.fr'); //transfer test curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // exec curl curl_exec($ch); // error test and set error message if (curl_errno($ch) == 1) { $aAssign['iCurlSslCheck'] = false; Configuration::updateValue(_FPC_MODULE_NAME . '_TEST_CURl_SSL', 1); } else { $aAssign['iCurlSslCheck'] = true; Configuration::updateValue(_FPC_MODULE_NAME . '_TEST_CURl_SSL', 2); Configuration::updateValue(_FPC_MODULE_NAME . '_SSL_TEST_TODO', 0); } //close curl connexion curl_close($ch); //clean footer FacebookPsConnect::$sQueryMode = 'xhr'; return( array('tpl' => _FPC_TPL_ADMIN_PATH . _FPC_TPL_CURL_SSL, 'assign' => $aAssign) ); } /** * _displayPrerequisitesCheck() method displays prerequisites check * * @param array $aPost * @return array */ private function _displayPrerequisitesCheck(array $aPost) { $aAssign = array( 'sValidImgUrl' => _FPC_URL_IMG . 'admin/icon-valid.png', 'sInvalidImgUrl' => _FPC_URL_IMG . 'admin/icon-invalid.png', 'sCheckCurlInit' => BT_FPCWarning::create()->run('function', 'curl_init'), 'sCheckAllowUrl' => BT_FPCWarning::create()->run('directive', 'allow_url_fopen'), 'sCheckGroup' => BT_FPCWarning::create()->run('configuration', '_DEFAULT_CUSTOMER_GROUP'), ); return ( array('tpl' => _FPC_TPL_ADMIN_PATH . _FPC_TPL_PREREQUISITES_CHECK_SETTINGS, 'assign' => $aAssign) ); } /** * create() method set singleton * * @return obj */ public static function create() { static $oDisplay; if ( null === $oDisplay) { $oDisplay = new BT_AdminDisplay(); } return $oDisplay; } }<file_sep>//***************************************************************************************************************************************************** //***************************************************************************************************************************************************** //fonction permettant de generer en masse les codes barres function gen_barcode() { if(confirm(document.getElementById('warning_msg').value)){ var url; var params; //creer les variables cachées var ps_root_dir=document.getElementById('ps_root_dir').value; var prefix_fo=document.getElementById('prefix_cd').value; url = http_header+domain+racine+'modules/yourbarcode_gp/ajax/gen_code_ean.php'; params= 'PS_ROOT_DIR='+ps_root_dir+'&prefix_fo='+prefix_fo; appel_php_gencode(url,params,domain,racine); } } function appel_php_gencode(chemin,params) { var xhr = null; if(window.XMLHttpRequest) // Firefox xhr = new XMLHttpRequest(); else if(window.ActiveXObject) // Internet Explorer xhr = new ActiveXObject("Microsoft.XMLHTTP"); else { // XMLHttpRequest non supporté par le navigateur alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); return; } //var params = 'PS_ROOT_DIR='+ps_root_dir+'&query='+query+'&mailobject='+mailobject+'&select_template_mail='+select_template_mail+'&select_lang='+select_lang; xhr.onreadystatechange = function() { debug_ajx_gen_barcode(xhr,domain,racine);}; xhr.open("POST", chemin, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Content-length", params.length); xhr.send(params); } function debug_ajx_gen_barcode (xhr) { if(xhr.readyState!=4) { //afficher merci de patienter } if (xhr.readyState==4){ var doc= xhr.responseText; //alert(doc); if (doc=='ok'){ alert(document.getElementById('msg_gen').value); } else { alert(document.getElementById('msg_error').value); } } } //************************************************************************************************************************************************ //************************************************************************************************************************************************ //Fonction permettant de modifier les codes ean13 de manière unitaire //fonction appeler pour mettre a jour ou renseigner un nouveau code ean13 function ajx_mvt(champ_qty) { var url; var params; //creer les variables cacher var ps_root_dir=document.getElementById('ps_root_dir').value; var COOKIE_EMP=document.getElementById('COOKIE_EMP').value; var tab_traduction=document.getElementById('traductions').value.split('|'); var ean13=document.getElementById(champ_qty).value; //rajoute une fenetre de validation si le controle de modification est activé if(document.getElementById('state_validation').value==1){ if(!confirm(tab_traduction[3])) { document.getElementById(champ_qty).value=document.getElementById('value_before').value; return false; } } tab_product=champ_qty.split('|'); id_product=tab_product[0]; id_product_attribute=tab_product[1]; url = http_header+domain+racine+'modules/yourbarcode_gp/ajax/upd_ean13.php'; params= 'id_product='+id_product+'&ean13='+ean13+'&PS_ROOT_DIR='+ps_root_dir+'&id_product_attribute='+id_product_attribute ; appel_php(url,params,domain,racine); } //fonction permettant de d'appeler une page php function appel_php(chemin,params) { var xhr = null; if(window.XMLHttpRequest) // Firefox xhr = new XMLHttpRequest(); else if(window.ActiveXObject) // Internet Explorer xhr = new ActiveXObject("Microsoft.XMLHTTP"); else { // XMLHttpRequest non supporté par le navigateur alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); return; } xhr.onreadystatechange = function() { debug_ajx_upd_ean13(xhr,domain,racine);}; xhr.open("POST", chemin, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Content-length", params.length); xhr.send(params); } //fonction permettant le debuggage appel_php function debug_ajx_upd_ean13 (xhr) { if(xhr.readyState!=4) { //afficher merci de patienter } ps_root_dir=document.getElementById('ps_root_dir').value; LANG=document.getElementById('LANG').value; if (xhr.readyState==4){ //recuperation des données du document XML var doc= xhr.responseText; alert(doc); var expression=new RegExp("^erreur", "g"); //recuperation des libellés d'etat var state_msg=document.getElementById('state_msg').value; var tab_state_msg=state_msg.split('|'); var tab_doc=doc.split('|'); //1->pb longueur; 2->pb bit de control; 3-> duplicate if (expression.test(tab_doc[0])){ var tab_doc_erreur=tab_doc[0].split(':'); var error_msg=document.getElementById('error_msg').value; var tab_error_msg=error_msg.split('|'); //affichage du message d'erreur alert(tab_error_msg[tab_doc_erreur[1]-1]); //en cas d'erreur on remet la valeur precedente trouvé dans la base de donnée document.getElementById(tab_doc[1].replace('-','|')).value=tab_doc[2]; } else { //en cas de succès on réinitialise la ligne correspondante correctement setClass(document.getElementById(tab_doc[1]),'lg_normal',100); document.getElementById('td_'+tab_doc[1]).innerHTML='<A target="_blank" href="'+http_header+domain+racine+'modules/yourbarcode_gp/pdf.php?cd_ean13='+tab_doc[0]+'&PS_ROOT_DIR='+ps_root_dir+'&url='+http_header+domain+racine+'modules/yourbarcode_gp/ean13.php">'+tab_doc[0]+'</A><BR><A target="_blank" href="'+http_header+domain+racine+'modules/yourbarcode_gp/items_pdf.php?cd_ean13='+tab_doc[0]+'&lang='+LANG+'&PS_ROOT_DIR='+ps_root_dir+'&url='+http_header+domain+racine+'">'+tab_doc[0]+'</A>'; document.getElementById('td_state'+tab_doc[1]).innerHTML=tab_state_msg[0]; } } } //************************************************************************************************************************************************ //************************************************************************************************************************************************ //fonction commune function only_number(max,champ){ var number=document.getElementById(champ).value; var expression=new RegExp("^[0-9]{1,"+max+"}$", "g"); if (!expression.test(number)){ alert(document.getElementById('error_msg').value); var formulaire_tab=document.forms["formulaire"]; formulaire_tab.elements[champ].value=document.getElementById('tampon').value; } } //fonction permettant de changer la classe css d'une balise function setClass(objet,dmcNom,qui){ objet.className=dmcNom; } //Autorise uniquement la saisie des nombres function number(evt,chemin_tpl,domain,racine,id_product,id_product_attribute,champ_qty) { var keyCode=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0)); if((keyCode>='48' & keyCode<='57') || keyCode=='46'|| keyCode=='8'){ return true; } if(keyCode=='13'){ document.getElementById('enter_detect').value='0'; document.getElementById('enter_detect').value='1'; return true; } return false; } //*********************************************************************************************************************************************** //*********************************************************************************************************************************************** //fonction permettant de sauvegarder le template en cours function save_gp(chemin_tpl) { var url; var params; //creer les variables cacher var ps_root_dir=document.getElementById('ps_root_dir').value; var prefix_cd=document.getElementById('prefix_cd').value; var format_pg=document.getElementById('format_pg').value; var format_spe_lg=document.getElementById('format_spe_lg').value; var format_spe_ht=document.getElementById('format_spe_ht').value; var orientation=document.getElementById('orientation').value; var marge_haut=document.getElementById('marge_haut').value; var marge_gauche=document.getElementById('marge_gauche').value; var rotation=document.getElementById('rotation').value; var largeur_cd=document.getElementById('largeur_cd').value; var hauteur_cd=document.getElementById('hauteur_cd').value; var nb_img_lg=document.getElementById('nb_img_lg').value; var nb_lig=document.getElementById('nb_lig').value; var esp_lg_lg=document.getElementById('esp_lg_lg').value; var esp_cl_cl=document.getElementById('esp_cl_cl').value; url = http_header+domain+racine+'modules/yourbarcode_gp/ajax/save_config.php'; params= 'PS_ROOT_DIR='+ps_root_dir+'&prefix_cd='+prefix_cd+'&format_pg='+format_pg+'&format_spe_lg='+format_spe_lg+'&format_spe_ht='+format_spe_ht+'&orientation='+orientation+'&marge_haut='+marge_haut+'&marge_gauche='+marge_gauche+'&rotation='+rotation+'&largeur_cd='+largeur_cd+'&hauteur_cd='+hauteur_cd+'&nb_img_lg='+nb_img_lg+'&nb_lig='+nb_lig+'&esp_lg_lg='+esp_lg_lg+'&esp_cl_cl='+esp_cl_cl; //alert(params); appel_php_val(url,params); } //fonction permettant de d'appeler une page php function appel_php_val(chemin,params) { var xhr = null; if(window.XMLHttpRequest) // Firefox xhr = new XMLHttpRequest(); else if(window.ActiveXObject) // Internet Explorer xhr = new ActiveXObject("Microsoft.XMLHTTP"); else { // XMLHttpRequest non supporté par le navigateur alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); return; } //var params = 'PS_ROOT_DIR='+ps_root_dir+'&query='+query+'&mailobject='+mailobject+'&select_template_mail='+select_template_mail+'&select_lang='+select_lang; xhr.onreadystatechange = function() { debug_ajx_val(xhr);}; //alert(chemin); xhr.open("POST", chemin, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Content-length", params.length); xhr.send(params); } //fonction permettant le debuggage appel_php function debug_ajx_val (xhr) { if(xhr.readyState!=4) { //afficher merci de patienter } if (xhr.readyState==4){ //recuperation des données du document XML var doc= xhr.responseText; alert(document.getElementById('msg').value); } } <file_sep><?php $dateLastImport = '09/02/2015 19:39:18'; $orders = array ( 0 => array ( 'id_order_ref' => '271737588916-1415333763017', 'id_order_seller' => '284', 'amount' => '320.0', 'status' => 'Complete', 'date' => '2015-01-12 12:13:58', 'email' => 'Invalid Request', 'products' => array ( ), 'error_messages' => array ( 0 => 'Status not complete, amount less than 0.1 or no matching product', ), ), 1 => array ( 'id_order_ref' => '271743112099-1418938576017', 'id_order_seller' => '285', 'amount' => '266.0', 'status' => 'Complete', 'date' => '2015-01-19 11:15:59', 'email' => 'Invalid Request', 'products' => array ( 0 => array ( 'id_product' => 104, 'id_product_attribute' => 0, 'id_ebay_profile' => 0, 'quantity' => '1', 'price' => '264.0', ), ), 'error_messages' => array ( 0 => 'Order already imported', ), ), 2 => array ( 'id_order_ref' => '271743144012-1420560334017', 'id_order_seller' => '286', 'amount' => '50.76', 'status' => 'Complete', 'date' => '2015-01-22 16:54:03', 'email' => 'Invalid Request', 'products' => array ( 0 => array ( 'id_product' => 475, 'id_product_attribute' => 25, 'id_ebay_profile' => 4, 'quantity' => '1', 'price' => '48.76', ), ), 'error_messages' => array ( 0 => 'Order already imported', ), ), 3 => array ( 'id_order_ref' => '271749176867-0', 'id_order_seller' => '287', 'amount' => '266.7', 'status' => 'Complete', 'date' => '2015-01-28 22:49:08', 'email' => '<EMAIL>', 'products' => array ( ), 'error_messages' => array ( 0 => 'Status not complete, amount less than 0.1 or no matching product', ), ), ); <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsAppearanceSettings', false)) return; class AuctionsAppearanceSettings extends CoreModuleSettings { const GLOBAL_BIDDER_NAME = 'auct_app_gl_bid_name'; const GLOBAL_BIDDER_NAME_LENGTH = 'auct_app_gl_bid_namlen'; const DETAILS_COUNTER_FORMAT = 'auct_app_det_count_frmt'; const DETAILS_SHOW_PRICE = 'auct_app_det_price'; const DETAILS_SHOW_START_TIME = 'auct_app_det_st_tim'; const DETAILS_SHOW_CLOSE_TIME = 'auct_app_det_cl_tim'; const DETAILS_SHOW_DURATION = 'auct_app_det_dur'; const DETAILS_SHOW_BIDS = 'auct_app_det_bids'; const DETAILS_SHOW_BIDS_LIST = 'auct_app_det_bids_lst'; const DETAILS_SHOW_WINNER = 'auct_app_det_winner'; const DETAILS_SHOW_STARTING_PRICE = 'auct_app_det_st_prc'; const DETAILS_SHOW_COUNTDOWN = 'auct_app_det_count'; const LIST_COUNTER_FORMAT = 'auct_app_lst_count_frmt'; const LIST_SHOW_PRICE = 'auct_app_lst_price'; const LIST_SHOW_START_TIME = 'auct_app_lst_st_tim'; const LIST_SHOW_CLOSE_TIME = 'auct_app_lst_cl_tim'; const LIST_SHOW_DURATION = 'auct_app_lst_dur'; const LIST_SHOW_BIDS = 'auct_app_lst_bids'; const LIST_SHOW_BIDS_LIST = 'auct_app_lst_bids_lst'; const LIST_SHOW_WINNER = 'auct_app_lst_winner'; const LIST_SHOW_STARTING_PRICE = 'auct_app_lst_st_prc'; const LIST_SHOW_COUNTDOWN = 'auct_app_lst_count'; const SIDE_COUNTER_FORMAT = 'auct_app_side_count_frmt'; const SIDE_SHOW_PRICE = 'auct_app_side_price'; const SIDE_SHOW_START_TIME = 'auct_app_side_st_tim'; const SIDE_SHOW_CLOSE_TIME = 'auct_app_side_cl_tim'; const SIDE_SHOW_DURATION = 'auct_app_side_dur'; const SIDE_SHOW_BIDS = 'auct_app_side_bids'; const SIDE_SHOW_BIDS_LIST = 'auct_app_side_bids_lst'; const SIDE_SHOW_WINNER = 'auct_app_side_winner'; const SIDE_SHOW_STARTING_PRICE = 'auct_app_side_st_prc'; const SIDE_SHOW_COUNTDOWN = 'auct_app_side_count'; const MYAUCTIONS_COUNTER_FORMAT = 'auct_app_myauc_count_frmt'; const MYAUCTIONS_SHOW_PRICE = 'auct_app_myauc_price'; const MYAUCTIONS_SHOW_START_TIME = 'auct_app_myauc_st_tim'; const MYAUCTIONS_SHOW_CLOSE_TIME = 'auct_app_myauc_cl_tim'; const MYAUCTIONS_SHOW_DURATION = 'auct_app_myauc_dur'; const MYAUCTIONS_SHOW_BIDS = 'auct_app_myauc_bids'; const MYAUCTIONS_SHOW_BIDS_LIST = 'auct_app_myauc_bids_lst'; const MYAUCTIONS_SHOW_WINNER = 'auct_app_myauc_winner'; const MYAUCTIONS_SHOW_STARTING_PRICE = 'auct_app_myauc_st_prc'; const MYAUCTIONS_SHOW_COUNTDOWN = 'auct_app_myauc_count'; const EMAIL_COUNTER_FORMAT = 'auct_app_email_count_frmt'; const EMAIL_SHOW_PRICE = 'auct_app_email_price'; const EMAIL_SHOW_START_TIME = 'auct_app_email_st_tim'; const EMAIL_SHOW_CLOSE_TIME = 'auct_app_email_cl_tim'; const EMAIL_SHOW_DURATION = 'auct_app_email_dur'; const EMAIL_SHOW_BIDS = 'auct_app_email_bids'; const EMAIL_SHOW_BIDS_LIST = 'auct_app_email_bids_lst'; const EMAIL_SHOW_WINNER = 'auct_app_email_winner'; const EMAIL_SHOW_STARTING_PRICE = 'auct_app_email_st_prc'; const EMAIL_SHOW_COUNTDOWN = 'auct_app_email_count'; const BID_LIST_DISABLED = 0; const BID_LIST_WINDOW = 1; const BID_LIST_TAB = 2; const COUNTDOWN_DISABLED = 0; const COUNTDOWN_DYNAMIC = 1; const COUNTDOWN_STATIC = 2; const BIDDER_NAME_LIMIT = 20; /** * $this->l('Full name'); * $this->l('First name'); * $this->l('Last name'); * $this->l('Email'); * $this->l('Email alias'); * $this->l('Nickname'); * $this->l('Hidden'); */ protected static $customer_name_formats_list = array( 'FullNameAuctionsCustomerName' => 'Full name', 'FirstNameAuctionsCustomerName' => 'First name', 'LastNameAuctionsCustomerName' => 'Last name', 'EmailAuctionsCustomerName' => 'Email', 'EmailAliasAuctionsCustomerName' => 'Email alias', 'NickNameAuctionsCustomerName' => 'Nickname', 'HiddenAuctionsCustomerName' => 'Hidden', ); protected $submit_action = 'submitAppearance'; public function getTitle() { return $this->l('Appearance'); } public function showForm($tab_index) { $fields_form = array(); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('General'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'select', 'label' => $this->l('Bidder name'), 'name' => self::GLOBAL_BIDDER_NAME, 'required' => false, 'options' => array( 'id' => 'value', 'name' => 'label', 'query' => $this->getCustomerNameFormats() ), 'desc' => $this->l('Choose how winning bidder name will be displayed') ), array( 'type' => 'text', 'label' => $this->l('Bidder name length limit'), 'name' => self::GLOBAL_BIDDER_NAME_LENGTH, 'required' => false, 'desc' => $this->l('Enter maximum number of characters displayed as bidder name.') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Auction details'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('Show start time'), 'name' => self::DETAILS_SHOW_START_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::DETAILS_SHOW_START_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::DETAILS_SHOW_START_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show close time'), 'name' => self::DETAILS_SHOW_CLOSE_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::DETAILS_SHOW_CLOSE_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::DETAILS_SHOW_CLOSE_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show duration'), 'name' => self::DETAILS_SHOW_DURATION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::DETAILS_SHOW_DURATION.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::DETAILS_SHOW_DURATION.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show number of bids'), 'name' => self::DETAILS_SHOW_BIDS, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::DETAILS_SHOW_BIDS.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::DETAILS_SHOW_BIDS.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show list of bids'), 'name' => self::DETAILS_SHOW_BIDS_LIST, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::DETAILS_SHOW_BIDS_LIST.'_tab', 'value' => self::BID_LIST_TAB, 'label' => $this->l('Tab') ), array( 'id' => self::DETAILS_SHOW_BIDS_LIST.'_window', 'value' => self::BID_LIST_WINDOW, 'label' => $this->l('Window') ), array( 'id' => self::DETAILS_SHOW_BIDS_LIST.'_off', 'value' => self::BID_LIST_DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show winning bidder'), 'name' => self::DETAILS_SHOW_WINNER, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::DETAILS_SHOW_WINNER.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::DETAILS_SHOW_WINNER.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show starting price'), 'name' => self::DETAILS_SHOW_STARTING_PRICE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::DETAILS_SHOW_STARTING_PRICE.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::DETAILS_SHOW_STARTING_PRICE.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show countdown'), 'name' => self::DETAILS_SHOW_COUNTDOWN, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::DETAILS_SHOW_COUNTDOWN.'_static', 'value' => self::COUNTDOWN_STATIC, 'label' => $this->l('Static') ), array( 'id' => self::DETAILS_SHOW_COUNTDOWN.'_dynamic', 'value' => self::COUNTDOWN_DYNAMIC, 'label' => $this->l('Dynamic') ), array( 'id' => self::DETAILS_SHOW_COUNTDOWN.'_off', 'value' => self::COUNTDOWN_DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'select', 'label' => $this->l('Counter format'), 'name' => self::DETAILS_COUNTER_FORMAT, 'required' => false, 'options' => array( 'id' => 'value', 'name' => 'label', 'query' => FormattedAuctionsDateTime::getCounterFormats() ), 'desc' => $this->l('Format for time left countdown. Upper case for always displayed, lower case only if non-zero, \'W\' weeks, \'D\' days, \'H\' hours, \'M\' minutes, \'S\' seconds') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Auctions list'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('Show start time'), 'name' => self::LIST_SHOW_START_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::LIST_SHOW_START_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::LIST_SHOW_START_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show close time'), 'name' => self::LIST_SHOW_CLOSE_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::LIST_SHOW_CLOSE_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::LIST_SHOW_CLOSE_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show duration'), 'name' => self::LIST_SHOW_DURATION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::LIST_SHOW_DURATION.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::LIST_SHOW_DURATION.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show number of bids'), 'name' => self::LIST_SHOW_BIDS, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::LIST_SHOW_BIDS.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::LIST_SHOW_BIDS.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show list of bids'), 'name' => self::LIST_SHOW_BIDS_LIST, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::LIST_SHOW_BIDS_LIST.'_window', 'value' => self::BID_LIST_WINDOW, 'label' => $this->l('Window') ), array( 'id' => self::LIST_SHOW_BIDS_LIST.'_off', 'value' => self::BID_LIST_DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show winning bidder'), 'name' => self::LIST_SHOW_WINNER, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::LIST_SHOW_WINNER.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::LIST_SHOW_WINNER.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show starting price'), 'name' => self::LIST_SHOW_STARTING_PRICE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::LIST_SHOW_STARTING_PRICE.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::LIST_SHOW_STARTING_PRICE.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show countdown'), 'name' => self::LIST_SHOW_COUNTDOWN, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::LIST_SHOW_COUNTDOWN.'_static', 'value' => self::COUNTDOWN_STATIC, 'label' => $this->l('Static') ), array( 'id' => self::LIST_SHOW_COUNTDOWN.'_dynamic', 'value' => self::COUNTDOWN_DYNAMIC, 'label' => $this->l('Dynamic') ), array( 'id' => self::LIST_SHOW_COUNTDOWN.'_off', 'value' => self::COUNTDOWN_DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'select', 'label' => $this->l('Counter format'), 'name' => self::LIST_COUNTER_FORMAT, 'required' => false, 'options' => array( 'id' => 'value', 'name' => 'label', 'query' => FormattedAuctionsDateTime::getCounterFormats() ), 'desc' => $this->l('Format for time left countdown. Upper case for always displayed, lower case only if non-zero, \'W\' weeks, \'D\' days, \'H\' hours, \'M\' minutes, \'S\' seconds') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Side blocks'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('Show current price'), 'name' => self::SIDE_SHOW_PRICE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::SIDE_SHOW_PRICE.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::SIDE_SHOW_PRICE.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show start time'), 'name' => self::SIDE_SHOW_START_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::SIDE_SHOW_START_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::SIDE_SHOW_START_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show close time'), 'name' => self::SIDE_SHOW_CLOSE_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::SIDE_SHOW_CLOSE_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::SIDE_SHOW_CLOSE_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show duration'), 'name' => self::SIDE_SHOW_DURATION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::SIDE_SHOW_DURATION.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::SIDE_SHOW_DURATION.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show number of bids'), 'name' => self::SIDE_SHOW_BIDS, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::SIDE_SHOW_BIDS.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::SIDE_SHOW_BIDS.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show list of bids'), 'name' => self::SIDE_SHOW_BIDS_LIST, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::SIDE_SHOW_BIDS_LIST.'_window', 'value' => self::BID_LIST_WINDOW, 'label' => $this->l('Window') ), array( 'id' => self::SIDE_SHOW_BIDS_LIST.'_off', 'value' => self::BID_LIST_DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show winning bidder'), 'name' => self::SIDE_SHOW_WINNER, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::SIDE_SHOW_WINNER.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::SIDE_SHOW_WINNER.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show starting price'), 'name' => self::SIDE_SHOW_STARTING_PRICE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::SIDE_SHOW_STARTING_PRICE.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::SIDE_SHOW_STARTING_PRICE.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show countdown'), 'name' => self::SIDE_SHOW_COUNTDOWN, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::SIDE_SHOW_COUNTDOWN.'_static', 'value' => self::COUNTDOWN_STATIC, 'label' => $this->l('Static') ), array( 'id' => self::SIDE_SHOW_COUNTDOWN.'_dynamic', 'value' => self::COUNTDOWN_DYNAMIC, 'label' => $this->l('Dynamic') ), array( 'id' => self::SIDE_SHOW_COUNTDOWN.'_off', 'value' => self::COUNTDOWN_DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'select', 'label' => $this->l('Counter format'), 'name' => self::SIDE_COUNTER_FORMAT, 'required' => false, 'options' => array( 'id' => 'value', 'name' => 'label', 'query' => FormattedAuctionsDateTime::getCounterFormats() ), 'desc' => $this->l('Format for time left countdown. Upper case for always displayed, lower case only if non-zero, \'W\' weeks, \'D\' days, \'H\' hours, \'M\' minutes, \'S\' seconds') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('My auctions'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('Show current price'), 'name' => self::MYAUCTIONS_SHOW_PRICE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::MYAUCTIONS_SHOW_PRICE.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::MYAUCTIONS_SHOW_PRICE.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show start time'), 'name' => self::MYAUCTIONS_SHOW_START_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::MYAUCTIONS_SHOW_START_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::MYAUCTIONS_SHOW_START_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show close time'), 'name' => self::MYAUCTIONS_SHOW_CLOSE_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::MYAUCTIONS_SHOW_CLOSE_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::MYAUCTIONS_SHOW_CLOSE_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show duration'), 'name' => self::MYAUCTIONS_SHOW_DURATION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::MYAUCTIONS_SHOW_DURATION.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::MYAUCTIONS_SHOW_DURATION.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show number of bids'), 'name' => self::MYAUCTIONS_SHOW_BIDS, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::MYAUCTIONS_SHOW_BIDS.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::MYAUCTIONS_SHOW_BIDS.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show list of bids'), 'name' => self::MYAUCTIONS_SHOW_BIDS_LIST, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::MYAUCTIONS_SHOW_BIDS_LIST.'_window', 'value' => self::BID_LIST_WINDOW, 'label' => $this->l('Window') ), array( 'id' => self::MYAUCTIONS_SHOW_BIDS_LIST.'_off', 'value' => self::BID_LIST_DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show winning bidder'), 'name' => self::MYAUCTIONS_SHOW_WINNER, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::MYAUCTIONS_SHOW_WINNER.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::MYAUCTIONS_SHOW_WINNER.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show starting price'), 'name' => self::MYAUCTIONS_SHOW_STARTING_PRICE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::MYAUCTIONS_SHOW_STARTING_PRICE.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::MYAUCTIONS_SHOW_STARTING_PRICE.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show countdown'), 'name' => self::MYAUCTIONS_SHOW_COUNTDOWN, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::MYAUCTIONS_SHOW_COUNTDOWN.'_static', 'value' => self::COUNTDOWN_STATIC, 'label' => $this->l('Static') ), array( 'id' => self::MYAUCTIONS_SHOW_COUNTDOWN.'_dynamic', 'value' => self::COUNTDOWN_DYNAMIC, 'label' => $this->l('Dynamic') ), array( 'id' => self::MYAUCTIONS_SHOW_COUNTDOWN.'_off', 'value' => self::COUNTDOWN_DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'select', 'label' => $this->l('Counter format'), 'name' => self::MYAUCTIONS_COUNTER_FORMAT, 'required' => false, 'options' => array( 'id' => 'value', 'name' => 'label', 'query' => FormattedAuctionsDateTime::getCounterFormats() ), 'desc' => $this->l('Format for time left countdown. Upper case for always displayed, lower case only if non-zero, \'W\' weeks, \'D\' days, \'H\' hours, \'M\' minutes, \'S\' seconds') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Emails'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('Show current price'), 'name' => self::EMAIL_SHOW_PRICE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::EMAIL_SHOW_PRICE.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::EMAIL_SHOW_PRICE.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show start time'), 'name' => self::EMAIL_SHOW_START_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::EMAIL_SHOW_START_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::EMAIL_SHOW_START_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show close time'), 'name' => self::EMAIL_SHOW_CLOSE_TIME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::EMAIL_SHOW_CLOSE_TIME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::EMAIL_SHOW_CLOSE_TIME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show duration'), 'name' => self::EMAIL_SHOW_DURATION, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::EMAIL_SHOW_DURATION.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::EMAIL_SHOW_DURATION.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show number of bids'), 'name' => self::EMAIL_SHOW_BIDS, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::EMAIL_SHOW_BIDS.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::EMAIL_SHOW_BIDS.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show winning bidder'), 'name' => self::EMAIL_SHOW_WINNER, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::EMAIL_SHOW_WINNER.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::EMAIL_SHOW_WINNER.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show starting price'), 'name' => self::EMAIL_SHOW_STARTING_PRICE, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::EMAIL_SHOW_STARTING_PRICE.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::EMAIL_SHOW_STARTING_PRICE.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'radio', 'label' => $this->l('Show countdown'), 'name' => self::EMAIL_SHOW_COUNTDOWN, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::EMAIL_SHOW_COUNTDOWN.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::EMAIL_SHOW_COUNTDOWN.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ) ), array( 'type' => 'select', 'label' => $this->l('Counter format'), 'name' => self::EMAIL_COUNTER_FORMAT, 'required' => false, 'options' => array( 'id' => 'value', 'name' => 'label', 'query' => FormattedAuctionsDateTime::getCounterFormats() ), 'desc' => $this->l('Format for time left countdown. Upper case for always displayed, lower case only if non-zero, \'W\' weeks, \'D\' days, \'H\' hours, \'M\' minutes, \'S\' seconds') ) ) ) ); return $this->renderForm($fields_form, $tab_index); } public function init() { $this->setValue(self::GLOBAL_BIDDER_NAME, Configuration::get(self::GLOBAL_BIDDER_NAME)); $this->setValue(self::GLOBAL_BIDDER_NAME_LENGTH, Configuration::get(self::GLOBAL_BIDDER_NAME_LENGTH)); $this->setValue(self::DETAILS_COUNTER_FORMAT, Configuration::get(self::DETAILS_COUNTER_FORMAT)); $this->setValue(self::DETAILS_SHOW_PRICE, Configuration::get(self::DETAILS_SHOW_PRICE)); $this->setValue(self::DETAILS_SHOW_START_TIME, Configuration::get(self::DETAILS_SHOW_START_TIME)); $this->setValue(self::DETAILS_SHOW_CLOSE_TIME, Configuration::get(self::DETAILS_SHOW_CLOSE_TIME)); $this->setValue(self::DETAILS_SHOW_DURATION, Configuration::get(self::DETAILS_SHOW_DURATION)); $this->setValue(self::DETAILS_SHOW_BIDS, Configuration::get(self::DETAILS_SHOW_BIDS)); $this->setValue(self::DETAILS_SHOW_BIDS_LIST, Configuration::get(self::DETAILS_SHOW_BIDS_LIST)); $this->setValue(self::DETAILS_SHOW_WINNER, Configuration::get(self::DETAILS_SHOW_WINNER)); $this->setValue(self::DETAILS_SHOW_STARTING_PRICE, Configuration::get(self::DETAILS_SHOW_STARTING_PRICE)); $this->setValue(self::DETAILS_SHOW_COUNTDOWN, Configuration::get(self::DETAILS_SHOW_COUNTDOWN)); $this->setValue(self::LIST_COUNTER_FORMAT, Configuration::get(self::LIST_COUNTER_FORMAT)); $this->setValue(self::LIST_SHOW_PRICE, Configuration::get(self::LIST_SHOW_PRICE)); $this->setValue(self::LIST_SHOW_START_TIME, Configuration::get(self::LIST_SHOW_START_TIME)); $this->setValue(self::LIST_SHOW_CLOSE_TIME, Configuration::get(self::LIST_SHOW_CLOSE_TIME)); $this->setValue(self::LIST_SHOW_DURATION, Configuration::get(self::LIST_SHOW_DURATION)); $this->setValue(self::LIST_SHOW_BIDS, Configuration::get(self::LIST_SHOW_BIDS)); $this->setValue(self::LIST_SHOW_BIDS_LIST, Configuration::get(self::LIST_SHOW_BIDS_LIST)); $this->setValue(self::LIST_SHOW_WINNER, Configuration::get(self::LIST_SHOW_WINNER)); $this->setValue(self::LIST_SHOW_STARTING_PRICE, Configuration::get(self::LIST_SHOW_STARTING_PRICE)); $this->setValue(self::LIST_SHOW_COUNTDOWN, Configuration::get(self::LIST_SHOW_COUNTDOWN)); $this->setValue(self::SIDE_COUNTER_FORMAT, Configuration::get(self::SIDE_COUNTER_FORMAT)); $this->setValue(self::SIDE_SHOW_PRICE, Configuration::get(self::SIDE_SHOW_PRICE)); $this->setValue(self::SIDE_SHOW_START_TIME, Configuration::get(self::SIDE_SHOW_START_TIME)); $this->setValue(self::SIDE_SHOW_CLOSE_TIME, Configuration::get(self::SIDE_SHOW_CLOSE_TIME)); $this->setValue(self::SIDE_SHOW_DURATION, Configuration::get(self::SIDE_SHOW_DURATION)); $this->setValue(self::SIDE_SHOW_BIDS, Configuration::get(self::SIDE_SHOW_BIDS)); $this->setValue(self::SIDE_SHOW_BIDS_LIST, Configuration::get(self::SIDE_SHOW_BIDS_LIST)); $this->setValue(self::SIDE_SHOW_WINNER, Configuration::get(self::SIDE_SHOW_WINNER)); $this->setValue(self::SIDE_SHOW_STARTING_PRICE, Configuration::get(self::SIDE_SHOW_STARTING_PRICE)); $this->setValue(self::SIDE_SHOW_COUNTDOWN, Configuration::get(self::SIDE_SHOW_COUNTDOWN)); $this->setValue(self::MYAUCTIONS_COUNTER_FORMAT, Configuration::get(self::MYAUCTIONS_COUNTER_FORMAT)); $this->setValue(self::MYAUCTIONS_SHOW_PRICE, Configuration::get(self::MYAUCTIONS_SHOW_PRICE)); $this->setValue(self::MYAUCTIONS_SHOW_START_TIME, Configuration::get(self::MYAUCTIONS_SHOW_START_TIME)); $this->setValue(self::MYAUCTIONS_SHOW_CLOSE_TIME, Configuration::get(self::MYAUCTIONS_SHOW_CLOSE_TIME)); $this->setValue(self::MYAUCTIONS_SHOW_DURATION, Configuration::get(self::MYAUCTIONS_SHOW_DURATION)); $this->setValue(self::MYAUCTIONS_SHOW_BIDS, Configuration::get(self::MYAUCTIONS_SHOW_BIDS)); $this->setValue(self::MYAUCTIONS_SHOW_BIDS_LIST, Configuration::get(self::MYAUCTIONS_SHOW_BIDS_LIST)); $this->setValue(self::MYAUCTIONS_SHOW_WINNER, Configuration::get(self::MYAUCTIONS_SHOW_WINNER)); $this->setValue(self::MYAUCTIONS_SHOW_STARTING_PRICE, Configuration::get(self::MYAUCTIONS_SHOW_STARTING_PRICE)); $this->setValue(self::MYAUCTIONS_SHOW_COUNTDOWN, Configuration::get(self::MYAUCTIONS_SHOW_COUNTDOWN)); $this->setValue(self::EMAIL_COUNTER_FORMAT, Configuration::get(self::EMAIL_COUNTER_FORMAT)); $this->setValue(self::EMAIL_SHOW_PRICE, Configuration::get(self::EMAIL_SHOW_PRICE)); $this->setValue(self::EMAIL_SHOW_START_TIME, Configuration::get(self::EMAIL_SHOW_START_TIME)); $this->setValue(self::EMAIL_SHOW_CLOSE_TIME, Configuration::get(self::EMAIL_SHOW_CLOSE_TIME)); $this->setValue(self::EMAIL_SHOW_DURATION, Configuration::get(self::EMAIL_SHOW_DURATION)); $this->setValue(self::EMAIL_SHOW_BIDS, Configuration::get(self::EMAIL_SHOW_BIDS)); $this->setValue(self::EMAIL_SHOW_BIDS_LIST, Configuration::get(self::EMAIL_SHOW_BIDS_LIST)); $this->setValue(self::EMAIL_SHOW_WINNER, Configuration::get(self::EMAIL_SHOW_WINNER)); $this->setValue(self::EMAIL_SHOW_STARTING_PRICE, Configuration::get(self::EMAIL_SHOW_STARTING_PRICE)); $this->setValue(self::EMAIL_SHOW_COUNTDOWN, Configuration::get(self::EMAIL_SHOW_COUNTDOWN)); } public function install() { $counter_formats = FormattedAuctionsDateTime::getCounterFormats(); Configuration::updateValue(self::GLOBAL_BIDDER_NAME, 'FirstNameAuctionsCustomerName'); Configuration::updateValue(self::GLOBAL_BIDDER_NAME_LENGTH, self::BIDDER_NAME_LIMIT); Configuration::updateValue(self::DETAILS_COUNTER_FORMAT, $counter_formats[1]['value']); Configuration::updateValue(self::DETAILS_SHOW_PRICE, self::ENABLED); Configuration::updateValue(self::DETAILS_SHOW_START_TIME, self::DISABLED); Configuration::updateValue(self::DETAILS_SHOW_CLOSE_TIME, self::DISABLED); Configuration::updateValue(self::DETAILS_SHOW_DURATION, self::DISABLED); Configuration::updateValue(self::DETAILS_SHOW_BIDS, self::ENABLED); Configuration::updateValue(self::DETAILS_SHOW_BIDS_LIST, self::BID_LIST_TAB); Configuration::updateValue(self::DETAILS_SHOW_WINNER, self::ENABLED); Configuration::updateValue(self::DETAILS_SHOW_STARTING_PRICE, self::DISABLED); Configuration::updateValue(self::DETAILS_SHOW_COUNTDOWN, self::COUNTDOWN_DYNAMIC); Configuration::updateValue(self::LIST_COUNTER_FORMAT, $counter_formats[1]['value']); Configuration::updateValue(self::LIST_SHOW_PRICE, self::ENABLED); Configuration::updateValue(self::LIST_SHOW_START_TIME, self::DISABLED); Configuration::updateValue(self::LIST_SHOW_CLOSE_TIME, self::DISABLED); Configuration::updateValue(self::LIST_SHOW_DURATION, self::DISABLED); Configuration::updateValue(self::LIST_SHOW_BIDS, self::ENABLED); Configuration::updateValue(self::LIST_SHOW_BIDS_LIST, self::BID_LIST_DISABLED); Configuration::updateValue(self::LIST_SHOW_WINNER, self::ENABLED); Configuration::updateValue(self::LIST_SHOW_STARTING_PRICE, self::DISABLED); Configuration::updateValue(self::LIST_SHOW_COUNTDOWN, self::COUNTDOWN_DYNAMIC); Configuration::updateValue(self::SIDE_COUNTER_FORMAT, $counter_formats[1]['value']); Configuration::updateValue(self::SIDE_SHOW_PRICE, self::ENABLED); Configuration::updateValue(self::SIDE_SHOW_START_TIME, self::DISABLED); Configuration::updateValue(self::SIDE_SHOW_CLOSE_TIME, self::DISABLED); Configuration::updateValue(self::SIDE_SHOW_DURATION, self::DISABLED); Configuration::updateValue(self::SIDE_SHOW_BIDS, self::ENABLED); Configuration::updateValue(self::SIDE_SHOW_BIDS_LIST, self::BID_LIST_DISABLED); Configuration::updateValue(self::SIDE_SHOW_WINNER, self::ENABLED); Configuration::updateValue(self::SIDE_SHOW_STARTING_PRICE, self::DISABLED); Configuration::updateValue(self::SIDE_SHOW_COUNTDOWN, self::COUNTDOWN_DYNAMIC); Configuration::updateValue(self::MYAUCTIONS_COUNTER_FORMAT, $counter_formats[1]['value']); Configuration::updateValue(self::MYAUCTIONS_SHOW_PRICE, self::ENABLED); Configuration::updateValue(self::MYAUCTIONS_SHOW_START_TIME, self::DISABLED); Configuration::updateValue(self::MYAUCTIONS_SHOW_CLOSE_TIME, self::DISABLED); Configuration::updateValue(self::MYAUCTIONS_SHOW_DURATION, self::DISABLED); Configuration::updateValue(self::MYAUCTIONS_SHOW_BIDS, self::ENABLED); Configuration::updateValue(self::MYAUCTIONS_SHOW_BIDS_LIST, self::BID_LIST_WINDOW); Configuration::updateValue(self::MYAUCTIONS_SHOW_WINNER, self::ENABLED); Configuration::updateValue(self::MYAUCTIONS_SHOW_STARTING_PRICE, self::DISABLED); Configuration::updateValue(self::MYAUCTIONS_SHOW_COUNTDOWN, self::COUNTDOWN_DYNAMIC); Configuration::updateValue(self::EMAIL_COUNTER_FORMAT, $counter_formats[1]['value']); Configuration::updateValue(self::EMAIL_SHOW_PRICE, self::ENABLED); Configuration::updateValue(self::EMAIL_SHOW_START_TIME, self::DISABLED); Configuration::updateValue(self::EMAIL_SHOW_CLOSE_TIME, self::DISABLED); Configuration::updateValue(self::EMAIL_SHOW_DURATION, self::DISABLED); Configuration::updateValue(self::EMAIL_SHOW_BIDS, self::ENABLED); Configuration::updateValue(self::EMAIL_SHOW_BIDS_LIST, self::BID_LIST_DISABLED); Configuration::updateValue(self::EMAIL_SHOW_WINNER, self::ENABLED); Configuration::updateValue(self::EMAIL_SHOW_STARTING_PRICE, self::DISABLED); Configuration::updateValue(self::EMAIL_SHOW_COUNTDOWN, self::ENABLED); return true; } public function uninstall() { Configuration::deleteByName(self::GLOBAL_BIDDER_NAME); Configuration::deleteByName(self::GLOBAL_BIDDER_NAME_LENGTH); Configuration::deleteByName(self::DETAILS_COUNTER_FORMAT); Configuration::deleteByName(self::DETAILS_SHOW_PRICE); Configuration::deleteByName(self::DETAILS_SHOW_START_TIME); Configuration::deleteByName(self::DETAILS_SHOW_CLOSE_TIME); Configuration::deleteByName(self::DETAILS_SHOW_DURATION); Configuration::deleteByName(self::DETAILS_SHOW_BIDS); Configuration::deleteByName(self::DETAILS_SHOW_BIDS_LIST); Configuration::deleteByName(self::DETAILS_SHOW_WINNER); Configuration::deleteByName(self::DETAILS_SHOW_STARTING_PRICE); Configuration::deleteByName(self::DETAILS_SHOW_COUNTDOWN); Configuration::deleteByName(self::LIST_COUNTER_FORMAT); Configuration::deleteByName(self::LIST_SHOW_PRICE); Configuration::deleteByName(self::LIST_SHOW_START_TIME); Configuration::deleteByName(self::LIST_SHOW_CLOSE_TIME); Configuration::deleteByName(self::LIST_SHOW_DURATION); Configuration::deleteByName(self::LIST_SHOW_BIDS); Configuration::deleteByName(self::LIST_SHOW_BIDS_LIST); Configuration::deleteByName(self::LIST_SHOW_WINNER); Configuration::deleteByName(self::LIST_SHOW_STARTING_PRICE); Configuration::deleteByName(self::LIST_SHOW_COUNTDOWN); Configuration::deleteByName(self::SIDE_COUNTER_FORMAT); Configuration::deleteByName(self::SIDE_SHOW_PRICE); Configuration::deleteByName(self::SIDE_SHOW_START_TIME); Configuration::deleteByName(self::SIDE_SHOW_CLOSE_TIME); Configuration::deleteByName(self::SIDE_SHOW_DURATION); Configuration::deleteByName(self::SIDE_SHOW_BIDS); Configuration::deleteByName(self::SIDE_SHOW_BIDS_LIST); Configuration::deleteByName(self::SIDE_SHOW_WINNER); Configuration::deleteByName(self::SIDE_SHOW_STARTING_PRICE); Configuration::deleteByName(self::SIDE_SHOW_COUNTDOWN); Configuration::deleteByName(self::MYAUCTIONS_COUNTER_FORMAT); Configuration::deleteByName(self::MYAUCTIONS_SHOW_PRICE); Configuration::deleteByName(self::MYAUCTIONS_SHOW_START_TIME); Configuration::deleteByName(self::MYAUCTIONS_SHOW_CLOSE_TIME); Configuration::deleteByName(self::MYAUCTIONS_SHOW_DURATION); Configuration::deleteByName(self::MYAUCTIONS_SHOW_BIDS); Configuration::deleteByName(self::MYAUCTIONS_SHOW_BIDS_LIST); Configuration::deleteByName(self::MYAUCTIONS_SHOW_WINNER); Configuration::deleteByName(self::MYAUCTIONS_SHOW_STARTING_PRICE); Configuration::deleteByName(self::MYAUCTIONS_SHOW_COUNTDOWN); Configuration::deleteByName(self::EMAIL_COUNTER_FORMAT); Configuration::deleteByName(self::EMAIL_SHOW_PRICE); Configuration::deleteByName(self::EMAIL_SHOW_START_TIME); Configuration::deleteByName(self::EMAIL_SHOW_CLOSE_TIME); Configuration::deleteByName(self::EMAIL_SHOW_DURATION); Configuration::deleteByName(self::EMAIL_SHOW_BIDS); Configuration::deleteByName(self::EMAIL_SHOW_BIDS_LIST); Configuration::deleteByName(self::EMAIL_SHOW_WINNER); Configuration::deleteByName(self::EMAIL_SHOW_STARTING_PRICE); Configuration::deleteByName(self::EMAIL_SHOW_COUNTDOWN); return true; } public function update() { Configuration::updateValue(self::GLOBAL_BIDDER_NAME, Tools::getValue(self::GLOBAL_BIDDER_NAME)); Configuration::updateValue(self::GLOBAL_BIDDER_NAME_LENGTH, Tools::getValue(self::GLOBAL_BIDDER_NAME_LENGTH)); Configuration::updateValue(self::DETAILS_COUNTER_FORMAT, Tools::getValue(self::DETAILS_COUNTER_FORMAT)); Configuration::updateValue(self::DETAILS_SHOW_PRICE, Tools::getValue(self::DETAILS_SHOW_PRICE)); Configuration::updateValue(self::DETAILS_SHOW_START_TIME, Tools::getValue(self::DETAILS_SHOW_START_TIME)); Configuration::updateValue(self::DETAILS_SHOW_CLOSE_TIME, Tools::getValue(self::DETAILS_SHOW_CLOSE_TIME)); Configuration::updateValue(self::DETAILS_SHOW_DURATION, Tools::getValue(self::DETAILS_SHOW_DURATION)); Configuration::updateValue(self::DETAILS_SHOW_BIDS, Tools::getValue(self::DETAILS_SHOW_BIDS)); Configuration::updateValue(self::DETAILS_SHOW_BIDS_LIST, Tools::getValue(self::DETAILS_SHOW_BIDS_LIST)); Configuration::updateValue(self::DETAILS_SHOW_WINNER, Tools::getValue(self::DETAILS_SHOW_WINNER)); Configuration::updateValue(self::DETAILS_SHOW_STARTING_PRICE, Tools::getValue(self::DETAILS_SHOW_STARTING_PRICE)); Configuration::updateValue(self::DETAILS_SHOW_COUNTDOWN, Tools::getValue(self::DETAILS_SHOW_COUNTDOWN)); Configuration::updateValue(self::LIST_COUNTER_FORMAT, Tools::getValue(self::LIST_COUNTER_FORMAT)); Configuration::updateValue(self::LIST_SHOW_PRICE, Tools::getValue(self::LIST_SHOW_PRICE)); Configuration::updateValue(self::LIST_SHOW_START_TIME, Tools::getValue(self::LIST_SHOW_START_TIME)); Configuration::updateValue(self::LIST_SHOW_CLOSE_TIME, Tools::getValue(self::LIST_SHOW_CLOSE_TIME)); Configuration::updateValue(self::LIST_SHOW_DURATION, Tools::getValue(self::LIST_SHOW_DURATION)); Configuration::updateValue(self::LIST_SHOW_BIDS, Tools::getValue(self::LIST_SHOW_BIDS)); Configuration::updateValue(self::LIST_SHOW_BIDS_LIST, Tools::getValue(self::LIST_SHOW_BIDS_LIST)); Configuration::updateValue(self::LIST_SHOW_WINNER, Tools::getValue(self::LIST_SHOW_WINNER)); Configuration::updateValue(self::LIST_SHOW_STARTING_PRICE, Tools::getValue(self::LIST_SHOW_STARTING_PRICE)); Configuration::updateValue(self::LIST_SHOW_COUNTDOWN, Tools::getValue(self::LIST_SHOW_COUNTDOWN)); Configuration::updateValue(self::SIDE_COUNTER_FORMAT, Tools::getValue(self::SIDE_COUNTER_FORMAT)); Configuration::updateValue(self::SIDE_SHOW_PRICE, Tools::getValue(self::SIDE_SHOW_PRICE)); Configuration::updateValue(self::SIDE_SHOW_START_TIME, Tools::getValue(self::SIDE_SHOW_START_TIME)); Configuration::updateValue(self::SIDE_SHOW_CLOSE_TIME, Tools::getValue(self::SIDE_SHOW_CLOSE_TIME)); Configuration::updateValue(self::SIDE_SHOW_DURATION, Tools::getValue(self::SIDE_SHOW_DURATION)); Configuration::updateValue(self::SIDE_SHOW_BIDS, Tools::getValue(self::SIDE_SHOW_BIDS)); Configuration::updateValue(self::SIDE_SHOW_BIDS_LIST, Tools::getValue(self::SIDE_SHOW_BIDS_LIST)); Configuration::updateValue(self::SIDE_SHOW_WINNER, Tools::getValue(self::SIDE_SHOW_WINNER)); Configuration::updateValue(self::SIDE_SHOW_STARTING_PRICE, Tools::getValue(self::SIDE_SHOW_STARTING_PRICE)); Configuration::updateValue(self::SIDE_SHOW_COUNTDOWN, Tools::getValue(self::SIDE_SHOW_COUNTDOWN)); Configuration::updateValue(self::MYAUCTIONS_COUNTER_FORMAT, Tools::getValue(self::MYAUCTIONS_COUNTER_FORMAT)); Configuration::updateValue(self::MYAUCTIONS_SHOW_PRICE, Tools::getValue(self::MYAUCTIONS_SHOW_PRICE)); Configuration::updateValue(self::MYAUCTIONS_SHOW_START_TIME, Tools::getValue(self::MYAUCTIONS_SHOW_START_TIME)); Configuration::updateValue(self::MYAUCTIONS_SHOW_CLOSE_TIME, Tools::getValue(self::MYAUCTIONS_SHOW_CLOSE_TIME)); Configuration::updateValue(self::MYAUCTIONS_SHOW_DURATION, Tools::getValue(self::MYAUCTIONS_SHOW_DURATION)); Configuration::updateValue(self::MYAUCTIONS_SHOW_BIDS, Tools::getValue(self::MYAUCTIONS_SHOW_BIDS)); Configuration::updateValue(self::MYAUCTIONS_SHOW_BIDS_LIST, Tools::getValue(self::MYAUCTIONS_SHOW_BIDS_LIST)); Configuration::updateValue(self::MYAUCTIONS_SHOW_WINNER, Tools::getValue(self::MYAUCTIONS_SHOW_WINNER)); Configuration::updateValue(self::MYAUCTIONS_SHOW_STARTING_PRICE, Tools::getValue(self::MYAUCTIONS_SHOW_STARTING_PRICE)); Configuration::updateValue(self::MYAUCTIONS_SHOW_COUNTDOWN, Tools::getValue(self::MYAUCTIONS_SHOW_COUNTDOWN)); Configuration::updateValue(self::EMAIL_COUNTER_FORMAT, Tools::getValue(self::EMAIL_COUNTER_FORMAT)); Configuration::updateValue(self::EMAIL_SHOW_PRICE, Tools::getValue(self::EMAIL_SHOW_PRICE)); Configuration::updateValue(self::EMAIL_SHOW_START_TIME, Tools::getValue(self::EMAIL_SHOW_START_TIME)); Configuration::updateValue(self::EMAIL_SHOW_CLOSE_TIME, Tools::getValue(self::EMAIL_SHOW_CLOSE_TIME)); Configuration::updateValue(self::EMAIL_SHOW_DURATION, Tools::getValue(self::EMAIL_SHOW_DURATION)); Configuration::updateValue(self::EMAIL_SHOW_BIDS, Tools::getValue(self::EMAIL_SHOW_BIDS)); Configuration::updateValue(self::EMAIL_SHOW_BIDS_LIST, Tools::getValue(self::EMAIL_SHOW_BIDS_LIST)); Configuration::updateValue(self::EMAIL_SHOW_WINNER, Tools::getValue(self::EMAIL_SHOW_WINNER)); Configuration::updateValue(self::EMAIL_SHOW_STARTING_PRICE, Tools::getValue(self::EMAIL_SHOW_STARTING_PRICE)); Configuration::updateValue(self::EMAIL_SHOW_COUNTDOWN, Tools::getValue(self::EMAIL_SHOW_COUNTDOWN)); return true; } protected function validate() { $condition = true; $condition &= Validate::isString(Tools::getValue(self::GLOBAL_BIDDER_NAME)); $condition &= Validate::isInt(Tools::getValue(self::GLOBAL_BIDDER_NAME_LENGTH)); $condition &= Validate::isString(Tools::getValue(self::DETAILS_COUNTER_FORMAT)); $condition &= Validate::isBool(Tools::getValue(self::DETAILS_SHOW_PRICE)); $condition &= Validate::isBool(Tools::getValue(self::DETAILS_SHOW_START_TIME)); $condition &= Validate::isBool(Tools::getValue(self::DETAILS_SHOW_CLOSE_TIME)); $condition &= Validate::isBool(Tools::getValue(self::DETAILS_SHOW_DURATION)); $condition &= Validate::isBool(Tools::getValue(self::DETAILS_SHOW_BIDS)); $condition &= Validate::isInt(Tools::getValue(self::DETAILS_SHOW_BIDS_LIST)); $condition &= Validate::isBool(Tools::getValue(self::DETAILS_SHOW_WINNER)); $condition &= Validate::isBool(Tools::getValue(self::DETAILS_SHOW_STARTING_PRICE)); $condition &= Validate::isInt(Tools::getValue(self::DETAILS_SHOW_COUNTDOWN)); $condition &= Validate::isString(Tools::getValue(self::LIST_COUNTER_FORMAT)); $condition &= Validate::isBool(Tools::getValue(self::LIST_SHOW_PRICE)); $condition &= Validate::isBool(Tools::getValue(self::LIST_SHOW_START_TIME)); $condition &= Validate::isBool(Tools::getValue(self::LIST_SHOW_CLOSE_TIME)); $condition &= Validate::isBool(Tools::getValue(self::LIST_SHOW_DURATION)); $condition &= Validate::isBool(Tools::getValue(self::LIST_SHOW_BIDS)); $condition &= Validate::isInt(Tools::getValue(self::LIST_SHOW_BIDS_LIST)); $condition &= Validate::isBool(Tools::getValue(self::LIST_SHOW_WINNER)); $condition &= Validate::isBool(Tools::getValue(self::LIST_SHOW_STARTING_PRICE)); $condition &= Validate::isInt(Tools::getValue(self::LIST_SHOW_COUNTDOWN)); $condition &= Validate::isString(Tools::getValue(self::SIDE_COUNTER_FORMAT)); $condition &= Validate::isBool(Tools::getValue(self::SIDE_SHOW_PRICE)); $condition &= Validate::isBool(Tools::getValue(self::SIDE_SHOW_START_TIME)); $condition &= Validate::isBool(Tools::getValue(self::SIDE_SHOW_CLOSE_TIME)); $condition &= Validate::isBool(Tools::getValue(self::SIDE_SHOW_DURATION)); $condition &= Validate::isBool(Tools::getValue(self::SIDE_SHOW_BIDS)); $condition &= Validate::isInt(Tools::getValue(self::SIDE_SHOW_BIDS_LIST)); $condition &= Validate::isBool(Tools::getValue(self::SIDE_SHOW_WINNER)); $condition &= Validate::isBool(Tools::getValue(self::SIDE_SHOW_STARTING_PRICE)); $condition &= Validate::isInt(Tools::getValue(self::SIDE_SHOW_COUNTDOWN)); $condition &= Validate::isString(Tools::getValue(self::MYAUCTIONS_COUNTER_FORMAT)); $condition &= Validate::isBool(Tools::getValue(self::MYAUCTIONS_SHOW_PRICE)); $condition &= Validate::isBool(Tools::getValue(self::MYAUCTIONS_SHOW_START_TIME)); $condition &= Validate::isBool(Tools::getValue(self::MYAUCTIONS_SHOW_CLOSE_TIME)); $condition &= Validate::isBool(Tools::getValue(self::MYAUCTIONS_SHOW_DURATION)); $condition &= Validate::isBool(Tools::getValue(self::MYAUCTIONS_SHOW_BIDS)); $condition &= Validate::isInt(Tools::getValue(self::MYAUCTIONS_SHOW_BIDS_LIST)); $condition &= Validate::isBool(Tools::getValue(self::MYAUCTIONS_SHOW_WINNER)); $condition &= Validate::isBool(Tools::getValue(self::MYAUCTIONS_SHOW_STARTING_PRICE)); $condition &= Validate::isInt(Tools::getValue(self::MYAUCTIONS_SHOW_COUNTDOWN)); $condition &= Validate::isString(Tools::getValue(self::EMAIL_COUNTER_FORMAT)); $condition &= Validate::isBool(Tools::getValue(self::EMAIL_SHOW_PRICE)); $condition &= Validate::isBool(Tools::getValue(self::EMAIL_SHOW_START_TIME)); $condition &= Validate::isBool(Tools::getValue(self::EMAIL_SHOW_CLOSE_TIME)); $condition &= Validate::isBool(Tools::getValue(self::EMAIL_SHOW_DURATION)); $condition &= Validate::isBool(Tools::getValue(self::EMAIL_SHOW_BIDS)); $condition &= Validate::isInt(Tools::getValue(self::EMAIL_SHOW_BIDS_LIST)); $condition &= Validate::isBool(Tools::getValue(self::EMAIL_SHOW_WINNER)); $condition &= Validate::isBool(Tools::getValue(self::EMAIL_SHOW_STARTING_PRICE)); $condition &= Validate::isInt(Tools::getValue(self::EMAIL_SHOW_COUNTDOWN)); return $condition; } public function getCustomerNameFormats() { $counter_formats = array(); foreach (self::$customer_name_formats_list as $index => $format) { $counter_formats[] = array( 'label' => $this->l($format), 'value' => $index ); } return $counter_formats; } } <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ class PowaTagTransaction extends ObjectModel { public $id_cart; public $id_order; public $id_customer; public $ip_address; public $id_device; public $order_state; public $date_add; public $date_upd; public static $definition = array( 'table' => 'powatag_transaction', 'primary' => 'id_powatag_transaction', 'multilang' => false, 'fields' => array( 'id_cart' => array('type' => self::TYPE_INT, 'validate' => 'isInt'), 'id_order' => array('type' => self::TYPE_INT, 'validate' => 'isInt'), 'id_customer' => array('type' => self::TYPE_INT, 'validate' => 'isInt'), 'ip_address' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), 'id_device' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), 'order_state' => array('type' => self::TYPE_INT, 'validate' => 'isInt'), 'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat'), 'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat'), ), ); public static function getTransactions($idCart = null, $idDevice = null, $ipAddress = null) { $sql = ' SELECT `'.self::$definition['primary'].'` FROM `'._DB_PREFIX_.self::$definition['table'].'` WHERE 1 '; if ($idCart && Validate::isInt($idCart)) { $sql .= ' AND `id_cart` = "'.$idCart.'" '; } if ($idDevice && Validate::isInt($idDevice)) { $sql .= ' AND `id_device` = "'.$idDevice.'" '; } if ($ipAddress && Validate::isInt($ipAddress)) { $sql .= ' AND `ip_address` = "'.$ipAddress.'" '; } $results = Db::getInstance()->ExecuteS($sql); return $results; } public static function install() { // Create Category Table in Database $sql = array(); $sql[] = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.self::$definition['table'].'` ( `'.self::$definition['primary'].'` INT(11) NOT NULL AUTO_INCREMENT, `id_cart` INT(11) unsigned NOT NULL, `id_order` INT(11) unsigned NOT NULL, `id_customer` INT(11) unsigned NOT NULL, `id_device` VARCHAR(255) NOT NULL, `ip_address` VARCHAR(255) NOT NULL, `order_state` INT(11) unsigned NOT NULL, date_add DATETIME NOT NULL, date_upd DATETIME NOT NULL, UNIQUE(`'.self::$definition['primary'].'`), PRIMARY KEY ('.self::$definition['primary'].') ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8;'; foreach ($sql as $q) { Db::getInstance()->Execute($q); } } public static function uninstall() { // Create Category Table in Database $sql = array(); $sql[] = 'DROP TABLE IF EXISTS `'._DB_PREFIX_.self::$definition['table'].'`'; foreach ($sql as $q) { Db::getInstance()->Execute($q); } } public function getCart() { return new Cart((int) $this->id_cart); } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsWatchModuleFrontController', false)) return; class AuctionsWatchModuleFrontController extends CoreModuleController { public $display_column_left = false; public $display_column_right = false; protected $action; protected $result; protected $id_customer; protected $id_products; public function process() { // Check page token if (!$this->isTokenValid()) die(Tools::displayError('Invalid token.')); parent::process(); $this->id_products = Tools::getValue('products', array()); $this->id_customer = (int)$this->context->customer->id; if (!$this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_WATCH_AUCTION)) return; if (empty($this->id_customer) || !is_array($this->id_products) || !$this->context->customer->isLogged()) return; $this->action = $this->getSubmittedAction(); $this->result = $this->handleActions($this->action, $this->id_customer, $this->id_products); } public function display() { if (Tools::getIsset('back')) Tools::redirect(html_entity_decode(urldecode(Tools::getValue('back')))); if (isset($_SERVER['HTTP_REFERER'])) Tools::redirect($_SERVER['HTTP_REFERER']); } public function displayAjax() { exit(Tools::jsonEncode(array( 'success' => $this->result, 'action' => $this->action, 'id_product_auction' => $this->id_products ))); } protected function handleActions($action, $id_customer, $auctions) { switch ($action) { case ProductAuctionSubscriptionDataManager::ADD: return ProductAuctionSubscriptionDataManager::addProductAuctionSubscription($id_customer, $auctions); case ProductAuctionSubscriptionDataManager::REMOVE: return ProductAuctionSubscriptionDataManager::removeProductAuctionSubscription($id_customer, $auctions); case ProductAuctionSubscriptionDataManager::CLEAR: return ProductAuctionSubscriptionDataManager::clearProductAuctionSubscription($id_customer, $auctions); } } protected function getSubmittedAction() { $actions = array( ProductAuctionSubscriptionDataManager::ADD, ProductAuctionSubscriptionDataManager::REMOVE, ProductAuctionSubscriptionDataManager::CLEAR ); foreach ($actions as $action) if (Tools::isSubmit($action)) return $action; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsMailingSettings', false)) return; class AuctionsMailingSettings extends CoreModuleSettings { const AUCTION_CUSTOMER_FINISHED = 'auct_mail_cust_fin'; const AUCTION_CUSTOMER_WON = 'auct_mail_cust_won'; const AUCTION_CUSTOMER_NOT_WON = 'auct_mail_cust_notwon'; const AUCTION_CUSTOMER_OFFER = 'auct_mail_cust_offer'; const AUCTION_CUSTOMER_LEAD = 'auct_mail_cust_lead'; const AUCTION_CUSTOMER_OUTBID = 'auct_mail_cust_outbid'; const AUCTION_CUSTOMER_RESTART = 'auct_mail_cust_restart'; const AUCTION_CUSTOMER_ACCEPT = 'auct_mail_cust_accept'; const AUCTION_CUSTOMER_REMIND = 'auct_mail_cust_remind'; const AUCTION_SUBSCRIBER_OFFER = 'auct_mail_sub_offer'; const AUCTION_SUBSCRIBER_FINISHED = 'auct_mail_sub_fin'; const AUCTION_SUBSCRIBER_RESTART = 'auct_mail_sub_restart'; const AUCTION_BACKOFFICE_OFFER = 'auct_mail_adm_offer'; const AUCTION_BACKOFFICE_FINISHED = 'auct_mail_adm_fin'; const AUCTION_BACKOFFICE_EMPLOYEES = 'auct_mail_adm_empl'; const AUCTION_MAIL_DELIMITER = ','; const AUCTION_MAIL_EOL = "\r\n"; const TYPE_DISABLED = 0; const TYPE_INSTANT = 1; const TYPE_CRON = 2; protected $submit_action = 'submitMailing'; public function getTitle() { return $this->l('Mailing'); } public function showForm($tab_index) { foreach ($this->getValue(self::AUCTION_BACKOFFICE_EMPLOYEES) as $employee_id) $this->values[self::AUCTION_BACKOFFICE_EMPLOYEES.'_'.$employee_id] = $employee_id; $fields_form = array( array( 'form' => array( 'legend' => array( 'title' => $this->l('Customer mailing'), 'image' => $this->getModule()->getPathUri().'img/icon/logo16px.png' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('A new offer is placed'), 'name' => self::AUCTION_CUSTOMER_OFFER, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_CUSTOMER_OFFER.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_CUSTOMER_OFFER.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_CUSTOMER_OFFER.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Email is sent to the bidders (except the winnig person and the person who was overbidden)') ), array( 'type' => 'radio', 'label' => $this->l('The highest offer is placed'), 'name' => self::AUCTION_CUSTOMER_LEAD, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_CUSTOMER_LEAD.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_CUSTOMER_LEAD.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_CUSTOMER_LEAD.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Email is sent only to the person who put the highest price (if disabled, new offer email is sent)') ), array( 'type' => 'radio', 'label' => $this->l('The offer was overbidden'), 'name' => self::AUCTION_CUSTOMER_OUTBID, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_CUSTOMER_OUTBID.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_CUSTOMER_OUTBID.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_CUSTOMER_OUTBID.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Email is sent only to the person who was overbidden (if disabled, new offer email is sent)') ), array( 'type' => 'radio', 'label' => $this->l('Auction finished'), 'name' => self::AUCTION_CUSTOMER_FINISHED, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_CUSTOMER_FINISHED.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_CUSTOMER_FINISHED.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_CUSTOMER_FINISHED.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Email is sent to the auction’s participants') ), array( 'type' => 'radio', 'label' => $this->l('Customer won auction'), 'name' => self::AUCTION_CUSTOMER_WON, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_CUSTOMER_WON.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_CUSTOMER_WON.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_CUSTOMER_WON.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Email is sent to the winner (if disabled, auction finished email is sent)') ), array( 'type' => 'radio', 'label' => $this->l('Customer did not win auction'), 'name' => self::AUCTION_CUSTOMER_NOT_WON, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_CUSTOMER_NOT_WON.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_CUSTOMER_NOT_WON.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_CUSTOMER_NOT_WON.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Email is sent to all auction participants except the winner (if disabled, auction finished email is sent)') ), array( 'type' => 'radio', 'label' => $this->l('Auction was restarted'), 'name' => self::AUCTION_CUSTOMER_RESTART, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_CUSTOMER_RESTART.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_CUSTOMER_RESTART.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_CUSTOMER_RESTART.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Participants receive notifications when the auction was restarted') ), array( 'type' => 'radio', 'label' => $this->l('Winner was accepted'), 'name' => self::AUCTION_CUSTOMER_ACCEPT, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_CUSTOMER_ACCEPT.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_CUSTOMER_ACCEPT.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_CUSTOMER_ACCEPT.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Email is sent to the person who despite reserve price had not been reached was accepted as a winner') ), array( 'type' => 'radio', 'label' => $this->l('Winner was reminded'), 'name' => self::AUCTION_CUSTOMER_REMIND, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_CUSTOMER_REMIND.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_CUSTOMER_REMIND.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_CUSTOMER_REMIND.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Email is sent to the person who despite winning the auction did not do a checkout') ) ) ) ), array( 'form' => array( 'legend' => array( 'title' => $this->l('Subscriber mailing'), 'image' => $this->getModule()->getPathUri().'img/icon/logo16px.png' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('A new offer is placed'), 'name' => self::AUCTION_SUBSCRIBER_OFFER, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_SUBSCRIBER_OFFER.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_SUBSCRIBER_OFFER.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_SUBSCRIBER_OFFER.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Subscribers receive notifications when a new offer is made') ), array( 'type' => 'radio', 'label' => $this->l('Auction finished'), 'name' => self::AUCTION_SUBSCRIBER_FINISHED, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_SUBSCRIBER_FINISHED.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_SUBSCRIBER_FINISHED.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_SUBSCRIBER_FINISHED.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Subscribers receive notifications when the auction finished') ), array( 'type' => 'radio', 'label' => $this->l('Auction was restarted'), 'name' => self::AUCTION_SUBSCRIBER_RESTART, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_SUBSCRIBER_RESTART.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_SUBSCRIBER_RESTART.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_SUBSCRIBER_RESTART.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Subscribers receive notifications when the auction was restarted') ) ) ) ), array( 'form' => array( 'legend' => array( 'title' => $this->l('Administrator mailing'), 'image' => $this->getModule()->getPathUri().'img/icon/logo16px.png' ), 'input' => array( array( 'type' => 'radio', 'label' => $this->l('A new offer is placed'), 'name' => self::AUCTION_BACKOFFICE_OFFER, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_BACKOFFICE_OFFER.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_BACKOFFICE_OFFER.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_BACKOFFICE_OFFER.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Administrators receive notifications when a new offer is made') ), array( 'type' => 'radio', 'label' => $this->l('Auction finished'), 'name' => self::AUCTION_BACKOFFICE_FINISHED, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::AUCTION_BACKOFFICE_FINISHED.'_'.self::TYPE_CRON, 'value' => self::TYPE_CRON, 'label' => $this->l('Cron Job') ), array( 'id' => self::AUCTION_BACKOFFICE_FINISHED.'_'.self::TYPE_INSTANT, 'value' => self::TYPE_INSTANT, 'label' => $this->l('Instant') ), array( 'id' => self::AUCTION_BACKOFFICE_FINISHED.'_'.self::TYPE_DISABLED, 'value' => self::TYPE_DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Administrators receive notifications when the auction finished') ), array( 'type' => 'checkbox', 'label' => $this->l('Send to these administrators'), 'name' => self::AUCTION_BACKOFFICE_EMPLOYEES, 'required' => false, 'values' => array( 'query' => $this->getEmployees(), 'id' => 'id', 'name' => 'name' ), 'desc' => $this->l('Send Administrator mailing to selected administrators') ) ) ) ) ); return $this->renderForm($fields_form, $tab_index); } public function init() { $this->setValue(self::AUCTION_CUSTOMER_FINISHED, (int)Configuration::get(self::AUCTION_CUSTOMER_FINISHED)); $this->setValue(self::AUCTION_CUSTOMER_WON, (int)Configuration::get(self::AUCTION_CUSTOMER_WON)); $this->setValue(self::AUCTION_CUSTOMER_NOT_WON, (int)Configuration::get(self::AUCTION_CUSTOMER_NOT_WON)); $this->setValue(self::AUCTION_CUSTOMER_OFFER, (int)Configuration::get(self::AUCTION_CUSTOMER_OFFER)); $this->setValue(self::AUCTION_CUSTOMER_LEAD, (int)Configuration::get(self::AUCTION_CUSTOMER_LEAD)); $this->setValue(self::AUCTION_CUSTOMER_OUTBID, (int)Configuration::get(self::AUCTION_CUSTOMER_OUTBID)); $this->setValue(self::AUCTION_CUSTOMER_RESTART, (int)Configuration::get(self::AUCTION_CUSTOMER_RESTART)); $this->setValue(self::AUCTION_CUSTOMER_ACCEPT, (int)Configuration::get(self::AUCTION_CUSTOMER_ACCEPT)); $this->setValue(self::AUCTION_CUSTOMER_REMIND, (int)Configuration::get(self::AUCTION_CUSTOMER_REMIND)); $this->setValue(self::AUCTION_SUBSCRIBER_OFFER, (int)Configuration::get(self::AUCTION_SUBSCRIBER_OFFER)); $this->setValue(self::AUCTION_SUBSCRIBER_FINISHED, (int)Configuration::get(self::AUCTION_SUBSCRIBER_FINISHED)); $this->setValue(self::AUCTION_SUBSCRIBER_RESTART, (int)Configuration::get(self::AUCTION_SUBSCRIBER_RESTART)); $this->setValue(self::AUCTION_BACKOFFICE_OFFER, (int)Configuration::get(self::AUCTION_BACKOFFICE_OFFER)); $this->setValue(self::AUCTION_BACKOFFICE_FINISHED, (int)Configuration::get(self::AUCTION_BACKOFFICE_FINISHED)); $this->setValue(self::AUCTION_BACKOFFICE_EMPLOYEES, explode(',', Configuration::get(self::AUCTION_BACKOFFICE_EMPLOYEES))); } public function install() { Configuration::updateValue(self::AUCTION_CUSTOMER_FINISHED, self::TYPE_CRON); Configuration::updateValue(self::AUCTION_CUSTOMER_WON, self::TYPE_CRON); Configuration::updateValue(self::AUCTION_CUSTOMER_NOT_WON, self::TYPE_CRON); Configuration::updateValue(self::AUCTION_CUSTOMER_OFFER, self::TYPE_INSTANT); Configuration::updateValue(self::AUCTION_CUSTOMER_LEAD, self::TYPE_INSTANT); Configuration::updateValue(self::AUCTION_CUSTOMER_OUTBID, self::TYPE_INSTANT); Configuration::updateValue(self::AUCTION_CUSTOMER_RESTART, self::TYPE_CRON); Configuration::updateValue(self::AUCTION_CUSTOMER_ACCEPT, self::TYPE_CRON); Configuration::updateValue(self::AUCTION_CUSTOMER_REMIND, self::TYPE_CRON); Configuration::updateValue(self::AUCTION_SUBSCRIBER_OFFER, self::TYPE_INSTANT); Configuration::updateValue(self::AUCTION_SUBSCRIBER_FINISHED, self::TYPE_CRON); Configuration::updateValue(self::AUCTION_SUBSCRIBER_RESTART, self::TYPE_CRON); Configuration::updateValue(self::AUCTION_BACKOFFICE_OFFER, self::TYPE_CRON); Configuration::updateValue(self::AUCTION_BACKOFFICE_FINISHED, self::TYPE_CRON); $employee = new Employee(); $employee->getByEmail(Configuration::get('PS_SHOP_EMAIL')); Configuration::updateValue(self::AUCTION_BACKOFFICE_EMPLOYEES, implode(',', array( $employee->id ))); return true; } public function uninstall() { Configuration::deleteByName(self::AUCTION_CUSTOMER_FINISHED); Configuration::deleteByName(self::AUCTION_CUSTOMER_WON); Configuration::deleteByName(self::AUCTION_CUSTOMER_NOT_WON); Configuration::deleteByName(self::AUCTION_CUSTOMER_OFFER); Configuration::deleteByName(self::AUCTION_CUSTOMER_LEAD); Configuration::deleteByName(self::AUCTION_CUSTOMER_OUTBID); Configuration::deleteByName(self::AUCTION_CUSTOMER_RESTART); Configuration::deleteByName(self::AUCTION_CUSTOMER_ACCEPT); Configuration::deleteByName(self::AUCTION_CUSTOMER_REMIND); Configuration::deleteByName(self::AUCTION_SUBSCRIBER_OFFER); Configuration::deleteByName(self::AUCTION_SUBSCRIBER_FINISHED); Configuration::deleteByName(self::AUCTION_SUBSCRIBER_RESTART); Configuration::deleteByName(self::AUCTION_BACKOFFICE_OFFER); Configuration::deleteByName(self::AUCTION_BACKOFFICE_FINISHED); Configuration::deleteByName(self::AUCTION_BACKOFFICE_EMPLOYEES); return true; } public function update() { Configuration::updateValue(self::AUCTION_CUSTOMER_FINISHED, (int)Tools::getValue(self::AUCTION_CUSTOMER_FINISHED)); Configuration::updateValue(self::AUCTION_CUSTOMER_WON, (int)Tools::getValue(self::AUCTION_CUSTOMER_WON)); Configuration::updateValue(self::AUCTION_CUSTOMER_NOT_WON, (int)Tools::getValue(self::AUCTION_CUSTOMER_NOT_WON)); Configuration::updateValue(self::AUCTION_CUSTOMER_OFFER, (int)Tools::getValue(self::AUCTION_CUSTOMER_OFFER)); Configuration::updateValue(self::AUCTION_CUSTOMER_LEAD, (int)Tools::getValue(self::AUCTION_CUSTOMER_LEAD)); Configuration::updateValue(self::AUCTION_CUSTOMER_OUTBID, (int)Tools::getValue(self::AUCTION_CUSTOMER_OUTBID)); Configuration::updateValue(self::AUCTION_CUSTOMER_RESTART, (int)Tools::getValue(self::AUCTION_CUSTOMER_RESTART)); Configuration::updateValue(self::AUCTION_CUSTOMER_ACCEPT, (int)Tools::getValue(self::AUCTION_CUSTOMER_ACCEPT)); Configuration::updateValue(self::AUCTION_CUSTOMER_REMIND, (int)Tools::getValue(self::AUCTION_CUSTOMER_REMIND)); Configuration::updateValue(self::AUCTION_SUBSCRIBER_OFFER, (int)Tools::getValue(self::AUCTION_SUBSCRIBER_OFFER)); Configuration::updateValue(self::AUCTION_SUBSCRIBER_FINISHED, (int)Tools::getValue(self::AUCTION_SUBSCRIBER_FINISHED)); Configuration::updateValue(self::AUCTION_SUBSCRIBER_RESTART, (int)Tools::getValue(self::AUCTION_SUBSCRIBER_RESTART)); Configuration::updateValue(self::AUCTION_BACKOFFICE_OFFER, (int)Tools::getValue(self::AUCTION_BACKOFFICE_OFFER)); Configuration::updateValue(self::AUCTION_BACKOFFICE_FINISHED, (int)Tools::getValue(self::AUCTION_BACKOFFICE_FINISHED)); $employees = array(); $employees_collection = EmployeeCore::getEmployees(); foreach ($employees_collection as $employee) if (Tools::isSubmit(self::AUCTION_BACKOFFICE_EMPLOYEES.'_'.$employee['id_employee'])) $employees[] = $employee['id_employee']; Configuration::updateValue(self::AUCTION_BACKOFFICE_EMPLOYEES, implode(',', $employees)); return true; } protected function validate() { $condition = true; $condition &= Validate::isInt(Tools::getValue(self::AUCTION_CUSTOMER_FINISHED)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_CUSTOMER_WON)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_CUSTOMER_NOT_WON)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_CUSTOMER_OFFER)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_CUSTOMER_LEAD)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_CUSTOMER_OUTBID)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_CUSTOMER_RESTART)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_CUSTOMER_ACCEPT)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_CUSTOMER_REMIND)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_SUBSCRIBER_OFFER)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_SUBSCRIBER_FINISHED)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_SUBSCRIBER_RESTART)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_BACKOFFICE_OFFER)); $condition &= Validate::isInt(Tools::getValue(self::AUCTION_BACKOFFICE_FINISHED)); return $condition; } protected function getEmployees() { $employees = array(); $employees_collection = new Collection('Employee'); $employees_collection->where('active', '=', 1); foreach ($employees_collection->getResults() as $employee) { $employees[] = array( 'id' => $employee->id, 'val' => $employee->id, 'name' => $employee->firstname.' '.$employee->lastname.' ('.$employee->email.')' ); } return $employees; } } <file_sep>/** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ $(document).ready(function() { var checkItems = function(checkbox_item) { var item_name = $('form.checkbox_form').attr('rel'); var item_id = $(checkbox_item).val(); if ($(checkbox_item).is(':checked') && $('#item_'+item_id).length < 1) { $('form.checkbox_form').append($('<input type="hidden" id="item_'+item_id+'" name="'+item_name+'[]" value="'+item_id+'"/>')); } if ($(checkbox_item).is(':not(:checked)') && $('#item_'+item_id).length > 0) { $('#item_'+item_id).remove(); } } $('.checkbox_check_all').click(function(){ if ($(this).is(':checked')) { $('.my_auctions_list .checker span').addClass('checked'); $('.my_auctions_list :checkbox:not(.checkbox_check_all)') .prop("checked", true) .each(function(){ checkItems(this); }); } else if ($(this).is(':not(:checked)')) { $('.my_auctions_list .checker span').removeClass('checked'); $('.my_auctions_list :checkbox:not(.checkbox_check_all)') .prop("checked", false) .each(function(){ checkItems(this); }); } }); $('.my_auctions_list :checkbox:not(.checkbox_check_all)').each(function(){ $(this).change(function(){ checkItems(this); }); }); }); <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('ProductAuctionType', false)) return; class ProductAuctionType implements ProductAuctionsObjectTemplatesInterface { const ENGLISH = 1; const DUTCH = 2; const FIRST_PRICE_SEALED = 3; const VICKREY = 4; const REVERSE = 5; const PENNY = 6; /** * * @var AuctionsTypeBase */ private $instance; /** * * @param integer $type * @param Module $module * @throws PrestaShopModuleException */ public function __construct($type) { switch ((int)$type) { case self::ENGLISH: $this->instance = new ProductAuctionTypeEnglish(); break; case self::DUTCH: case self::FIRST_PRICE_SEALED: case self::VICKREY: case self::REVERSE: case self::PENNY: default: throw new PrestaShopModuleException('Unsupported auction type!'); } } /** * * @return AbstractProductAuctionItem */ public function getProductAuctionItem() { return $this->instance->getProductAuctionItem(); } /** * * @return AbstractProductAuctionCreate */ public function getProductAuctionCreate() { return $this->instance->getProductAuctionCreate(); } /** * * @return AbstractProductAuctionItem */ public function getProductAuctionOfferItem() { return $this->instance->getProductAuctionOfferItem(); } /** * * @return AbstractProductAuctionValidator */ public function getProductAuctionValidator() { return $this->instance->getProductAuctionValidator(); } /** * * @param Auctions $module * @return AbstractProductAuctionBid */ public function getProductAuctionBid(Auctions $module) { return $this->instance->getProductAuctionBid($module); } /** * * @param Auctions $module * @return AbstractProductAuctionMailing */ public function getProductAuctionMailingManager(Auctions $module) { return $this->instance->getProductAuctionMailingManager($module); } /** * * @param Module $module * @param string $sType */ public function getProductAuctionPermissions(AuctionsAppearanceSettings $appearance_settings) { return $this->instance->getProductAuctionPermissions($appearance_settings); } /** * * @param AbstractProductAuctionBidResult $product_auction_bid_result */ public function bid(AbstractProductAuctionBidResult $product_auction_bid_result) { return $this->instance->bid($product_auction_bid_result); } /** * * @param AbstractProductAuctionItem $product_auction_item */ public function process(AbstractProductAuctionItem $product_auction_item) { return $this->instance->process($product_auction_item); } /** * * @param ProductAuction $oProductAuction */ public function restart(ProductAuction $product_auction) { return $this->instance->restart($product_auction); } /** * * @param ProductAuction $product_auction */ public function finish(ProductAuction $product_auction) { return $this->instance->finish($product_auction); } /** * * @param ProductAuction $product_auction */ public function acceptWinner(ProductAuction $product_auction) { return $this->instance->acceptWinner($product_auction); } /** * * @param ProductAuction $product_auction */ public function remindWinner(ProductAuction $product_auction) { return $this->instance->remindWinner($product_auction); } /** * * @param ProductAuctionOffer $product_auction_offer */ public function markWinner(ProductAuctionOffer $product_auction_offer) { return $this->instance->markWinner($product_auction_offer); } /** * * @param ProductAuctionOffer $product_auction_offer */ public function rejectWinner(ProductAuctionOffer $product_auction_offer) { return $this->instance->rejectWinner($product_auction_offer); } /** * * @param CoreModuleEventListenerInterface $event_listener */ public function notify(CoreModuleEventListenerInterface $event_listener) { return $this->instance->notify($event_listener); } /** * * @return CoreModuleEventDispatcher */ public function dispatcher() { return $this->instance->dispatcher(); } } <file_sep>/** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author Magic Toolbox <<EMAIL>> * @copyright Copyright (c) 2015 Magic Toolbox <<EMAIL>>. All rights reserved * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ var templateOptions = []; var magicscrollOptions = []; //initOptionsValidation('template', 'magicscroll'); function initOptionsValidation(templateOptionName, magicscrollOptionName, templateOptionValuesPrefix, magicscrollOptionValuesPrefix) { if(templateOptionValuesPrefix === undefined) { templateOptionValuesPrefix = ''; } if(magicscrollOptionValuesPrefix === undefined) { magicscrollOptionValuesPrefix = ''; } if(!templateOptions.length) templateOptions = document.getElementsByName(templateOptionName); if(!magicscrollOptions.length) magicscrollOptions = document.getElementsByName(magicscrollOptionName); if(templateOptions.length && magicscrollOptions.length) { bindOptions(magicscrollOptions, magicscrollOptionValuesPrefix+'Yes', templateOptions, templateOptionValuesPrefix+'original', templateOptionValuesPrefix+'bottom'); bindOptions(templateOptions, templateOptionValuesPrefix+'original', magicscrollOptions, magicscrollOptionValuesPrefix+'Yes', magicscrollOptionValuesPrefix+'No'); } } function bindOptions(optionsToBind, onValue, optionsToSet, checkValue, setValue) { if(optionsToBind[0].type == 'radio') { for(var i = 0, l = optionsToBind.length; i < l; i++) { optionsToBind[i].onclick = function() { if(this.checked && this.value == onValue) { setOptionValue(optionsToSet, checkValue, setValue); } } } } else if(optionsToBind[0].type == 'select-one') { optionsToBind[0].onchange = function() { if(this.value == onValue) { setOptionValue(optionsToSet, checkValue, setValue); } } } } function setOptionValue(options, checkValue, setValue) { if(options[0].type == 'select-one') { if(options[0].value == checkValue) { for(var i = 0, l = options[0].options.length; i < l; i++) { if(options[0].options[i].value == setValue) { options[0].value = options[0].options[i].value; options[0].selectedIndex = i; return; } } } } else if(options[0].type == 'radio') { var setOption = false; for(var i = 0, l = options.length; i < l; i++) { if(options[i].checked && options[i].value == checkValue) { options[i].checked = false; setOption = true; } else /*checkValue value must be first in node list*/if(setOption && options[i].value == setValue) { options[i].checked = true; return; } } } } <file_sep><?php class adminyourbarcode_gpController extends ModuleAdminController { public function __construct() { parent :: __construct(); $this->content =$this->display_barcodeManager(); } public function display_barcodeManager() { $this->_html = ''; $version=substr(str_replace('.','',_PS_VERSION_),0,3); if ($version>=150){ //recuperation du code de la boutique $context = Context::getContext(); $id_shop = (int)$context->shop->id; //Recuperation du context boutique, groupe de boutique ou toutes les boutiques if(Shop::getContext()<>1 && Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE')==1){ $this->_html=$this->_html.$this->l('You must choose one shop to use this module. You cannot choose a group or all shop'); return $this->_html; } } else { $id_shop=1; } if (Configuration::get('PS_SSL_ENABLED')==0) { $this->_html=$this->_html. '<SCRIPT> var http_header=\'http://\';</SCRIPT>'; $http_header='http://'; } else { $this->_html=$this->_html. '<SCRIPT> var http_header=\'https://\';</SCRIPT>'; $http_header='https://'; } if($version<150){ $domain=$domain; $this->_html=$this->_html. '<SCRIPT> var domain=\''.$domain.'\';</SCRIPT>'; $racine=$racine; $this->_html=$this->_html. '<SCRIPT> var racine=\''.$racine.'\';</SCRIPT>'; } else { //recuperation du code de la boutique $context = Context::getContext(); $id_shop = (int)$context->shop->id; $sql_url='select * from '._DB_PREFIX_.'shop_url where id_shop='.$id_shop; $result_url = Db::getInstance()->ExecuteS($sql_url); foreach($result_url as $row_url) { $domain=$row_url['domain']; $this->_html=$this->_html. '<SCRIPT> var domain=\''.$domain.'\';</SCRIPT>'; $racine=$row_url['physical_uri']; //ex: / si racine ou alors si repertoire ex: /mon_repertoire/ $this->_html=$this->_html. '<SCRIPT> var racine=\''.$racine.'\';</SCRIPT>'; } } $this->_html=$this->_html. '<SCRIPT>var shop=\''.$id_shop.'\';</SCRIPT>'; $this->_html=$this->_html. '<link href="'._MODULE_DIR_.'yourbarcode_gp/css/style.css" rel="stylesheet" type="text/css" media="all" />'; $this->_html=$this->_html. '<script type="text/javascript" src="'._MODULE_DIR_.'yourbarcode_gp/js/tablefilter_all.js"></script>'; $this->_html=$this->_html. '<script type="text/javascript" src="'._MODULE_DIR_.'yourbarcode_gp/js/adminbarcode.js"></script>'; //////////////////////////////////////////////////////////////////////////////////// //creation table temporaire pour concatener les combinaisons des differents attribut //////////////////////////////////////////////////////////////////////////////////// $sql='show tables where Tables_in_'._DB_NAME_.' like \''._DB_PREFIX_.'yourstock_gp_concat_attr%\''; $resultat=Db::getInstance()->ExecuteS($sql); foreach ($resultat as $row){ $sql='drop table '.$row['Tables_in_'._DB_NAME_]; Db::getInstance()->Execute($sql); } $table_tmp=_DB_PREFIX_.'yourstock_gp_concat_attr'.time(); Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS '.$table_tmp.' ( `id_product_attribute` int(11) NOT NULL, `name` varchar(256), PRIMARY KEY (`id_product_attribute`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;'); //affichage commun a tout les onglets $this->_html=$this->_html. '<fieldset> <legend> '.$this->l('Manage your barcode').' </legend>'; $this->_html=$this->_html. '<form name="formulaire" ID="formulaire" onsubmit="return valider()" method="post" action="">'; $this->_html=$this->_html. '<input type="hidden" value="'._PS_ROOT_DIR_.'" name="ps_root_dir" id="ps_root_dir"/>'; $this->_html=$this->_html. '<input type="hidden" value="0" name="enter_detect" id="enter_detect"/>'; $this->_html=$this->_html. '<input type="hidden" value="0" name="value_before" id="value_before"/>'; $this->_html=$this->_html. '<input type="hidden" value="'.(int)Context::getContext()->language->id.'" name="LANG" id="LANG"/>'; global $cookie; $this->_html=$this->_html. '<input type="hidden" value="'.$cookie->id_employee.'" name="COOKIE_EMP" id="COOKIE_EMP"/>'; $this->_html=$this->_html. '<input type="hidden" value="'.$this->l('Ok').'|'.$this->l('Not ok').'|'.$this->l('Not valide number').'|'.$this->l('Are you sure?').'" name="traductions" id="traductions"/>'; $this->_html=$this->_html. '<input type="hidden" value="0" name="state_validation" id="state_validation"/>'; $sql='select distinct id_product_attribute from '._DB_PREFIX_.'product_attribute_combination where id_product_attribute in (select '._DB_PREFIX_.'product_attribute.id_product_attribute from '._DB_PREFIX_.'product_attribute)'; $result = Db::getInstance()->ExecuteS($sql); foreach($result as $row){ $sql='select '._DB_PREFIX_.'product_attribute_combination.id_product_attribute, '._DB_PREFIX_.'attribute_lang.name from '._DB_PREFIX_.'product_attribute_combination, '._DB_PREFIX_.'attribute_lang where '._DB_PREFIX_.'attribute_lang.id_attribute='._DB_PREFIX_.'product_attribute_combination.id_attribute and '._DB_PREFIX_.'product_attribute_combination.id_product_attribute='.$row['id_product_attribute'].' -- and '._DB_PREFIX_.'attribute_lang.name<>NULL and '._DB_PREFIX_.'attribute_lang.id_lang='.(int)Context::getContext()->language->id; $result1 = Db::getInstance()->ExecuteS($sql); $concat_attr=''; foreach ($result1 as $row1) { $concat_attr=$concat_attr.addslashes($row1['name']).'\n'; } $query='INSERT INTO '.$table_tmp.' (`id_product_attribute`, `name`) VALUES (\''.$row['id_product_attribute'].'\',\''.$concat_attr.'\')'; Db::getInstance()->Execute($query); } //recuperation des stocks pour tous les produits $sql='select '._DB_PREFIX_.'product.id_product, '._DB_PREFIX_.'product.active, if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),0,'._DB_PREFIX_.'product_attribute.id_product_attribute) as id_product_attribute, if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),'._DB_PREFIX_.'product.quantity,'._DB_PREFIX_.'product_attribute.quantity) as quantity, CONCAT(CONCAT('._DB_PREFIX_.'product_lang.name,\':<BR>\'),'._DB_PREFIX_.'product_lang.description_short) as description_short, '.$table_tmp.'.name as combination, if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),'._DB_PREFIX_.'product.ean13,'._DB_PREFIX_.'product_attribute.ean13) as barcode from '._DB_PREFIX_.'product JOIN '._DB_PREFIX_.'product_lang ON ('._DB_PREFIX_.'product_lang.id_product='._DB_PREFIX_.'product.id_product and '._DB_PREFIX_.'product_lang.id_shop='.$id_shop.') JOIN '._DB_PREFIX_.'product_shop ON ('._DB_PREFIX_.'product.id_product='._DB_PREFIX_.'product_shop.id_product) LEFT OUTER JOIN '._DB_PREFIX_.'product_attribute ON ('._DB_PREFIX_.'product_attribute.id_product='._DB_PREFIX_.'product.id_product) LEFT OUTER JOIN '.$table_tmp.' ON ('.$table_tmp.'.id_product_attribute='._DB_PREFIX_.'product_attribute.id_product_attribute) where ('._DB_PREFIX_.'product_lang.id_lang='.(int)Context::getContext()->language->id.' and '._DB_PREFIX_.'product_lang.id_shop='.$id_shop.') and '._DB_PREFIX_.'product.active=1 and '._DB_PREFIX_.'product_shop.id_shop='.$id_shop.' order by '._DB_PREFIX_.'product.id_product, if(isnull('._DB_PREFIX_.'product_attribute.id_product_attribute),0,'._DB_PREFIX_.'product_attribute.id_product_attribute)'; //LIMIT 1000'; $result_tab_final = Db::getInstance()->ExecuteS($sql); //generation des constantes $ch_jv=str_replace('\\','/',_PS_MODULE_DIR_); //affichage de table $this->_html=$this->_html. '<TABLE border="1" id="table1" name="table1" cellpadding="1" cellspacing="0" width="100%">'; $this->_html=$this->_html. '<TR> <TH scope=\'col\'><strong >'.$this->l('Items PDF').'</strong></TH> <TH scope=\'col\'><strong >'.$this->l('barcode').'</strong></TH> <TH scope=\'col\'><strong >'.$this->l('Items').'</strong></TH> <TH scope=\'col\'><strong >'.$this->l('Items description').'</strong></TH> <TH scope=\'col\'><strong >'.$this->l('Combination').'</strong></TH> </TR>'; $i=0; foreach ($result_tab_final as $row) { $line=''; $erreur_barcode=$this->test_ean13($row['barcode']); if ($erreur_barcode>0){ $state=$this->l('Error'); $class_lg='lg_pb_stk'; $stkstate=$this->l('Not ok'); } else { $class_lg='lg_normal'; $stkstate=$this->l('Ok'); $state=$this->l('Ok'); } $line=$line.'<TR class="'.$class_lg.'" ID="'.$row['id_product'].'-'.$row['id_product_attribute'].'"> <TD id="td_'.$row['id_product'].'-'.$row['id_product_attribute'].'"> <A target="_blank" href="'._MODULE_DIR_.'yourbarcode_gp/pdf.php?cd_ean13='.$row['barcode'].'&PS_ROOT_DIR='.addslashes(_PS_ROOT_DIR_).'&url='.$http_header.$domain._MODULE_DIR_.'yourbarcode_gp/ean13.php">'.$row['barcode'].'</A> <A target="_blank" href="'._MODULE_DIR_.'yourbarcode_gp/items_pdf.php?cd_ean13='.$row['barcode'].'&lang='.(int)Context::getContext()->language->id.'&PS_ROOT_DIR='.addslashes(_PS_ROOT_DIR_).'&url='.$http_header.$domain.$racine.'">'.$row['barcode'].'</A> </TD>'; $line=$line.' <TD><INPUT TYPE="TEXT" name="in'.$row['id_product'].'x'.$row['id_product_attribute'].'" id="'.$row['id_product'].'|'.$row['id_product_attribute'].'" value="'.$row['barcode'].'" onKeypress="return number(event,\''.$ch_jv.'yourbarcode_gp/\',\''.$domain.'\',\''.$racine.'\',\''.$row['id_product'].'\',\''.$row['id_product_attribute'].'\',\''.$row['id_product'].'|'.$row['id_product_attribute'].'\');" onchange="ajx_mvt(\''.$row['id_product'].'|'.$row['id_product_attribute'].'\');"/></TD>'; $line=$line.' <TD>'.$row['id_product'].'</TD> <TD>'.$row['description_short'].'</TD> <TD>'.$row['combination'].'</TD> <TD id="td_state'.$row['id_product'].'-'.$row['id_product_attribute'].'">'.$state.'</TD>'; $line=$line. '</TR>'; $this->_html=$this->_html.$line; } $this->_html=$this->_html. '<INPUT TYPE="HIDDEN" ID="error_msg" NAME="error_msg" VALUE="'.$this->l('lenght error').'|'.$this->l('Bit control error').'|'.$this->l('Duplicate barcode').'">'; $this->_html=$this->_html. '<INPUT TYPE="HIDDEN" ID="state_msg" NAME="state_msg" VALUE="'.$this->l('Ok').'|'.$this->l('Error').'">'; $this->_html=$this->_html. '<INPUT TYPE="HIDDEN" ID="value_selected_field" NAME="value_selected_field" VALUE="">'; $this->_html=$this->_html. '</TABLE>'; $this->_html=$this->_html. '</FORM>'; $this->_html=$this->_html. '</fieldset>'; $this->_html=$this->_html. '<script language="javascript" type="text/javascript"> var tfConfig = { on_keyup: true } var table1Filters = { on_keyup :true, col_1: "none", btn: true, btn_text: "'.$this->l('filter').'" } setFilterGrid("table1",table1Filters); </script>'; return $this->_html; } function test_ean13($ean13){ if(strlen($ean13)<>13) { return 1; //return 'pb_longueur'; } $bit_ctrl=$this->calc_bit_ctrl(substr($ean13,0,-1)); //function de test a reprendre ici test si le bit de controle est ok if($ean13<>substr($ean13,0,-1).$bit_ctrl){ return 2; //return 'pb_bit_control'; } //si ok return 0 return 0; } function calc_bit_ctrl($code_ean) { $ctrl_key=0; $len_ch= strlen($code_ean); $i=0; while($i<$len_ch) { $etape = $len_ch - $i; $tab[$i] = substr($code_ean, -$etape,1); $i++; } foreach ($tab as $key => $value){ if (($key+1)%2==0){ $ctrl_key=$ctrl_key+$value*3; } else { $ctrl_key=$ctrl_key+$value; } } $ctrl_key=$ctrl_key%10; if ($ctrl_key==0) { return $ctrl_key; } else { return 10-$ctrl_key; } } } ?><file_sep><?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_34c869c542dee932ef8cd96d2f91cae6'] = 'Nuestras tiendas'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_a82be0f551b8708bc08eb33cd9ded0cf'] = 'Información'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_d1aa22a3126f04664e0fe3f598994014'] = 'Especiales'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_9ff0635f5737513b1a6f559ac2bff745'] = 'Nuevos productos'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_3cb29f0ccc5fd220a97df89dafe46290'] = 'Top ventas'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_02d4482d332e1aef3437cd61c9bcc624'] = 'Contáctenos'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_e1da49db34b0bdfdddaba2ad6552f848'] = 'Mapa del sitio'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_5813ce0ec7196c492c97596718f71969'] = 'Mapa del sitio'; $_MODULE['<{blockcms}touchmenot1.0.3>blockcms_7a52e36bf4a1caa031c75a742fb9927a'] = 'Desarrollado por'; <file_sep>// declare main object of module var FpcModule = function(sName) { // set name this.name = sName; // set name this.oldVersion = false; // set translated js msgs this.msgs = {}; // stock error array this.aError = []; // set url of admin img this.sImgUrl = ''; // set url of module's web service this.sWebService = ''; // set response this.response = null; // set this in obj context var oThis = this; /* * show() method show effect and assign HTML in * User: Business Tech (www.businesstech.fr) - Contact: http://www.businesstech.fr/en/contact-us * @param string sId : container to show in * @param string sHtml : HTML to display * @return - */ this.show = function(sId, sHtml) { $("#" + sId).html(sHtml).css('style', 'none'); $("#" + sId).show('fast'); }; /* * hide() method hide effect and delete html * User: Business Tech (www.businesstech.fr) - Contact: http://www.businesstech.fr/en/contact-us * @param string sId : container to hide in * @return - */ this.hide = function(sId) { $("#" + sId).hide('fast', function() { $("#" + sId).html(''); } ); }; /* * form() method check all fields of current form and execute : XHR or submit => used for update all admin config * User: Business Tech (www.businesstech.fr) - Contact: http://www.businesstech.fr/en/contact-us * @see ajax * @param string sForm : form * @param string sURI : query params used for XHR * @param string sRequestParam : param action and type in order to send with post mode * @param string sToDisplay : * @param string sToHide : force to hide specific ID * @param bool bSubmit : used only for sending main form * @param bool bFancyBox : used only for fancybox in xhr * @param string sCallback : * @param string sErrorType : * @param string sLoadBar : * @return string : HTML returned by smarty */ this.form = function(sForm, sURI, sRequestParam, sToDisplay, sToHide, bSubmit, bFancyBox, sCallback, sErrorType, sLoadBar) { // set loading bar if (sLoadBar) { $('#'+sLoadBar).show(); } // set return validation var aError = []; // get all fields of form var fields = $("#" + sForm).serializeArray(); // set counter var iCounter = 0; // set bIsError var bIsError = false; // check element form jQuery.each(fields, function(i, field) { bIsError = false; switch(field.name) { case 'id' : if (field.value == '') { oThis.aError[iCounter] = oThis.msgs.id; bIsError = true; } break; case 'secret' : if (field.value == '') { oThis.aError[iCounter] = oThis.msgs.secret; bIsError = true; } break; case 'callback' : if (field.value == '') { oThis.aError[iCounter] = oThis.msgs.callback; bIsError = true; } break; case 'scope' : if (field.value == '') { oThis.aError[iCounter] = oThis.msgs.scope; bIsError = true; } break; case 'developerKey' : if (field.value == '') { oThis.aError[iCounter] = oThis.msgs.developerKey; bIsError = true; } break; case 'socialEmail' : if (field.value == '') { oThis.aError[iCounter] = oThis.msgs.socialEmail; bIsError = true; } break; default: break; } if ($('#' + field.name) != undefined && bIsError == true) { if ($('input[name="' + field.name + '"]').length != 0) { $('input[name="' + field.name + '"]').css('border', '1px solid red'); } if ($('textarea[name="' + field.name + '"]').length != 0) { $('textarea[name="' + field.name + '"]').css('border', '1px solid red'); } ++iCounter; } }); // use case - no errors in form if (oThis.aError.length == 0) { // use case - Ajax request if (bSubmit == undefined || bSubmit == null || !bSubmit) { // format object of fields in string to execute Ajax request var sFormParams = $.param(fields); if (sCallback != null) { } if (sRequestParam != null && sRequestParam != '') { sFormParams = sRequestParam + '&' + sFormParams; } // execute Ajax request this.ajax(sURI, sFormParams, sToDisplay, sToHide, bFancyBox, null, sLoadBar); return true; } // use case - send form else { // hide loading bar if (sLoadBar) { $('#'+sLoadBar).hide(); } document.forms[sForm].submit(); return true; } } // display errors this.displayError(sErrorType); return false; }; /* * ajax() method execute XHR * User: Business Tech (www.businesstech.fr) - Contact: http://www.businesstech.fr/en/contact-us * @param string sURI : query params used for XHR * @param string sParams : * @param string sToShow : * @param string sToHide : * @param bool bFancyBox : used only for fancybox in xhr * @param bool bFancyBoxActivity : used only for fancybox in xhr * @param string sLoadBar : used only for loading * @return string : HTML returned by smarty */ this.ajax = function(sURI, sParams, sToShow, sToHide, bFancyBox, bFancyBoxActivity, sLoadBar) { if(bFancyBox && bFancyBoxActivity != false) { $.fancybox.showActivity(); } sParams = 'sMode=xhr' + ((sParams == null || sParams == undefined) ? '' : '&' + sParams) ; // configure XHR $.ajax({ type : 'POST', url : sURI, data : sParams, dataType : 'html', success: function(data) { // hide loading bar if (sLoadBar) { $('#'+sLoadBar).hide(); } if(bFancyBox) { // update fancybox content $.fancybox(data); // use case - update only widget list if (sToShow == oThis.name + 'ConnectorList') { oThis.ajax('' + sURI, 'sAction=display&sType=connectors', '' + sToShow + '', '' + sToHide + ''); } // use case - update widget list and hook list else if (sToShow == oThis.name + 'HookList') { sToShow = sToHide = oThis.name + 'ConnectorList'; oThis.ajax('' + sURI + 'connectors', 'sAction=display&sType=connectors', '' + sToShow + '', '' + sToHide + ''); sToShow = sToHide = oThis.name + 'HookList'; oThis.ajax('' + sURI + 'hooks', 'sAction=display&sType=hooks', '' + sToShow + '', '' + sToHide + ''); } } else if (sToShow != null && sToHide != null) { // same hide and show if (sToShow == sToHide) { oThis.hide('fast'); $('#' + sToHide).hide('fast'); $('#' + sToHide).empty(); setTimeout('', 1000); oThis.show(sToShow, data); } else { oThis.hide(sToHide); setTimeout('', 1000); oThis.show(sToShow, data); } } else if (sToShow != null) { oThis.show(sToShow, data); } else if (sToHide != null) { oThis.hide(sToHide); } else { oThis.response = data; } }, error: function(xhr, ajaxOptions, thrownError) { $("#" + oThis.name + "FormError").addClass('alert error'); oThis.show("#" + oThis.name + "FormError", '<h3>internal error</h3>'); } }); }; /* * displayError() method display errors * User: Business Tech (www.businesstech.fr) - Contact: http://www.businesstech.fr/en/contact-us * @param string sType : type of container * @return bool */ this.displayError = function(sType) { if (oThis.aError.length != 0) { var sError = '<img class="pointer" src="' + oThis.sImgUrl + 'hook/cancel.png' + '" onclick="$(\'#' + oThis.name + sType + 'Error\').hide(\'' + oThis.name + sType + 'Error\');" />'; for (var i = 0; i < oThis.aError.length;++i) { sError += '<span>' + oThis.aError[i] + '</span><br />'; } $("#" + oThis.name + sType + "Error").html(sError).addClass('form-error'); $("#" + oThis.name + sType + "Error").show(); // flush errors oThis.aError = []; return false; } }; /* * changeSelect() method displays or hide related option form * User: Business Tech (www.businesstech.fr) - Contact: http://www.businesstech.fr/en/contact-us * @param string sId : type of container * @param string sDestId * @param string sDestId2 * @param string sType of second dest id * @return */ this.changeSelect = function(sId, sDestId, sDestId2, sDestIdToHide) { $("#" + sId).bind($.browser.msie ? 'click' : 'change', function (event) { $("#" + sId + " input:checked").each(function () { switch ($(this).val()) { case 'true' : // display option features $("#" + sDestId).fadeIn('fast', function() {$("#" + sDestId).css('display', 'block')}); break; default: // hide option features $("#" + sDestId).fadeOut('fast'); // set to false if (sDestId2 && sDestIdToHide) { $("#" + sDestId2 + " input").each(function () { switch ($(this).val()) { case 'false' : $(this).attr('checked', 'checked'); // hide option features $("#" + sDestIdToHide).fadeOut('fast'); break; default: $(this).attr('checked', ''); break; } } ); } break; } }); }); }; /* * selectAll() method select / deselect all checkbox * User: Business Tech (www.businesstech.fr) - Contact: http://www.businesstech.fr/en/contact-us * @param string sId : type of container * @param string sCible : all checkbox to process * @return */ this.selectAll = function(sId, sCible){ $("#" + sId).bind($.browser.msie ? 'click' : 'change', function (event){ if (this.checked == true) { $(sCible).attr('checked', true); } else{ $(sCible).attr('checked', false); } }); }; /* * updateHook() method verify all childnodes of hook list and determine position to display widget in hook * User: Business Tech (www.businesstech.fr) * @param string sURI : query params used for XHR * @param string sHookList : * @param string sToShow : * @param string sToHide : * @param bool bFancyBox : used only for fancybox in xhr * @return string : HTML returned by smarty */ this.updateHook = function(sURI, sHookList, sToShow, sToHide, bFancyBox) { var sList = ''; if ($("#" + sHookList + " li").length != 0) { var aConnectorId = []; $("#" + sHookList + " li").each(function(i, elt) { aConnectorId[i] = elt.id; } ); sList = aConnectorId.toString(); } this.ajax(sURI, 'sConnectorList=' + sList, sToShow, sToHide, bFancyBox); }; /* * draggableConnector() method set draggable * User: Business Tech (www.businesstech.fr) * @param obj Current HTML elt * @return - */ this.draggableConnector = function() { // declare draggable elts $("#" + oThis.name + "DraggableConnector li").draggable({ revert : "invalid" }); // declare droppable elt - only drop elt in this tag $("#" + oThis.name + "DroppableConnector ul").droppable({ drop : function(event, ui) { // append draggable elt $("#" + oThis.name + "DroppableConnector ul").append(ui.draggable); // set css and desactivate drag $(ui.draggable).css({position:"relative", top:"0px", left:"0px", display : "block"}) .draggable("disable") .css({opacity : 1}) .addClass('fbpscsortli'); // append img and click evt only in no already added img var bFound = $(ui.draggable).find('img.' + oThis.name + 'Garbage'); // use case - add img and click evt in no img case if (bFound.length == 0) { $(ui.draggable).append('<img class="' + oThis.name + 'Garbage" src="' + oThis.sAdminImgUrl + 'delete.gif" />').bind('click', function() { oThis.deleteConnector(this); } ); } } }); }; /* * sortableConnector() method set sortable Connector * User: Business Tech (www.businesstech.fr) * @param obj Current HTML elt * @return - */ this.sortableConnector = function() { // set sortable elt $( "#" + oThis.name + "Sortable" ).sortable(); $( "#" + oThis.name + "Sortable" ).disableSelection(); }; /* * deleteConnector() method delete added Connector in hook form * User: Business Tech (www.businesstech.fr) * @param obj Current HTML elt * @return - */ this.deleteConnector = function(oElt) { $(oElt).find('img.' + oThis.name + 'Garbage').remove(); $("#" + oThis.name + "DraggableConnector ul").append($(oElt).removeClass('fbpscsortli').draggable('enable').draggable('option', 'revert' , 'invalid').addClass('fbpscdragli')); }; /* * collect() method save the customer action and behavior * User: Business Tech (www.businesstech.fr) - Contact: http://www.businesstech.fr/en/contact-us * @param string sConnector : connector name : facebook | twitter | google | paypal * @param int iCustId : customer id * @param int iSocialId : customer social id * @param string sAction : FB action : like or want button, etc ... * @param string sType : PS object type: product or manufacturer or supplier ... * @param int iObjId : PS object ID : product or manufacturer or supplier or category ... */ this.collect = function(sConnector, iCustId, iSocialId, sAction, sType, iObjId) { this.ajax(this.sWebService, 'sAction=clt&sType=scl&cn=' + sConnector + '&ci=' + iCustId + '&si=' + iSocialId + '&ca=' + sAction + '&ct=' + sType + '&oi=' + iObjId, null, null, null, null, null); }; };<file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author P<NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AuctionsBlocksSettings', false)) return; class AuctionsBlocksSettings extends CoreModuleSettings { const BLOCK_OFF = 0; const BLOCK_LEFT = 1; const BLOCK_RIGHT = 2; const ITEMS_IN_BLOCK = 5; const ITEMS_IN_HOME_BLOCK = 8; const LATEST_THRESHOLD = 0; const ENDING_THRESHOLD = 0; const POPULAR_THRESHOLD = 0; const FEATURED_CATEGORY = 2; const BLOCKS_LATEST_AUCTIONS_SIDE = 'auct_blc_latest_side'; const BLOCKS_LATEST_AUCTIONS_SIDE_COUNT = 'auct_blc_latest_scount'; const BLOCKS_LATEST_AUCTIONS_HOME = 'auct_blc_latest_home'; const BLOCKS_LATEST_AUCTIONS_HOME_COUNT = 'auct_blc_latest_hcount'; const BLOCKS_LATEST_AUCTIONS_TIME = 'auct_blc_latest_time'; const BLOCKS_ENDING_AUCTIONS_SIDE = 'auct_blc_ending_side'; const BLOCKS_ENDING_AUCTIONS_SIDE_COUNT = 'auct_blc_ending_scount'; const BLOCKS_ENDING_AUCTIONS_HOME = 'auct_blc_ending_home'; const BLOCKS_ENDING_AUCTIONS_HOME_COUNT = 'auct_blc_ending_hcount'; const BLOCKS_ENDING_AUCTIONS_TIME = 'auct_blc_ending_time'; const BLOCKS_POPULAR_AUCTIONS_SIDE = 'auct_blc_popular_side'; const BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT = 'auct_blc_popular_scount'; const BLOCKS_POPULAR_AUCTIONS_HOME = 'auct_blc_popular_home'; const BLOCKS_POPULAR_AUCTIONS_HOME_COUNT = 'auct_blc_popular_hcount'; const BLOCKS_POPULAR_AUCTIONS_TIME = 'auct_blc_popular_time'; const BLOCKS_FEATURED_AUCTIONS_SIDE = 'auct_blc_feat_side'; const BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT = 'auct_blc_feat_scount'; const BLOCKS_FEATURED_AUCTIONS_HOME = 'auct_blc_feat_home'; const BLOCKS_FEATURED_AUCTIONS_HOME_COUNT = 'auct_blc_feat_hcount'; const BLOCKS_FEATURED_AUCTIONS_CATEGORY = 'auct_blc_feat_cat'; protected $submit_action = 'submitBlocks'; public function getTitle() { return $this->l('Blocks'); } public function showForm($tab_index) { $fields_form = array(); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Latest auctions'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'text', 'label' => $this->l('Threshold'), 'name' => self::BLOCKS_LATEST_AUCTIONS_TIME, 'required' => false, 'desc' => $this->l('Decide how many second after the start of the auction, the auction is considered "latest". If "0", the option is disabled.') ), array( 'type' => 'radio', 'label' => $this->l('Side blocks'), 'name' => self::BLOCKS_LATEST_AUCTIONS_SIDE, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::BLOCKS_LATEST_AUCTIONS_SIDE.'OFF', 'label' => $this->l('Disabled'), 'value' => self::BLOCK_OFF ), array( 'id' => self::BLOCKS_LATEST_AUCTIONS_SIDE.'LEFT', 'label' => $this->l('Left'), 'value' => self::BLOCK_LEFT ), array( 'id' => self::BLOCKS_LATEST_AUCTIONS_SIDE.'RIGHT', 'label' => $this->l('Right'), 'value' => self::BLOCK_RIGHT ) ), 'desc' => $this->l('Decide where the block will be located on the page.') ), array( 'type' => 'text', 'label' => $this->l('Side items count'), 'name' => self::BLOCKS_LATEST_AUCTIONS_SIDE_COUNT, 'required' => false, 'desc' => $this->l('Define how many items will be displayed it the block.') ), array( 'type' => 'radio', 'label' => $this->l('Home block'), 'name' => self::BLOCKS_LATEST_AUCTIONS_HOME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::BLOCKS_LATEST_AUCTIONS_HOME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::BLOCKS_LATEST_AUCTIONS_HOME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Decide if "Latest auctions" block will appear on the home page') ), array( 'type' => 'text', 'label' => $this->l('Home items count'), 'name' => self::BLOCKS_LATEST_AUCTIONS_HOME_COUNT, 'required' => false, 'desc' => $this->l('Define how many items will be displayed it the block.') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Ending auctions'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'text', 'label' => $this->l('Threshold'), 'name' => self::BLOCKS_ENDING_AUCTIONS_TIME, 'required' => false, 'desc' => $this->l('Decide how many seconds before the end of the auction, the auction is considered "ending". If "0", the option is disabled.') ), array( 'type' => 'radio', 'label' => $this->l('Side blocks'), 'name' => self::BLOCKS_ENDING_AUCTIONS_SIDE, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::BLOCKS_ENDING_AUCTIONS_SIDE.'OFF', 'label' => $this->l('Disabled'), 'value' => self::BLOCK_OFF ), array( 'id' => self::BLOCKS_ENDING_AUCTIONS_SIDE.'LEFT', 'label' => $this->l('Left'), 'value' => self::BLOCK_LEFT ), array( 'id' => self::BLOCKS_ENDING_AUCTIONS_SIDE.'RIGHT', 'label' => $this->l('Right'), 'value' => self::BLOCK_RIGHT ) ), 'desc' => $this->l('Decide where the block will be located on the page.') ), array( 'type' => 'text', 'label' => $this->l('Side items count'), 'name' => self::BLOCKS_ENDING_AUCTIONS_SIDE_COUNT, 'required' => false, 'desc' => $this->l('Define how many items will be displayed it the block.') ), array( 'type' => 'radio', 'label' => $this->l('Home block'), 'name' => self::BLOCKS_ENDING_AUCTIONS_HOME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::BLOCKS_ENDING_AUCTIONS_HOME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::BLOCKS_ENDING_AUCTIONS_HOME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Decide if "Ending auctions" block will appear on the home page') ), array( 'type' => 'text', 'label' => $this->l('Home items count'), 'name' => self::BLOCKS_ENDING_AUCTIONS_HOME_COUNT, 'required' => false, 'desc' => $this->l('Define how many items will be displayed it the block.') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Popular auctions'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'text', 'label' => $this->l('Threshold'), 'name' => self::BLOCKS_POPULAR_AUCTIONS_TIME, 'required' => false, 'desc' => $this->l('Decide how many bids on the auction, make the auction "popular". If "0", the option is disabled.') ), array( 'type' => 'radio', 'label' => $this->l('Side blocks'), 'name' => self::BLOCKS_POPULAR_AUCTIONS_SIDE, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::BLOCKS_POPULAR_AUCTIONS_SIDE.'OFF', 'label' => $this->l('Disabled'), 'value' => self::BLOCK_OFF ), array( 'id' => self::BLOCKS_POPULAR_AUCTIONS_SIDE.'LEFT', 'label' => $this->l('Left'), 'value' => self::BLOCK_LEFT ), array( 'id' => self::BLOCKS_POPULAR_AUCTIONS_SIDE.'RIGHT', 'label' => $this->l('Right'), 'value' => self::BLOCK_RIGHT ) ), 'desc' => $this->l('Decide where the block will be located on the page.') ), array( 'type' => 'text', 'label' => $this->l('Side items count'), 'name' => self::BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT, 'required' => false, 'desc' => $this->l('Define how many items will be displayed it the block.') ), array( 'type' => 'radio', 'label' => $this->l('Home block'), 'name' => self::BLOCKS_POPULAR_AUCTIONS_HOME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::BLOCKS_POPULAR_AUCTIONS_HOME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::BLOCKS_POPULAR_AUCTIONS_HOME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Decide if "Popular auctions" block will appear on the home page') ), array( 'type' => 'text', 'label' => $this->l('Home items count'), 'name' => self::BLOCKS_POPULAR_AUCTIONS_HOME_COUNT, 'required' => false, 'desc' => $this->l('Define how many items will be displayed it the block.') ) ) ) ); $fields_form[] = array( 'form' => array( 'legend' => array( 'title' => $this->l('Featured auctions'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'select', 'label' => $this->l('Category'), 'name' => self::BLOCKS_FEATURED_AUCTIONS_CATEGORY, 'required' => false, 'options' => array( 'id' => 'value', 'name' => 'label', 'query' => $this->getCategories() ), 'desc' => $this->l('Decide which category makes the auction "featured".') ), array( 'type' => 'radio', 'label' => $this->l('Side blocks'), 'name' => self::BLOCKS_FEATURED_AUCTIONS_SIDE, 'required' => false, 'class' => 't', 'values' => array( array( 'id' => self::BLOCKS_FEATURED_AUCTIONS_SIDE.'OFF', 'label' => $this->l('Disabled'), 'value' => self::BLOCK_OFF ), array( 'id' => self::BLOCKS_FEATURED_AUCTIONS_SIDE.'LEFT', 'label' => $this->l('Left'), 'value' => self::BLOCK_LEFT ), array( 'id' => self::BLOCKS_FEATURED_AUCTIONS_SIDE.'RIGHT', 'label' => $this->l('Right'), 'value' => self::BLOCK_RIGHT ) ), 'desc' => $this->l('Decide where the block will be located on the page.') ), array( 'type' => 'text', 'label' => $this->l('Side items count'), 'name' => self::BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT, 'required' => false, 'desc' => $this->l('Define how many items will be displayed it the block.') ), array( 'type' => 'radio', 'label' => $this->l('Home block'), 'name' => self::BLOCKS_FEATURED_AUCTIONS_HOME, 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array( array( 'id' => self::BLOCKS_FEATURED_AUCTIONS_HOME.'_on', 'value' => self::ENABLED, 'label' => $this->l('Enabled') ), array( 'id' => self::BLOCKS_FEATURED_AUCTIONS_HOME.'_off', 'value' => self::DISABLED, 'label' => $this->l('Disabled') ) ), 'desc' => $this->l('Decide if "Featured auctions" block will appear on the home page') ), array( 'type' => 'text', 'label' => $this->l('Home items count'), 'name' => self::BLOCKS_FEATURED_AUCTIONS_HOME_COUNT, 'required' => false, 'desc' => $this->l('Define how many items will be displayed it the block.') ) ) ) ); return $this->renderForm($fields_form, $tab_index); } public function init() { $this->setValue(self::BLOCKS_LATEST_AUCTIONS_SIDE, (int)Configuration::get(self::BLOCKS_LATEST_AUCTIONS_SIDE)); $this->setValue(self::BLOCKS_LATEST_AUCTIONS_HOME, (int)Configuration::get(self::BLOCKS_LATEST_AUCTIONS_HOME)); $this->setValue(self::BLOCKS_LATEST_AUCTIONS_SIDE_COUNT, (int)Configuration::get(self::BLOCKS_LATEST_AUCTIONS_SIDE_COUNT)); $this->setValue(self::BLOCKS_LATEST_AUCTIONS_HOME_COUNT, (int)Configuration::get(self::BLOCKS_LATEST_AUCTIONS_HOME_COUNT)); $this->setValue(self::BLOCKS_LATEST_AUCTIONS_TIME, (int)Configuration::get(self::BLOCKS_LATEST_AUCTIONS_TIME)); $this->setValue(self::BLOCKS_ENDING_AUCTIONS_SIDE, (int)Configuration::get(self::BLOCKS_ENDING_AUCTIONS_SIDE)); $this->setValue(self::BLOCKS_ENDING_AUCTIONS_HOME, (int)Configuration::get(self::BLOCKS_ENDING_AUCTIONS_HOME)); $this->setValue(self::BLOCKS_ENDING_AUCTIONS_SIDE_COUNT, (int)Configuration::get(self::BLOCKS_ENDING_AUCTIONS_SIDE_COUNT)); $this->setValue(self::BLOCKS_ENDING_AUCTIONS_HOME_COUNT, (int)Configuration::get(self::BLOCKS_ENDING_AUCTIONS_HOME_COUNT)); $this->setValue(self::BLOCKS_ENDING_AUCTIONS_TIME, (int)Configuration::get(self::BLOCKS_ENDING_AUCTIONS_TIME)); $this->setValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE, (int)Configuration::get(self::BLOCKS_POPULAR_AUCTIONS_SIDE)); $this->setValue(self::BLOCKS_POPULAR_AUCTIONS_HOME, (int)Configuration::get(self::BLOCKS_POPULAR_AUCTIONS_HOME)); $this->setValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT, (int)Configuration::get(self::BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT)); $this->setValue(self::BLOCKS_POPULAR_AUCTIONS_HOME_COUNT, (int)Configuration::get(self::BLOCKS_POPULAR_AUCTIONS_HOME_COUNT)); $this->setValue(self::BLOCKS_POPULAR_AUCTIONS_TIME, (int)Configuration::get(self::BLOCKS_POPULAR_AUCTIONS_TIME)); $this->setValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE, (int)Configuration::get(self::BLOCKS_FEATURED_AUCTIONS_SIDE)); $this->setValue(self::BLOCKS_FEATURED_AUCTIONS_HOME, (int)Configuration::get(self::BLOCKS_FEATURED_AUCTIONS_HOME)); $this->setValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT, (int)Configuration::get(self::BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT)); $this->setValue(self::BLOCKS_FEATURED_AUCTIONS_HOME_COUNT, (int)Configuration::get(self::BLOCKS_FEATURED_AUCTIONS_HOME_COUNT)); $this->setValue(self::BLOCKS_FEATURED_AUCTIONS_CATEGORY, (int)Configuration::get(self::BLOCKS_FEATURED_AUCTIONS_CATEGORY)); } public function install() { Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_SIDE, self::BLOCK_OFF); Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_HOME, self::BLOCK_OFF); Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_SIDE_COUNT, self::ITEMS_IN_BLOCK); Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_HOME_COUNT, self::ITEMS_IN_HOME_BLOCK); Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_TIME, self::LATEST_THRESHOLD); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_SIDE, self::BLOCK_OFF); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_HOME, self::BLOCK_OFF); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_SIDE_COUNT, self::ITEMS_IN_BLOCK); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_HOME_COUNT, self::ITEMS_IN_HOME_BLOCK); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_TIME, self::ENDING_THRESHOLD); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE, self::BLOCK_OFF); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_HOME, self::BLOCK_OFF); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT, self::ITEMS_IN_BLOCK); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_HOME_COUNT, self::ITEMS_IN_HOME_BLOCK); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_TIME, self::POPULAR_THRESHOLD); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE, self::BLOCK_OFF); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_HOME, self::BLOCK_OFF); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT, self::ITEMS_IN_BLOCK); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_HOME_COUNT, self::ITEMS_IN_HOME_BLOCK); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_CATEGORY, self::FEATURED_CATEGORY); return true; } public function uninstall() { Configuration::deleteByName(self::BLOCKS_LATEST_AUCTIONS_SIDE); Configuration::deleteByName(self::BLOCKS_LATEST_AUCTIONS_HOME); Configuration::deleteByName(self::BLOCKS_LATEST_AUCTIONS_SIDE_COUNT); Configuration::deleteByName(self::BLOCKS_LATEST_AUCTIONS_HOME_COUNT); Configuration::deleteByName(self::BLOCKS_LATEST_AUCTIONS_TIME); Configuration::deleteByName(self::BLOCKS_ENDING_AUCTIONS_SIDE); Configuration::deleteByName(self::BLOCKS_ENDING_AUCTIONS_HOME); Configuration::deleteByName(self::BLOCKS_ENDING_AUCTIONS_SIDE_COUNT); Configuration::deleteByName(self::BLOCKS_ENDING_AUCTIONS_HOME_COUNT); Configuration::deleteByName(self::BLOCKS_ENDING_AUCTIONS_TIME); Configuration::deleteByName(self::BLOCKS_POPULAR_AUCTIONS_SIDE); Configuration::deleteByName(self::BLOCKS_POPULAR_AUCTIONS_HOME); Configuration::deleteByName(self::BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT); Configuration::deleteByName(self::BLOCKS_POPULAR_AUCTIONS_HOME_COUNT); Configuration::deleteByName(self::BLOCKS_POPULAR_AUCTIONS_TIME); Configuration::deleteByName(self::BLOCKS_FEATURED_AUCTIONS_SIDE); Configuration::deleteByName(self::BLOCKS_FEATURED_AUCTIONS_HOME); Configuration::deleteByName(self::BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT); Configuration::deleteByName(self::BLOCKS_FEATURED_AUCTIONS_HOME_COUNT); Configuration::deleteByName(self::BLOCKS_FEATURED_AUCTIONS_CATEGORY); return true; } public function update() { Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_SIDE, (int)Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_SIDE)); Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_HOME, (int)Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_HOME)); Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_SIDE_COUNT, (int)Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_SIDE_COUNT)); Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_HOME_COUNT, (int)Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_HOME_COUNT)); Configuration::updateValue(self::BLOCKS_LATEST_AUCTIONS_TIME, (int)Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_TIME)); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_SIDE, (int)Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_SIDE)); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_HOME, (int)Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_HOME)); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_SIDE_COUNT, (int)Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_SIDE_COUNT)); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_HOME_COUNT, (int)Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_HOME_COUNT)); Configuration::updateValue(self::BLOCKS_ENDING_AUCTIONS_TIME, (int)Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_TIME)); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE, (int)Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE)); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_HOME, (int)Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_HOME)); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT, (int)Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT)); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_HOME_COUNT, (int)Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_HOME_COUNT)); Configuration::updateValue(self::BLOCKS_POPULAR_AUCTIONS_TIME, (int)Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_TIME)); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE, (int)Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE)); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_HOME, (int)Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_HOME)); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT, (int)Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT)); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_HOME_COUNT, (int)Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_HOME_COUNT)); Configuration::updateValue(self::BLOCKS_FEATURED_AUCTIONS_CATEGORY, (int)Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_CATEGORY)); return true; } protected function validate() { $condition = true; $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_SIDE)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_HOME)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_SIDE_COUNT)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_HOME_COUNT)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_LATEST_AUCTIONS_TIME)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_SIDE)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_HOME)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_SIDE_COUNT)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_HOME_COUNT)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_ENDING_AUCTIONS_TIME)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_HOME)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_SIDE_COUNT)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_HOME_COUNT)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_POPULAR_AUCTIONS_TIME)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_HOME)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_SIDE_COUNT)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_HOME_COUNT)); $condition &= Validate::isInt(Tools::getValue(self::BLOCKS_FEATURED_AUCTIONS_CATEGORY)); return $condition; } protected function getCategories() { $categories = CategoryCore::getSimpleCategories($this->context->language->id); $categories_options = array(); foreach ($categories as $category) { $categories_options[] = array( 'label' => $category['name'], 'value' => $category['id_category'] ); } return $categories_options; } } <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ /** * Link to access the controller : $link->getModuleLink('powatag', 'confirmation'). */ class PowatagConfirmationModuleFrontController extends ModuleFrontController { public function __construct() { $this->display_column_left = false; $this->display_column_right = false; parent::__construct(); $this->context = Context::getContext(); } public function postProcess() { parent::postProcess(); } public function init() { parent::init(); } public function initContent() { parent::initContent(); // Init smarty content and set template to display $order = new Order(Order::getOrderByCartId(Tools::getValue('id_cart'))); if ($order->id_customer == Tools::getValue('id_customer')) { $this->context->smarty->assign(array( 'order' => $order, 'state' => new OrderState($order->current_state, $this->context->language->id), )); $this->setTemplate('confirmation.tpl'); } else { $this->setTemplate('error.tpl'); } } public function setMedia() { parent::setMedia(); $this->addCSS(__PS_BASE_URI__.'modules/powatag/views/css/confirmation.css'); } } <file_sep><?php /** * 2007-2015 PrestaShop. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author Presta<NAME> <<EMAIL>> * @copyright 2007-2014 PrestaShop SA * * @version Release: $Revision: 7776 $ * * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ abstract class PowaTagAbstract { /* public static $BAD_REQUEST = array('code' => '400101', 'response' => 400); public static $SHOP_NOT_FOUND = array('code' => 'SHOP_NOT_FOUND', 'response' => 404); public static $SKU_NOT_FOUND = array('code' => '200210', 'response' => 200); public static $NOT_IN_STOCK = array('code' => 'NOT_IN_STOCK', 'response' => 400); public static $INVALID_PAYMENT = array('code' => 'INVALID_PAYMENT', 'response' => 400); public static $UNEXPECTED_ERROR = array('code' => 'UNEXPECTED_ERROR', 'response' => 500); */ /** * Request datas. * * @var array */ protected $datas; /** * Current context. * * @var Context */ protected $context; protected $display_taxes; /** * Module. * * @var Module */ protected $module; /** * Errors. * * @var array */ protected $error = array(); /** * Total without tax. * * @var int */ protected $subTotal = 0; /** * Total with tax. * * @var int */ protected $subTotalWt = 0; /** * Total tax for products. * * @var int */ protected $subTax = 0; public function __construct(stdClass $datas) { $this->datas = $datas; $this->context = Context::getContext(); $this->module = Module::getInstanceByName('powatag'); $this->initLang(); $id_group = Group::getCurrent()->id; $this->display_taxes = Group::getPriceDisplayMethod($id_group) == PS_TAX_EXC ? false : true; } public function initLang() { if ($iso = Tools::getValue('lang')) { $lang = Tools::substr($iso, 0, 2); if ($language_id = Language::getIdByIso($lang)) { $this->context->language = new Language($language_id); } } } /** * Get error. * * @return string Error */ public function getError() { return $this->error; } public function addError($message, $error = null) { if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Error', PowaTagLogs::ERROR, $message); } if (is_null($error)) { $error = PowaTagErrorType::$UNEXPECTED_ERROR; } if (count($this->error)) { return; } $this->error = array( 'error' => $error, 'message' => $message, ); } public function getCountry($codeCountry) { if (Validate::isInt($codeCountry)) { $country = new Country($codeCountry); } elseif (!$codeCountry instanceof Country) { $country = $this->getCountryByCode($codeCountry); } return $country; } /** * Get currency object by iso_code. * * @param string $iso_code ISO code * * @return Currency Currency Object */ protected function getCurrencyByIsoCode($iso_code) { $idCurrency = (int) Currency::getIdByIsoCode($iso_code); $currency = new Currency($idCurrency); if (!PowaTagValidate::currencyEnable($currency)) { $this->addError(sprintf($this->module->l('Currency not found : %s'), $iso_code), PowaTagErrorType::$CURRENCY_NOT_SUPPORTED); return false; } return $currency; } /** * Get Country object by code. * * @param string $code Code * * @return Country Country object */ protected function getCountryByCode($code) { $idCountry = (int) Country::getByIso($code); $country = new Country($idCountry, (int) $this->context->language->id); return $country; } /** * Calculate total of products without tax. * * @return float Total of products */ protected function getSubTotal($products, $codeCountry, $check = true) { if (Validate::isInt($codeCountry)) { $country = new Country($codeCountry); } elseif (!$codeCountry instanceof Country) { $country = $this->getCountryByCode($codeCountry); } $address = Address::initialize(); $address->id_country = $country->id; if ($products && count($products)) { foreach ($products as $p) { $product = PowaTagProductHelper::getProductByCode($p->product->code, $this->context->language->id); if (!Validate::isLoadedObject($product)) { $this->addError(sprintf($this->module->l('This product does not exists : %s'), $p->product->code), PowaTagErrorType::$SKU_NOT_FOUND); return false; } $variants = $p->product->productVariants; $product_rate = 1 + ($product->getTaxesRate($address) / 100); foreach ($variants as $variant) { $variantCurrency = $this->getCurrencyByIsoCode($variant->finalPrice->currency); if (!PowaTagValidate::currencyEnable($variantCurrency)) { $this->addError(sprintf($this->module->l('Currency not found : %s'), $variantCurrency), PowaTagErrorType::$CURRENCY_NOT_SUPPORTED); return false; } $variantAmount = $variant->finalPrice->amount; if ($id_product_attribute = PowaTagProductAttributeHelper::getCombinationByCode($product->id, $variant->code)) { $priceAttribute = $product->getPrice(false, $id_product_attribute); $qtyInStock = PowaTagProductQuantityHelper::getProductQuantity($product, $id_product_attribute); } elseif ($product) { $priceAttribute = $product->getPrice(false); $qtyInStock = PowaTagProductQuantityHelper::getProductQuantity($product); } else { $this->addError(sprintf($this->module->l('This variant does not exist : %s'), $variant->code), PowaTagErrorType::$SKU_NOT_FOUND); return false; } $priceAttributeWt = $priceAttribute * $product_rate; $this->convertToCurrency($variantAmount, $variantCurrency, false); if (version_compare(_PS_VERSION_, 1.6, '<')) { $priceAttribute = Tools::ps_round($priceAttribute, 2); $variantAmount = Tools::ps_round($variantAmount, 2); $priceAttributeWt = Tools::ps_round($priceAttributeWt, 2); } if ($check && $priceAttribute != $variantAmount) { $this->addError(sprintf($this->module->l('Price variant is different with the price shop : %s %s != %s'), $variant->code, $priceAttribute, $variantAmount), PowaTagErrorType::$OTHER_PRODUCT_ERROR); return false; } if ($qtyInStock == 0) { $this->addError(sprintf($this->module->l('No Stock Available'), $variant->code), PowaTagErrorType::$SKU_OUT_OF_STOCK); return false; } if ($qtyInStock < $p->quantity) { $this->addError(sprintf($this->module->l('Quantity > Stock Count'), $variant->code), PowaTagErrorType::$INSUFFICIENT_STOCK); return false; } $totalPriceAttribute = ($priceAttribute * $p->quantity); $totalPriceAttributeWt = ($priceAttributeWt * $p->quantity); $this->subTotal += $totalPriceAttribute; $this->subTotalWt += $totalPriceAttributeWt; $this->subTax += ($totalPriceAttributeWt - $totalPriceAttribute); } } $this->subTax = $this->subTotalWt - $this->subTotal; return true; } else { return false; } } /** * Calculate shipping costs without tax. * * @return float Shipping costs */ protected function getShippingCost($products, Currency $currency, $country, $useTax = true) { $id_carrier = (int) Configuration::get('POWATAG_SHIPPING'); if (!$country instanceof Country) { if (Validate::isInt($country)) { $country = new Country((int) $country, (int) $this->context->language->id); } else { $country = $this->getCountryByCode($country); } } if (!PowaTagValidate::countryEnable($country)) { $this->addError(sprintf($this->module->l('Country does not exists or is not enabled for this shop : %s'), $country->iso_code), PowaTagErrorType::$MERCHANT_WRONG_COUNTRY); return false; } $shippingCost = $this->getShippingCostByCarrier($products, $currency, $id_carrier, $country, $useTax); if (!$shippingCost) { $shippingCost = 0.0; } if (Validate::isFloat($shippingCost)) { return $shippingCost; } else { return false; } } /** * Get Shipping By barrier. * * @param int $id_carrier ID Carrier * @param Country $country Country * @param float $subTotal Total Products * @param bool $useTax If use tax * * @return float Shipping Costs */ private function getShippingCostByCarrier($products, Currency $currency, $id_carrier, Country $country, $useTax = false) { $productLists = $products; $shippingCost = 0; $id_zone = (int) $country->id_zone; $carrier = new Carrier($id_carrier, (int) $this->context->language->id); if (!$this->ifCarrierDeliveryZone($carrier, $id_zone)) { return false; } $address = new Address(); $address->id_country = (int) $country->id; $address->id_state = 0; $address->postcode = 0; if ($useTax && !Tax::excludeTaxeOption()) { $carrier_tax = $carrier->getTaxesRate($address); } $configuration = Configuration::getMultiple(array( 'PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT', )); $shippingMethod = $carrier->getShippingMethod(); // Get shipping cost using correct method if ($carrier->range_behavior) { if (($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT && !Carrier::checkDeliveryPriceByWeight($carrier->id, 0, (int) $id_zone)) || ($shippingMethod == Carrier::SHIPPING_METHOD_PRICE && !Carrier::checkDeliveryPriceByPrice($carrier->id, $this->subTotalWt, $id_zone, (int) $this->id_currency) )) { $shippingCost += 0; } else { if ($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT) { $shippingCost += $carrier->getDeliveryPriceByWeight(0, $id_zone); } else { // by price $shippingCost += $carrier->getDeliveryPriceByPrice($this->subTotalWt, $id_zone, (int) $currency->id); } } } else { if ($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT) { $shippingCost += $carrier->getDeliveryPriceByWeight(0, $id_zone); } else { $shippingCost += $carrier->getDeliveryPriceByPrice($this->subTotalWt, $id_zone, (int) $currency->id); } } if (isset($configuration['PS_SHIPPING_HANDLING']) && $carrier->shipping_handling) { $shippingCost += (float) $configuration['PS_SHIPPING_HANDLING']; } foreach ($productLists as $p) { $product = new Product($p->product->code); $shippingCost += ($product->additional_shipping_cost * $p->quantity); } // Apply tax if ($useTax && isset($carrier_tax)) { $shippingCost *= 1 + ($carrier_tax / 100); } $shippingCost = (float) Tools::ps_round((float) $shippingCost, 2); return $shippingCost; } private function isCarrierInRange($carrier, $id_zone) { if (!$carrier->range_behavior) { PowaTagLogs::initAPILog('isCarrierInRange', PowaTagLogs::SUCCESS, '! carrier->range_behavior'); return true; } $shipping_method = $carrier->getShippingMethod(); if ($shipping_method == Carrier::SHIPPING_METHOD_FREE) { PowaTagLogs::initAPILog('isCarrierInRange', PowaTagLogs::SUCCESS, 'shipping_method == Carrier::SHIPPING_METHOD_FREE'); return true; } $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight( (int) $carrier->id, null, $id_zone ); if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT && $check_delivery_price_by_weight) { PowaTagLogs::initAPILog('isCarrierInRange', PowaTagLogs::SUCCESS, 'shipping_method == Carrier::SHIPPING_METHOD_WEIGHT ...'); return true; } $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice( (int) $carrier->id, $this->subTotal, $id_zone, (int) $this->id_currency ); if ($shipping_method == Carrier::SHIPPING_METHOD_PRICE && $check_delivery_price_by_price) { PowaTagLogs::initAPILog('isCarrierInRange', PowaTagLogs::SUCCESS, 'shipping_method == Carrier::SHIPPING_METHOD_PRICE ...'); return true; } PowaTagLogs::initAPILog('isCarrierInRange', PowaTagLogs::ERROR, 'No suitable shipping method found'); return false; } /** * Calculate tax (Shipping + Products). * * @return float Total tax */ protected function getTax($products, Currency $currency, $country) { $id_carrier = (int) Configuration::get('POWATAG_SHIPPING'); if (!$country instanceof Country) { $country = new Country($country); } $tax = $this->subTax; $shippingCostWt = $this->getShippingCostByCarrier($products, $currency, $id_carrier, $country, $this->subTotal, true); $tax += ($shippingCostWt - $this->shippingCost); return (float) Tools::ps_round($tax, 2); } /** * Check if customer has tax. * * @param mix $customer Customer information (id|email|object) * * @return bool Tax enable */ protected function taxEnableByCustomer($customer) { if (!Validate::isLoadedObject($customer)) { if (Validate::isEmail($customer)) { $customer = $this->getCustomerByEmail($customer); } elseif (Validate::isInt($customer)) { $customer = new Customer((int) $customer); } } return !Group::getPriceDisplayMethod((int) $customer->id_default_group); } protected function getCustomerByEmail($email, $register = false, $lastName = null, $firstName = null, $emailAddress = null) { $customer = new Customer(); $customer->getByEmail($email); if (!Validate::isLoadedObject($customer) && $register) { if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create customer', PowaTagLogs::IN_PROGRESS, 'Customer : '.$lastName.' '.$firstName); } $customer->lastname = $lastName; $customer->firstname = $firstName; $customer->email = $emailAddress; $customer->setWsPasswd(Tools::substr($customer->lastname, 0, 1).$firstName); if (!$customer->save()) { $this->addError($this->module->l('Impossible to save customer'), PowaTagErrorType::$INTERNAL_ERROR); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create customer', PowaTagLogs::ERROR, $this->error['message']); } return false; } if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create customer', PowaTagLogs::SUCCESS, 'Customer ID : '.$customer->id); } } return $customer; } protected function formatNumber($number, $precision = 0) { $number = Tools::ps_round($number, $precision); return number_format($number, 2, '.', ''); } protected function ifCarrierDeliveryZone($carrier, $id_zone = false, $country = false) { if (!$carrier instanceof Carrier) { if (Validate::isInt($carrier)) { $carrier = new Carrier((int) $carrier); } else { $this->addError($this->module->l('Error since load carrier'), PowaTagErrorType::$MERCHANT_WRONG_COUNTRY); return false; } } if (!$id_zone && !$country) { $this->addError($this->module->l('Thanks to fill country or id zone'), PowaTagErrorType::$MERCHANT_WRONG_COUNTRY); return false; } elseif (!$id_zone && $country) { if (!$country instanceof Country) { if (Validate::isInt($country)) { $country = new Country($country); } else { $country = self::getCountryByCode($country); } } if (!PowaTagValidate::countryEnable($country)) { $this->addError($this->module->l('Country does not exists or not active'), PowaTagErrorType::$MERCHANT_WRONG_COUNTRY); return false; } $id_zone = (int) $country->id_zone; } if (!$this->isCarrierInRange($carrier, $id_zone)) { $this->addError(sprintf($this->module->l('Carrier not delivery in : %s'), $country->name), PowaTagErrorType::$MERCHANT_WRONG_COUNTRY); return false; } if (!$carrier->active) { $this->addError(sprintf($this->module->l('Carrier is not active : %s'), $carrier->name), PowaTagErrorType::$MERCHANT_WRONG_COUNTRY); return false; } if ($carrier->is_free == 1) { return true; } $shippingMethod = $carrier->getShippingMethod(); // Get only carriers that are compliant with shipping method if (($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight($id_zone) === false) || ($shippingMethod == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice($id_zone) === false)) { $this->addError(sprintf($this->module->l('Carrier not delivery for this shipping method in ID Zone : %s'), $id_zone), PowaTagErrorType::$MERCHANT_WRONG_COUNTRY); return false; } return true; } protected function convertToCurrency(&$amount, $currency, $toCurrency = true) { if ($currency->iso_code != $this->context->currency->iso_code) { $amount = Tools::convertPrice($amount, $currency, $toCurrency); } } /** * Create or Updates Prestashop address. * * @return Address Address object */ protected function createAddress($addressInformations, $address = null) { $country = $this->getCountryByCode($addressInformations->country->alpha2Code); if (!$country->active) { $this->addError(sprintf($this->module->l('This country is not active : %s'), $addressInformations->country->alpha2Code), PowaTagErrorType::$MERCHANT_WRONG_COUNTRY); return false; } if (!isset($addressInformations->friendlyName)) { $friendlyName = $this->module->l('My address'); } else { $friendlyName = $addressInformations->friendlyName; } if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create address', PowaTagLogs::IN_PROGRESS, $addressInformations->lastName.' '.$addressInformations->firstName.' : '.$friendlyName); } $address = $address != null ? $address : Address::initialize(); $address->id_customer = (int) $this->customer->id; $address->id_country = (int) $country->id; $address->alias = $friendlyName; $address->lastname = $addressInformations->lastName; $address->firstname = $addressInformations->firstName; $address->address1 = $addressInformations->line1; $address->address2 = $addressInformations->line2; $address->postcode = $addressInformations->postCode; $address->city = $addressInformations->city; $address->phone = isset($addressInformations->phone) ? $addressInformations->phone : '0000000000'; $address->id_state = isset($addressInformations->state) ? (int) State::getIdByIso($addressInformations->state, (int) $country->id) : 0; try { if (!$address->save()) { $this->addError('Cannot save address', PowaTagErrorType::$OTHER_ADDRESS_ERROR); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create address', PowaTagLogs::ERROR, $this->error['message']); } return false; } } catch (Exception $e) { $this->addError($e->getMessage(), PowaTagErrorType::$OTHER_ADDRESS_ERROR); if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create address', PowaTagLogs::ERROR, $this->error['message']); } return false; } if (PowaTagAPI::apiLog()) { PowaTagLogs::initAPILog('Create address', PowaTagLogs::SUCCESS, 'Address ID : '.$address->id); } return $address; } public function checkProductsAreShippable($products) { foreach ($products as $p) { $carrier_ok = false; $product = PowaTagProductHelper::getProductByCode($p->product->code, $this->context->language->id); if (!$product) { // product not found $this->addError($this->module->l('This product does not exists : ').$p->product->code, PowaTagErrorType::$SKU_NOT_FOUND); return; } $carriers = $product->getCarriers(); if (count($carriers)) { $powatag_carrier = Configuration::get('POWATAG_SHIPPING'); foreach ($carriers as $carrier) { if ($carrier['id_carrier'] == $powatag_carrier) { $carrier_ok = true; break; } } if (!$carrier_ok) { $this->addError($this->module->l('Product with id').' '.$product->id.' '.$this->module->l('cannot be shipped with the carrier ').' '.$powatag_carrier, PowaTagErrorType::$MERCHANT_WRONG_COUNTRY); } } } } public function checkOrderState($id_order, &$data) { $order = new Order($id_order); if ($order->current_state == Configuration::get('PS_OS_ERROR')) { $data = array( 'code' => PowaTagErrorType::$FAILED_TO_PLACE_ORDER['code'], 'response' => PowaTagErrorType::$FAILED_TO_PLACE_ORDER['response'], 'errorMessage' => $this->module->l('Error while creating the order. Payment error ' . $this->error['message']), ); return 'error'; } return false; } } <file_sep><?php /** * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to <EMAIL> so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author <NAME> <<EMAIL>> * @copyright 2007-2015 PrestaShop SA * @version Release: $Revision: 6844 $ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ if (!defined('_PS_VERSION_')) exit(); if (class_exists('AdminAuctionsSubscriptionsController', false)) return; class AdminAuctionsSubscriptionsController extends ModuleAdminController { protected $tab_access_customers; protected $product_identifier; protected $product_table; protected $product_class_name; protected $id_product; public function __construct() { $this->bootstrap = true; $this->identifier = 'id_product_auction'; $this->table = 'product_auction_subscriptions'; $this->className = 'ProductAuction'; $this->product_identifier = 'id_product'; $this->product_table = 'product'; $this->product_class_name = 'Product'; $this->list_no_link = false; $this->explicitSelect = true; parent::__construct(); $this->tab_access_customers = Profile::getProfileAccess($this->context->employee->id_profile, Tab::getIdFromClassName('AdminCustomers')); if ($this->tabAccess['delete']) $this->bulk_actions = array( 'delete' => array( 'text' => $this->l('Delete selected'), 'confirm' => $this->l('Are you sure you want to permanently delete the selected items?') ) ); $this->_defaultOrderBy = $this->identifier; $genders = array(); $genders_icon = array(); $genders_icon[] = array( 'src' => '../genders/Unknown.jpg', 'alt' => '' ); foreach (Gender::getGenders() as $gender) { $gender_file = 'genders/'.$gender->id.'.jpg'; if (file_exists(_PS_IMG_DIR_.$gender_file)) $genders_icon[$gender->id] = array( 'src' => '../'.$gender_file, 'alt' => $gender->name ); else $genders_icon[$gender->id] = array( 'src' => '../genders/Unknown.jpg', 'alt' => $gender->name ); $genders[$gender->id] = $gender->name; } $this->fields_list = array(); $this->fields_list['id_customer'] = array( 'title' => $this->l('Customer ID'), 'width' => 80, 'filter_key' => 'jc!id_customer' ); $this->fields_list['id_gender'] = array( 'title' => $this->l('Title'), 'width' => 70, 'align' => 'center', 'icon' => $genders_icon, 'orderby' => false, 'type' => 'select', 'list' => $genders, 'filter_key' => 'jc!id_gender' ); $this->fields_list['lastname'] = array( 'title' => $this->l('Last name'), 'width' => 'auto', 'filter_key' => 'jc!lastname' ); $this->fields_list['firstname'] = array( 'title' => $this->l('First Name'), 'width' => 'auto', 'filter_key' => 'jc!firstname' ); $this->fields_list['email'] = array( 'title' => $this->l('Email address'), 'width' => 140, 'filter_key' => 'jc!email' ); $this->fields_list['age'] = array( 'title' => $this->l('Age'), 'width' => 40, 'align' => 'center', 'havingFilter' => true, ); $this->fields_list['active'] = array( 'title' => $this->l('Enabled'), 'width' => 70, 'align' => 'center', 'type' => 'bool', 'icon' => array(0 => array('class' => 'icon-2x icon-red icon-times-circle'), 1 => array('class' => 'icon-2x icon-green icon-check-circle')), 'orderby' => false, 'filter_key' => 'jc!active' ); $this->fields_list['date_add'] = array( 'title' => $this->l('Date'), 'filter_key' => 'a!date_add' ); $this->_select = ' a.id_product_auction, IF (YEAR(jc.`birthday`) = 0, "-", (YEAR(CURRENT_DATE)-YEAR(jc.`birthday`)) - (RIGHT(CURRENT_DATE, 5) < RIGHT(jc.birthday, 5))) AS `age` '; $this->_join .= ' INNER JOIN `'._DB_PREFIX_.'customer` jc ON (jc.`id_customer` = a.`id_customer`) '; $this->loadObject(true); $this->tpl_delete_link_vars = array( 'id_product_auction' => $this->object->id ); if (!$this->module->getSettings('AuctionsFeaturesSettings')->getValue(AuctionsFeaturesSettings::PERMISSIONS_SHOW_WATCH_AUCTION)) Tools::redirectAdmin($this->context->link->getAdminLink('AdminAuctionsView')."&{$this->identifier}={$this->object->id}"); if (Validate::isLoadedObject($this->object)) { $this->_where .= ' AND a.id_product_auction = '.$this->object->id; $this->id_product = $this->object->id_product; $this->object->setProduct(new Product($this->id_product)); } } public function init() { parent::init(); self::$currentIndex .= "&{$this->identifier}={$this->object->id}"; } public function initToolbar() { parent::initToolbar(); unset($this->toolbar_btn['new']); // Default cancel button - like old back link $back = Tools::safeOutput(Tools::getValue('back', $this->context->link->getAdminLink('AdminAuctionsView')."&{$this->identifier}={$this->object->id}")); if (!Validate::isCleanHtml($back)) die(Tools::displayError()); $this->toolbar_btn['back'] = array( 'href' => $back, 'desc' => $this->l('Back to details') ); $this->context->smarty->assign('toolbar_scroll', 1); $this->context->smarty->assign('show_toolbar', 1); $this->context->smarty->assign('toolbar_btn', $this->toolbar_btn); } public function initToolbarTitle() { parent::initToolbarTitle(); if ($this->id_product > 0 && isset($this->toolbar_title[0])) $this->toolbar_title[0] = $this->object->product->name[$this->context->language->id]; } public function renderView() { if ($this->tab_access_customers['view']) { $customer_id = (int)Tools::getValue('id_customer'); $product_auction_id = (int)$this->object->id; $back = urlencode($this->context->link->getAdminLink('AdminAuctionsSubscriptions')."&id_product_auction={$product_auction_id}"); Tools::redirectAdmin($this->context->link->getAdminLink('AdminCustomers')."&viewcustomer&id_customer={$customer_id}&back={$back}"); } } public function renderList() { if (!$this->object->id) Tools::redirectAdmin($this->context->link->getAdminLink('AdminAuctions')); $this->identifier = 'id_customer'; if ($this->tab_access_customers['view']) $this->addRowAction('view'); if ($this->tabAccess['delete']) $this->addRowAction('delete'); if (Module::isInstalled('agilemultipleseller')) if ($this->is_seller) $this->actions = array_diff($this->actions, array( 'view' )); return parent::renderList(); } public function processDelete() { $res = true; if (Validate::isLoadedObject($object = $this->loadObject())) { // check if request at least one object with noZeroObject if (isset($object->noZeroObject) && count(call_user_func(array( $this->className, $object->noZeroObject ))) <= 1) $this->errors[] = Tools::displayError('You need at least one object.').' <b>'.$this->table.'</b><br />'.Tools::displayError('You cannot delete all of the items.'); elseif (array_key_exists('delete', $this->list_skip_actions) && in_array($object->id, $this->list_skip_actions['delete'])) // check if some ids are in list_skip_actions and forbid deletion $this->errors[] = Tools::displayError('You cannot delete this item.'); else { $id_customer = (int)Tools::getValue('id_customer'); $res = Db::getInstance()->execute(' DELETE FROM `'._DB_PREFIX_.'product_auction_subscriptions` WHERE id_product_auction = '.(int)$this->object->id.' AND id_customer = '.$id_customer.' '); if ($res) $this->redirect_after = self::$currentIndex.'&conf=1&token='.$this->token; $this->errors[] = Tools::displayError('An error occurred during deletion.'); if ($res) Logger::addLog(sprintf($this->l('%s deletion', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$this->object->id, true, (int)$this->context->employee->id); } } else $this->errors[] = Tools::displayError('An error occurred while deleting the object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)'); return $object; } protected function processBulkDelete() { if (is_array($this->boxes) && !empty($this->boxes)) { if (Validate::isLoadedObject($object = $this->loadObject())) { if (isset($object->noZeroObject)) { $objects_count = count(call_user_func(array( $this->className, $object->noZeroObject ))); // Check if all object will be deleted if ($objects_count <= 1 || count($this->boxes) == $objects_count) $this->errors[] = Tools::displayError('You need at least one object.').' <b>'.$this->table.'</b><br />'.Tools::displayError('You cannot delete all of the items.'); } else { $result = true; foreach ($this->boxes as $id) { $delete_ok = true; $res = Db::getInstance()->execute(' DELETE FROM `'._DB_PREFIX_.'product_auction_subscriptions` WHERE id_product_auction = '.(int)$this->object->id.' AND id_customer = '.(int)$id.' '); if (!$res) { $result = false; $delete_ok = false; } if ($delete_ok) Logger::addLog(sprintf($this->l('%s deletion', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$id, true, (int)$this->context->employee->id); else $this->errors[] = sprintf(Tools::displayError('Can\'t delete #%d'), $id); } if ($result) $this->redirect_after = self::$currentIndex.'&conf=2&token='.$this->token; $this->errors[] = Tools::displayError('An error occurred while deleting this selection.'); } } else $this->errors[] = Tools::displayError('An error occurred while deleting the object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)'); } else $this->errors[] = Tools::displayError('You must select at least one element to delete.'); if (isset($result)) return $result; else return false; } public function viewAccess($disable = false) { if (!Module::isInstalled('agilemultipleseller')) return parent::viewAccess($disable); $eaccess = AgileSellerManager::get_entity_access($this->product_table); if ($this->is_seller && $this->object->id_product) { $id_owner = AgileSellerManager::getObjectOwnerID($this->product_table, $this->object->id_product); if ($id_owner > 0 || $eaccess['is_exclusive']) if (!AgileSellerManager::hasOwnership($this->product_table, $this->object->id_product)) return false; } if ($disable) return true; if ($this->tabAccess['view'] === '1') return true; return false; } }
fb9b975b770dd167d7281860deefc11049fb6826
[ "JavaScript", "SQL", "PHP" ]
155
PHP
yonkon/smith.int
0ce90954d6dc88b3a9595cace01f91f425e6a91e
d623ec259d67144874ed5da807641c15fa028abe
refs/heads/main
<file_sep>import React, { PropTypes, Component } from 'react'; import { View, Text, Button, Alert, StyleSheet , Image, TouchableOpacity, ImageBackground, ScrollView} from 'react-native'; import Card from './Layout/Card'; import Buttons from './Layout/Buttons'; import Img from '../assets/images/_image'; import 'localstorage-polyfill'; const br = `\n`; export default class Information extends Component { constructor(props) { super(props); } render = () => { return( <View style={{flex:1}}> <ImageBackground source={Img.background} style={styles.imageBackground}> <View style={{flex:2, justifyContent: 'center', flexDirection: 'column', alignItems: 'center',}}> <Text style={styles.centerText}>ShiFumi Heroes</Text> </View> <View style={{flex:5, justifyContent: 'center', flexDirection: 'column', alignItems: 'center',}}> <ScrollView> <Text style={[{}, styles.centerTextMin]}>Le jeu du Shifumi est une bataille, vous devez battre l'adversaire à l'aide de choix. Choisissez entre la pierre, la feuille ou les ciseaux. {br}{br} La feuille bat la pierre. {br}{br} La pierre bat les ciseaux. {br}{br} Les ciseaux battent la feuille. {br}{br} Une partie se déroule en 3 manches. Pensez donc à la psychologie du joueur adverse pour élaborer des stratégies.{br}{br} Notez que l'application recherche des joueurs pendant 45 secondes, si il n'y a pas de joueurs disponible, alors il faudra essayer plus tard, ou inviter vos amis ! En attendant, vous pouvez vous entrainer avec le mode solo. </Text> </ScrollView> </View> </ImageBackground> </View> ); } } const styles = StyleSheet.create({ centerTextTimeout :{ fontSize:15, color: 'rgb(240,240,240)', paddingLeft: 60, paddingRight: 60, }, centerTextMin:{ //marginTop: 30, //justifyContent: 'center', fontSize: 17, //marginLeft:150, fontWeight: 'bold', color:'white', paddingLeft: 50, paddingRight: 50, }, centerText:{ //marginTop: 200, //justifyContent: 'center', fontSize: 25, //marginLeft:50, fontWeight: 'bold', color:'white', }, view: { flex: 1, backgroundColor: '#1abc9c', }, imageBackground: { flex: 4, width: '100%', height: '100%', }, });<file_sep>module.exports = function(api) { api.cache(true); return { presets: ['babel-preset-expo'], /* resolve: { modules: [__dirname,path.join(__dirname, '../src'), 'node_modules'] } */ }; }; <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, Text, Navigator, Button, StyleSheet, ImageBackground, TouchableOpacity, Image } from 'react-native'; import Img from '../assets/images/_image'; const br = `\n`; export default class Configuration extends Component { constructor(props) { super(props); this.state = { radioSet: ['1', '2', '3', '4'], radioDifficulty: ['Easy', 'Medium', 'Hard', 'Impossible'], checkedSet: 0, checkedDifficulty: 0 } // SAVE AND EXPORT CONFIGURATION // use redux ? } render() { return ( <View style={styles.view}> <ImageBackground source={Img.background} style={styles.imageBackground}> <View style={styles.header}> <Text style={styles.title}>Configuration{br}{br}{br}</Text> <Text style={styles.textConfig}> Nombre de manche{br}</Text> <View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'stretch'}}> {this.state.radioSet.map((data, key) => { return ( <View key={key}> {this.state.checkedSet == key ? <TouchableOpacity style={styles.btn}> <Image style={styles.imgBtn} source={Img.selected}/> <Text>{data}</Text> </TouchableOpacity> : <TouchableOpacity onPress={()=>{this.setState({checkedSet: key})}} style={styles.btn}> <Image style={styles.imgBtn} source={Img.noSelected} /> <Text>{data}</Text> </TouchableOpacity> } </View> ) })} </View> {/**************************************************************************************** */} <Text style={styles.textConfig}> Difficulté {br}</Text> <View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'stretch'}}> {this.state.radioDifficulty.map((data, key) => { return ( <View key={key}> {this.state.checkedDifficulty == key ? <TouchableOpacity style={styles.btn}> <Image style={styles.imgBtn} source={Img.selected}/> <Text>{data}</Text> </TouchableOpacity> : <TouchableOpacity onPress={()=>{this.setState({checkedDifficulty: key})}} style={styles.btn}> <Image style={styles.imgBtn} source={Img.noSelected} /> <Text>{data}</Text> </TouchableOpacity> } </View> ) })} </View> </View> </ImageBackground> </View> ); } } const styles = StyleSheet.create({ textConfig: { fontWeight: 'bold', fontSize: 18 }, imageBackground: { flex: 4, width: '100%', height: '100%', }, btn : { width: 30, height: 30, marginLeft: 15, marginRight: 15, }, imgBtn : { width: 20, height: 20, }, view: { flex: 1, backgroundColor: '#1abc9c', }, header: { flex: 1, alignItems: 'center', flexDirection: 'column', justifyContent: 'center', }, title: { fontSize: 25, color: 'black', marginTop: 16, fontWeight: 'bold', }, content: { flex: 2, }, button: { marginBottom: 10, }, });<file_sep># HOW TO WORKING PARSE SERVER ? 1. using heroku 2. fork parse-exemple 3. change config for mongoDB cloud instance cluster 4. deploy on heroku 5. visit : https://shifumi-game-akarah.herokuapp.com/parse/function/hello<file_sep>import React, { Component } from 'react'; import { View, StyleSheet } from 'react-native'; export default class CircleScore extends Component { constructor(props) { super(props); } render() { let { colorSet1, colorSet2, colorSet3 } = this.props; return ( <View> <View style={styles.AroundScoreContainer}> <View style={[ styles.AroundScore,{ backgroundColor: colorSet1 }]} ></View> <View style={[ styles.AroundScore,{ backgroundColor: colorSet2 }]} ></View> <View style={[ styles.AroundScore,{ backgroundColor: colorSet3 }]} ></View> </View> </View> ); } } const styles = StyleSheet.create({ view: { flex: 0, backgroundColor: '#1abc9c', }, AroundScore:{ width: 90, height: 30, //borderRadius: 150/2, justifyContent: 'center', backgroundColor: 'rgba(40,40,70,1)', marginRight: 5, marginLeft: 5, borderWidth: 0, //borderColor: 'rgba(255,255,255,1)', borderColor: 'rgba(70,70,70,1)', }, AroundScoreContainer:{ flex: 0, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'stretch', marginTop: 5, } });<file_sep>import Parse from 'parse'; class Database { // use for get an object in database by ID get = async (className, id) => { let Object = Parse.Object.extend(className, null, null); let query = new Parse.Query(Object); return query.get(id) .then((obj) => { //console.log('database get :' + obj) return obj; }, (error) => { //console.log('database get :' + error.message); return null; }); } // use for listening a row in database listen = async (className, id, onUpdate) => { let query = new Parse.Query(className); query.equalTo("objectId", id); let subscription = await query.subscribe(); subscription.on('update', onUpdate); //subscription.on('update', function (message) {console.log("database updated : ", message); }); return subscription; } } const db = new Database(); export default db; <file_sep>const Img = { feuille: require('./feuille.png'), ciseau: require('./ciseau.png'), pierre : require('./pierre.png'), background : require('./Background.png'), dosCarte : require('./dosCarte.png'), noSelected : require('./noSelected.png'), selected : require('./selected.png'), icon : require('./icon.png'), bois : require('./textureBois.jpg'), carteBois : require('./carteBois.png'), } export default Img;<file_sep>import React, { PropTypes, Component } from 'react'; import { View, Text, Button, Alert, StyleSheet , Image, TouchableOpacity, ImageBackground} from 'react-native'; import { NavigationContainer, useRoute } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import Img from '../assets/images/_image'; import CircleScore from './Layout/CircleScore'; import Card from './Layout/Card'; import Buttons from './Layout/Buttons'; import '../stores/GameController'; import '../stores/UserController'; import 'localstorage-polyfill'; import Parse from 'parse'; import db from '../utils/database'; const br = `\n`; export default class MultiPlayer extends Component { constructor(props) { super(props); this.state = { gameFound : 0, //Replace this to 0 for search Player View maxSet : 3, PlayerUserChoice: '', Player2Choice: '', colorSet1: 'rgb(165,165,165)', colorSet2: 'rgb(165,165,165)', colorSet3: 'rgb(165,165,165)', visibilityEnemyCard : 0, visibilityUserCard : 0, visibilityNextSetButton : 0, cardToDisplayUser : '', cardToDisplayEnemy : '', pointPlayer2 : 0, pointUser : 0, player2Hasplayed : 1, enemyCurrentChoice : null, userCurrentChoice : null, choicesIsFinished : 0, visibilityCards : 1, textSet : 'Manche en cours', timeoutSearchGame : 45 }; this.idGame = null; this.pointPlayer2 = 0; this.pointUser = 0; this.currentSet = 1; this.result = '0'; this.idUser = Math.floor(Math.random() * Math.floor(15000)).toString(); this.placePlayerInDatabase= null; //this.timeoutForSearchGame(); } async componentWillUnmount(){ game = await db.get('GameInstance', this.idGame ); game.destroy().then((object) => { /*console.log('Clean Database ( ComponentWillUnmount ) ');*/ }, (error) => {/*console.log(error.message); */ }); // clean interval clearInterval(this.clockCall); } componentDidMount(){ //Search Other Game this.searchOtherPlayerAndInitializeGame(); //Set interval for maximum time of search game this.clockCall = setInterval(() => { this.setState((prevstate) => ({ timeoutSearchGame : prevstate.timeoutSearchGame-1 })); }, 1000); } // SearchGame // create Game // listen database searchOtherPlayerAndInitializeGame = async () => { this.idGame = await searchGameInstanceWithEmptyPlayer2(); // join a existing game if( this.idGame != null ){ //console.log('Game found : id = ' + this.idGame); await subscribeInAGame('player2',this.idGame, this.idUser) // joiner this.setState({ gameFound : 1 }); clearInterval(this.clockCall); this.placePlayerInDatabase = '2'; } // if game is not found, create game instance and wait a player2 else{ await createGameInstance(this.idUser); this.idGame = localStorage.getItem("gameId"); //console.log('Game was created : ' + this.idGame); //this.timeoutForSearchGame(); // host this.placePlayerInDatabase = '1'; } db.listen("GameInstance", this.idGame, (gameReturn) => { if (/*gameReturn.attributes.player1 != '0' && gameReturn.attributes.player2 != '0' || */ this.state.gameFound != 1){ this.setState({ gameFound : 1 }); clearInterval(this.clockCall); } else { // in game if (gameReturn.attributes.P1CurrentChoice != null && gameReturn.attributes.P2CurrentChoice != null){ this.majView(gameReturn); } } }).then((success) => { /*console.log("subscribe status ")*/ }, (error) => { console.log(error.message)}); } // Refresh all states in a game // executed in a listen function majView = (gameReturn) => { let { visibilityUserCard, visibilityEnemyCard, cardToDisplayEnemy,textSet, cardToDisplayUser, visibilityNextSetButton, colorSet1, colorSet2, colorSet3, gameFound, enemyCurrentChoice, userCurrentChoice } = this.state; if(this.placePlayerInDatabase == '1'){ enemyCurrentChoice = gameReturn.attributes.P2CurrentChoice; userCurrentChoice = gameReturn.attributes.P1CurrentChoice; cardToDisplayEnemy = gameReturn.attributes.P2CurrentChoice; cardToDisplayUser = gameReturn.attributes.P1CurrentChoice; } else{ enemyCurrentChoice = gameReturn.attributes.P1CurrentChoice; userCurrentChoice = gameReturn.attributes.P2CurrentChoice; cardToDisplayEnemy = gameReturn.attributes.P1CurrentChoice; cardToDisplayUser = gameReturn.attributes.P2CurrentChoice; } visibilityEnemyCard = 0; visibilityUserCard = 1; visibilityNextSetButton = 0; textSet = 'Manche en cours'; this.setState({ enemyCurrentChoice : enemyCurrentChoice, userCurrentChoice : userCurrentChoice, cardToDisplayEnemy : cardToDisplayEnemy, cardToDisplayUser : cardToDisplayUser, visibilityEnemyCard : visibilityEnemyCard, visibilityUserCard : visibilityUserCard, visibilityNextSetButton : visibilityNextSetButton, textSet : textSet , }); // IF all players has played if(enemyCurrentChoice != '0' && userCurrentChoice != '0' ){ this.MakeSet(); this.setState({ visibilityCards : 0, visibilityNextSetButton : 1, visibilityEnemyCard : 1, visibilityUserCard : 1, textSet : 'Manche terminée', }); this.redirectGame(); } return ; } selectCard = async (userChoice) => { var query = new Parse.Query('GameInstance'); query.equalTo("id", this.idGame); game = await db.get('GameInstance', this.idGame ); if(this.placePlayerInDatabase == '1'){ game.set('P1CurrentChoice', userChoice); await game.save(); } else if(this.placePlayerInDatabase == '2'){ game.set('P2CurrentChoice', userChoice); await game.save(); } } MakeSet = () => { let result = null; this.result = '0'; if (this.state.enemyCurrentChoice == this.state.userCurrentChoice){ result = "null"; this.result = 'null'; } else if (this.state.enemyCurrentChoice == "pierre" && this.state.userCurrentChoice == "feuille"){ result = "Gagné"; } else if (this.state.enemyCurrentChoice == "pierre" && this.state.userCurrentChoice == "ciseau"){ result = "Perdu"; } else if (this.state.enemyCurrentChoice == "feuille" && this.state.userCurrentChoice == "ciseau"){ result = "Gagné"; } else if (this.state.enemyCurrentChoice == "feuille" && this.state.userCurrentChoice == "pierre"){ result = "Perdu"; } else if (this.state.enemyCurrentChoice == "ciseau" && this.state.userCurrentChoice == "pierre"){ result = "Gagné"; } else if (this.state.enemyCurrentChoice == "ciseau" && this.state.userCurrentChoice == "feuille"){ result = "Perdu"; } this.updateGame(result) ; } updateGame = (result) => { this.setState({ visibilityUserCard: 1, visibilityEnemyCard: 1, }); this.result = "0"; if (result == "Gagné"){ if (this.currentSet == 1) { this.setState({colorSet1 : 'rgb(106,206,0)'}); this.pointUser = this.pointUser + 1; }; if (this.currentSet == 2) { this.setState({colorSet2 : 'rgb(106,206,0)'}); this.pointUser = this.pointUser + 1; }; if (this.currentSet == 3) { this.setState({colorSet3 : 'rgb(106,206,0)'}); this.pointUser = this.pointUser + 1; }; } else if (result == "Perdu"){ if (this.currentSet == 1) { this.setState({colorSet1 : 'red'}); this.pointPlayer2 = this.pointPlayer2 + 1; }; if (this.currentSet == 2) { this.setState({colorSet2 : 'red'}); this.pointPlayer2 = this.pointPlayer2 + 1; }; if (this.currentSet == 3) { this.setState({colorSet3 : 'red'}); this.pointPlayer2 = this.pointPlayer2 + 1; }; } this.setState({ visibilityUserCard : 1, }); } nextSet = async () => { if(this.state.enemyCurrentChoice == this.state.userCurrentChoice){ this.result = "null" ; } if(this.result != "null"){ this.currentSet = this.currentSet + 1; } this.setState({ visibilityUserCard: 0, visibilityEnemyCard: 0, cardToDisplayUser: null, cardToDisplayEnemy: null, enemyCurrentChoice : null, userCurrentChoice : null, visibilityUserCard : 0, visibilityCards : 1, visibilityNextSetButton : 0, textSet : 'Manche en cours' , }); game = await db.get('GameInstance', this.idGame ); game.set('P2CurrentChoice', null); game.set('P1CurrentChoice', null); await game.save(); } redirectGame = () => { let navigation = this.props.navigation; if(this.placePlayerInDatabase == '1'){ if (this.currentSet >= 3 && this.pointPlayer2 >= 2 ){ setTimeout(function(){navigation.navigate('EndGame',{ result: ['Défaite'] })}, 700); } else if (this.currentSet >= 3 && this.pointUser >= 2){ setTimeout(function(){navigation.navigate('EndGame',{ result: ['Victoire'] })}, 700); } } else if(this.placePlayerInDatabase == '2'){ if (this.currentSet >= 3 && this.pointUser >= 2 ){ setTimeout(function(){navigation.navigate('EndGame',{ result: ['Victoire'] })}, 700); } else if (this.currentSet >= 3 && this.pointPlayer2 >= 2){ setTimeout(function(){navigation.navigate('EndGame',{ result: ['Défaite'] })}, 700); } } } render = () => { const { visibilityUserCard, visibilityEnemyCard, cardToDisplayEnemy, cardToDisplayUser, colorSet1, colorSet2, colorSet3, gameFound, textSet, visibilityNextSetButton, visibilityCards, timeoutSearchGame } = this.state; //this.timeoutForSearchGame(); if(gameFound == 0 && timeoutSearchGame > 0){ return( <View style={{flex:1}}> <ImageBackground source={Img.background} style={styles.imageBackground}> <View style={{flex:3, justifyContent: 'center', flexDirection: 'column', alignItems: 'center',}}> <Text style={styles.centerText}>Recherche d'adversaire</Text> </View> <View style={{flex:3, justifyContent: 'center', flexDirection: 'column', alignItems: 'center',}}> <Text style={[{}, styles.centerTextMin]}>Patientez...</Text> </View> <View style={{flex:4, justifyContent: 'center', flexDirection: 'column', alignItems: 'center',}}> <Text style={[{}, styles.centerTextTimeout]}> Temps restant : {timeoutSearchGame} secondes</Text> </View> </ImageBackground> </View> ) } else if (gameFound == 0 && timeoutSearchGame <= 0){ return( <View style={{flex:1}}> <ImageBackground source={Img.background} style={styles.imageBackground}> <View style={{flex:3, justifyContent: 'center', flexDirection: 'column', alignItems: 'center',}}> <Text style={styles.centerText}>Recherche d'adversaire terminé</Text> </View> <View style={{flex:4, justifyContent: 'center', flexDirection: 'column', alignItems: 'center',}}> <Text style={[{}, styles.centerTextTimeout]}> Malheureusement, nous ne trouvons pas de joueur, veuillez essayez plus tard </Text> </View> <View style={{flex:4, justifyContent: 'center', flexDirection: 'column', alignItems: 'center',}}> <Buttons buttonText="Menu" navigation={this.props.navigation} NameRenderView="Home" texture={Img.bois} /> </View> </ImageBackground> </View> ) } else if(gameFound == 1){ return ( <View style={styles.view}> <ImageBackground source={Img.background} style={styles.imageBackground}> <View style={[{flex:1 ,justifyContent:'center'}, styles.header]}> <View style={{flex:4}}> <Image source={Img.dosCarte} resizeMode="contain" style={styles.enemyCard}/> </View> <View style={[styles.containerEnemyCardPlayed, { opacity: visibilityEnemyCard, flex:4 }]}> <Image source={Img[cardToDisplayEnemy]} resizeMode="contain" style={styles.CardPlayedEnemy} /> </View> <View style={{flex:3 ,justifyContent:'center'}}> <Text style={styles.BattleText}>{textSet}</Text> <CircleScore colorSet1={colorSet1} colorSet2={colorSet2} colorSet3={colorSet3} /> </View> <View style={[styles.containerUserCardPlayed, { opacity: visibilityUserCard, flex:4 ,justifyContent:'center' } ]}> <Image source={Img[cardToDisplayUser]} resizeMode="contain" style={styles.CardPlayedUser} /> </View> <View style={[styles.nextSet, { flex:1 , opacity: visibilityNextSetButton} ]}> <TouchableOpacity onPress={() => this.nextSet()} > <Text> Passer a la manche suivante </Text> </TouchableOpacity> </View> <View style={{flex:1, justifyContent: 'center'}}> <Text style={styles.setText}> Coup n°{ this.currentSet } </Text> </View> <View style={{flex:5, justifyContent: 'center'}}> <View style={[styles.ContainerChoiceUserCards , {flex: 2, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'stretch', opacity: visibilityCards }]}> <Card onPress={() => this.selectCard("ciseau")} icon={Img.ciseau} texture={Img.carteBois} color="rgba(191,44,44,1)"/> <Card onPress={() => this.selectCard("feuille")} icon={Img.feuille} texture={Img.carteBois} color="rgba(242,203,5,1)"/> <Card onPress={() => this.selectCard("pierre")} icon={Img.pierre} texture={Img.carteBois} color="rgba(74,140,91,1)"/> </View> </View> </View> </ImageBackground> </View> ); } } } const styles = StyleSheet.create({ centerTextTimeout :{ fontSize:15, color: 'rgb(240,240,240)', paddingLeft: 60, paddingRight: 60, }, ContainerChoiceUserCards:{ //marginBottom: 220, }, nextSet:{ backgroundColor: 'yellow', padding: 8, fontSize:9, margin: 6, alignItems: 'center', }, centerTextMin:{ marginTop: 30, //justifyContent: 'center', fontSize: 20, //marginLeft:150, fontWeight: 'bold', color:'white', }, centerText:{ marginTop: 240, //justifyContent: 'center', fontSize: 25, //marginLeft:50, fontWeight: 'bold', color:'white', }, view: { flex: 1, backgroundColor: '#1abc9c', }, square : { marginBottom:2, marginTop:2, padding: 2, }, imageBackground: { flex: 4, width: '100%', height: '100%', }, header: { flex: 1, justifyContent: 'center', alignItems: 'center', marginBottom: 0, }, boardContainer: { flex: 4, }, scoreContainer: { flex: 2, }, scoreColorTwo: { backgroundColor: '#34495e', }, scoreColorOne: { backgroundColor: '#9b59b6', }, container1: { width: 105, height: 140, backgroundColor: 'rgba(191,44,44,1)', borderRadius: 15, justifyContent: 'center', alignItems: 'center', }, container2: { width: 105, height: 140, backgroundColor: 'rgba(242,203,5,1)', borderRadius: 15, justifyContent: 'center', alignItems: 'center', }, container3: { width: 105, height: 140, backgroundColor: 'rgba(74,140,91,1)', borderRadius: 15, justifyContent: 'center', alignItems: 'center', }, rect: { width: 105, height: 140, borderRadius: 10, borderWidth: 5, borderColor: 'rgba(255,255,255,1)', justifyContent: 'center', alignItems: 'center', marginTop:1, }, image1: { width: 70, height: 70, }, enemyCard: { width: 1500, height: 300, }, CardPlayedUser: { width: 90, height: 60, //marginTop: 150, //marginBottom: 0, }, CardPlayedEnemy: { width: 90, height: 60, //marginTop: -110, //marginBottom: 60, }, containerEnemyCardPlayed: { transform: [ { rotate: "90deg" }, //{ translateX: -130 }, { translateY: 45 } ], }, containerUserCardPlayed: { transform: [ { rotate: "-90deg" }, //{ translateX: 0 }, //{ translateY: -75 } ], }, BattleText: { fontSize: 17, marginTop: 0, fontWeight: "bold", color: 'white', }, setText:{ fontSize: 15, marginBottom:15, color: 'rgb(50,50,50)', } });<file_sep> // In a node.js environment //const Parse = require('parse/node'); // ES6 Minimized <file_sep>import * as React from 'react'; import 'react-native-gesture-handler'; import 'localstorage-polyfill'; import Parse from 'parse'; createUserObject = async () => { const User = Parse.Object.extend("User"); const user = new User(); user.set("player1", "user1"); user.set("player2", "user2"); user.save() .then(function(user){ //return user.json(); }) .then(function(err){ }) }<file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, Text, Button, StyleSheet, TouchableOpacity, ImageBackground } from 'react-native'; import Img from '../assets/images/_image'; import Buttons from './Layout/Buttons'; import 'react-native-gesture-handler'; import Parse from 'parse'; const br = `\n`; // TODO: import score from database export default class EndGame extends Component { constructor(props) { super(props); } render() { let { result } = this.props; const { navigation} = this.props; return ( <View style={styles.view}> <ImageBackground source={Img.background} style={styles.imageBackground}> <View style={styles.header}> <View style={styles.TextContainer} > <Text style={styles.TextBasic}>Partie terminée</Text><Text style={styles.textResult}>{result}</Text> </View> </View> <View style={styles.content}> <Buttons buttonText="Retour Menu" navigation={navigation} NameRenderView="Home" texture={Img.bois} /> </View> </ImageBackground> </View> ); } } const styles = StyleSheet.create({ view: { flex: 1, backgroundColor: '#1abc9c', }, imageBackground: { flex: 4, width: '100%', height: '100%', }, content: { flex: 2, alignItems: 'center', marginTop: 80, }, header: { flex: 1, alignItems: 'center', flexDirection: 'column', justifyContent: 'center', }, title: { fontSize: 30, color: '#ecf0f1', marginTop: 16, }, button: { marginBottom: 10, }, MenuButtonContainer : { alignItems: 'center', width: 210, backgroundColor: 'grey', padding: 30, marginTop:100, borderWidth: 4, borderColor: "#774D3B", }, MenuButtonText:{ color: 'white', fontSize : 20, }, TextBasic:{ marginTop:250, color:'white', fontSize:25, }, textResult:{ color:'white', fontSize:50, fontWeight:'bold', } }); <file_sep># Shifumi mobile app project The shi fu mi application is a mobile application. The application consists of a navigation menu, as well as single player gameplay ## Technology - React Native - Expo - Parse server ( for back end ) ## Use this project ```bash $ git clone https://github.com/DurandSacha/shifumi-mobile-project ``` ```bash $ npm install ``` ```bash $ expo start ``` ## Project using back end parse server from other repository - Parse server deployed with heroku on domain - parse server using mongoDB atlas you can check the parse server here : ```bash https://shifumi-game-akarah.herokuapp.com/parse/classes/User ``` <file_sep>import * as React from 'react'; import { View, Text, StyleSheet, ImageBackground, Image, AsyncStorage } from 'react-native'; import { NavigationContainer, useRoute } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import Game from "./components/Game"; import MultiPlayer from "./components/MultiPlayer"; import EndGame from "./components/EndGame"; import Information from "./components/Information"; import Configuration from "./components/Configuration"; import 'react-native-gesture-handler'; import Img from './assets/images/_image'; import Buttons from './components/Layout/Buttons'; import 'localstorage-polyfill'; //import AsyncStorage from '@react-native-async-storage/async-storage'; // old: '@react-native-async-storage/async-storage'; // @react-native-community/async-storage // use : react-native link @react-native-async-storage/async-storage import Parse from 'parse'; /* Back end (Parse Server) is available and deployed with : https://github.com/DurandSacha/parse-server-example at https://shifumi-game-akarah.herokuapp.com/parse/function/hello - Heroku app with connected github - MongoDB is configured with : https://cloud.mongodb.com/v2 */ Parse.setAsyncStorage(AsyncStorage); Parse.initialize("0123456789", "0123456789", "0123456789"); Parse.serverURL = 'http://shifumi-game-akarah.herokuapp.com/parse/'; Parse.liveQueryServerURL = 'ws://shifumi-game-akarah.herokuapp.com/parse/'; // This file init the projet, and displaying the home menu with navigation function HomeScreen({ navigation }) { if (localStorage.getItem('terminated') < 1 || localStorage.getItem('terminated') == null){ localStorage.setItem('terminated', 0); } let terminated = localStorage.getItem('terminated'); return ( <View style={styles.view}> <ImageBackground source={Img.background} style={styles.imageBackground}> <View style={styles.header}> <Image style={styles.icon} source={Img.icon} /> </View> <View style={styles.content}> <Buttons buttonText="Jeu Solo" navigation={navigation} NameRenderView="Game" texture={Img.bois} /> <Buttons buttonText="Jeu multijoueur" navigation={navigation} NameRenderView="MultiGame" texture={Img.bois} /> <Buttons buttonText="Information" navigation={navigation} NameRenderView="Information" texture={Img.bois} /> {/*<Buttons buttonText="Configuration" navigation={navigation} NameRenderView="Configuration" texture={Img.bois} />*/} </View> </ImageBackground> </View> ); } /* Function for routing */ function ConfigurationScreen({ navigation }) { return ( <Configuration navigation={navigation}/> ); } /* Function for routing */ function GameScreen({ navigation }) { return ( <Game navigation={navigation}/> ); } /* Function for routing */ function MultiGameScreen({ navigation }) { return ( <MultiPlayer navigation={navigation}/> ); } /* Function for routing */ function EndGameScreen({ navigation }) { const route = useRoute(); const { result } = route.params; return ( <EndGame navigation={navigation} result={result}/> ); } /* Function for routing */ function InformationScreen({ navigation }) { const route = useRoute(); return ( <Information navigation={navigation}/> ); } const Stack = createStackNavigator(); /* routing system */ function App() { return ( <NavigationContainer> <Stack.Navigator headerMode="none" initialRouteName="Home"> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Information" component={InformationScreen} /> <Stack.Screen name="Configuration" component={ConfigurationScreen} /> <Stack.Screen name="Game" component={GameScreen} /> <Stack.Screen name="MultiGame" component={MultiGameScreen} /> <Stack.Screen name="EndGame" component={EndGameScreen} /> </Stack.Navigator> </NavigationContainer> ); } const styles = StyleSheet.create({ imageBackground: { flex: 4, width: '100%', height: '100%', }, icon: { width: 140, height: 140, marginTop:170, }, MenuButtonContainer : { alignItems: 'center', width: 210, backgroundColor: 'grey', padding: 30, marginTop: 20, borderWidth: 4, borderColor: "#774D3B", }, MenuButtonText:{ color: 'white', fontSize : 20, fontFamily: "Cochin", }, view: { flex: 1, backgroundColor: '#1abc9c', alignItems: 'center', }, header: { flex: 1, alignItems: 'center', flexDirection: 'column', justifyContent: 'center', }, title: { fontSize: 60, color: '#774D3B', marginTop: 150, fontWeight:'bold', }, content: { flex: 2, alignItems: 'center', marginTop: 80, }, button: { marginBottom: 15, }, }); // DEMO: //.then(((subscription)=>{console.log(subscription)}, (error)=>{console.log(error.message)}) export default App;<file_sep>import React, { Component } from 'react'; import { View, Text, StyleSheet , Image, ImageBackground } from 'react-native'; import 'react-native-gesture-handler'; import Img from '../assets/images/_image'; import CircleScore from './Layout/CircleScore'; import Card from './Layout/Card'; import CardPlayed from './Layout/CardPlayed'; import {widthPercentageToDP, heightPercentageToDP } from 'react-native-responsive-screen'; import 'localstorage-polyfill'; const br = `\n`; export default class Game extends Component { constructor(props) { super(props); this.state = { maxSet : 3, MachineChoice: '', colorSet1: 'rgb(165,165,165)', colorSet2: 'rgb(165,165,165)', colorSet3: 'rgb(165,165,165)', visibilityEnemyCard : 0, visibilityUserCard : 0, cardToDisplayUser : 'feuille', cardToDisplayEnemy : 'feuille', pointMachine : 0, pointUser : 0, }; this.pointMachine = 0; this.pointUser = 0; this.currentSet = 0; } makeMachineChoice = () => { const choice = ['feuille', 'ciseau', 'pierre'] const random = Math.floor(Math.random() * choice.length); this.state = { MachineChoice: choice[random] }; return choice[random]; } updateGame = (result, userChoice, MachineChoice) => { this.setState({ visibilityUserCard: 1, visibilityEnemyCard: 1, cardToDisplayUser: userChoice, cardToDisplayEnemy: MachineChoice, }); let currentSet = this.currentSet; let i = 0 while (i <= 3) { i = i + 1; if (currentSet == i){ if(result == "null"){} else if (result == "Gagné"){ this.pointUser = this.pointUser + 1 ; if (currentSet == 1) { this.setState({colorSet1 : 'rgb(106,206,0)'}) }; if (currentSet == 2) { this.setState({colorSet2 : 'rgb(106,206,0)'}) }; if (currentSet == 3) { this.setState({colorSet3 : 'rgb(106,206,0)'}) }; } else{ if (currentSet == 1) { this.setState({colorSet1 : 'red'}) }; if (currentSet == 2) { this.setState({colorSet2 : 'red'}) }; if (currentSet == 3) { this.setState({colorSet3 : 'red'}) }; this.pointMachine = this.pointMachine + 1 ; } } } } MakeSet = (userChoice) => { let MachineChoice = this.makeMachineChoice() ; if (MachineChoice == userChoice){ var result = "null"; this.currentSet = this.currentSet -1;} else if (MachineChoice == "pierre" && userChoice == "feuille"){var result = "Gagné";} else if (MachineChoice == "pierre" && userChoice == "ciseau"){var result = "Perdu";} else if (MachineChoice == "feuille" && userChoice == "ciseau"){var result = "Gagné";} else if (MachineChoice == "feuille" && userChoice == "pierre"){var result = "Perdu";} else if (MachineChoice == "ciseau" && userChoice == "pierre"){var result = "Gagné";} else if (MachineChoice == "ciseau" && userChoice == "feuille"){var result = "Perdu";} if (this.currentSet <= 3){ this.currentSet = this.currentSet + 1; } this.updateGame(result,userChoice,MachineChoice); this.forceUpdate(); this.redirectGame(); return ; } redirectGame = () => { let navigation = this.props.navigation; if (this.currentSet >= 3 && this.pointMachine >= 2 ){ setTimeout(function(){ let terminated = localStorage.getItem('terminated'); localStorage.setItem('terminated', parseInt(terminated) + parseInt(1) ); navigation.navigate('EndGame',{ result: ['Défaite'] }); }, 700); } else if (this.currentSet >= 3 && this.pointUser >= 2){ setTimeout(function(){ let terminated = localStorage.getItem('terminated'); localStorage.setItem('terminated', parseInt(terminated) + parseInt(1) ); navigation.navigate('EndGame',{ result: ['Victoire'] }); }, 700); } } render =() => { const { visibilityUserCard, visibilityEnemyCard, cardToDisplayEnemy, cardToDisplayUser, colorSet1, colorSet2, colorSet3 } = this.state; return ( <View style={styles.view}> <ImageBackground source={Img.background} style={styles.imageBackground}> <View style={[{flex:1 ,justifyContent:'center'}, styles.header]}> <View style={{flex:4}}> <Image source={Img.dosCarte} resizeMode="contain" style={styles.enemyCard}/> </View> <View style={[styles.containerEnemyCardPlayed, { flex:4, opacity: visibilityEnemyCard }]}> <CardPlayed icon={Img[cardToDisplayEnemy]} texture={Img.carteBois} ></CardPlayed> </View> <View style={{flex:3 ,justifyContent:'center'}}> <Text style={styles.BattleText}>Choisissez une carte</Text> <CircleScore colorSet1={colorSet1} colorSet2={colorSet2} colorSet3={colorSet3} /> </View> <View style={[styles.containerUserCardPlayed, { flex:4 ,justifyContent:'center', opacity: visibilityUserCard } ]}> <CardPlayed icon={Img[cardToDisplayUser]} texture={Img.carteBois} ></CardPlayed> </View> <View style={{flex:1, justifyContent: 'center'}}> <Text style={styles.setText}> Coup n°{ this.currentSet } </Text> </View> <View style={{flex:5, justifyContent: 'center'}}> <View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'stretch'}}> <Card onPress={() => this.MakeSet("ciseau")} icon={Img.ciseau} texture={Img.carteBois} color="rgba(191,44,44,1)"/> <Card onPress={() => this.MakeSet("feuille")} icon={Img.feuille} texture={Img.carteBois} color="rgba(242,203,5,1)"/> <Card onPress={() => this.MakeSet("pierre")} icon={Img.pierre} texture={Img.carteBois} color="rgba(74,140,91,1)"/> </View> </View> </View> </ImageBackground> </View> ); } } const styles = StyleSheet.create({ view: { flex: 1, backgroundColor: '#1abc9c', }, square : { marginBottom:2, //marginTop:2, //padding: 2, }, imageBackground: { flex: 4, width: widthPercentageToDP('100%'), height : heightPercentageToDP('100%'), }, header: { flex: 1, justifyContent: 'center', alignItems: 'center', marginBottom: 0, }, boardContainer: { flex: 4, }, scoreContainer: { flex: 2, }, scoreColorTwo: { backgroundColor: '#34495e', }, scoreColorOne: { backgroundColor: '#9b59b6', }, container1: { width: 105, height: 140, backgroundColor: 'rgba(191,44,44,1)', borderRadius: 15, justifyContent: 'center', alignItems: 'center', }, container2: { width: 105, height: 140, backgroundColor: 'rgba(242,203,5,1)', borderRadius: 15, justifyContent: 'center', alignItems: 'center', }, container3: { width: 105, height: 140, backgroundColor: 'rgba(74,140,91,1)', borderRadius: 15, justifyContent: 'center', alignItems: 'center', }, rect: { width: 105, height: 140, borderRadius: 0, borderWidth: 2, borderColor: 'rgba(255,255,255,1)', justifyContent: 'center', alignItems: 'center', marginTop:1, }, image1: { width: 70, height: 70, }, enemyCard: { width: 1400, height: 280, }, CardPlayedUser: { width: 90, height: 60, //marginTop: 70, //marginBottom: 10, }, CardPlayedEnemy: { width: 80, height: 55, //marginTop: -0, //marginBottom: 20, }, containerEnemyCardPlayed: { transform: [ { rotate: "90deg" }, { translateX: -90 }, { translateY: -1 } ], }, containerUserCardPlayed: { transform: [ { rotate: "-90deg" }, { translateX: 0 }, { translateY: 0 } ], }, BattleText: { fontSize: 17, //marginTop: -45, fontWeight: "bold", marginLeft: 75, color:'white', }, setText:{ fontSize: 15, marginBottom: 10, color:'white', } });<file_sep>import React, { Component } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, ImageBackground } from 'react-native'; export default class Buttons extends Component { constructor(props) { super(props); } render() { let {navigation, buttonText, NameRenderView, texture} = this.props return ( <ImageBackground style={styles.backgroundImageBois} source={texture}> <TouchableOpacity style={styles.MenuButtonContainer} onPress={() => navigation.push(NameRenderView)} color="#138a72"> <Text style={styles.MenuButtonText} >{buttonText}</Text> </TouchableOpacity> </ImageBackground> ); } } const styles = StyleSheet.create({ backgroundImageBois :{ marginBottom:15, }, MenuButtonText:{ color: 'white', fontWeight: 'bold', fontSize : 20, }, button: { //marginBottom: 15, }, MenuButtonContainer : { alignItems: 'center', width: 210, //backgroundColor: 'grey', padding: 30, //marginTop: 20, //borderWidth: 4, //borderColor: "#774D3B", overflow: 'hidden', }, });<file_sep>import 'react-native-gesture-handler'; import 'localstorage-polyfill'; import Parse from 'parse'; import db from '../utils/database'; import 'localstorage-polyfill'; createGameInstance = async (namePlayer1) => { const GameInstance = Parse.Object.extend("GameInstance"); const game = new GameInstance(); game.set("player1", namePlayer1); game.set("player2", '0'); game.set("P1CurrentChoice", '0'); game.set("P2CurrentChoice", '0'); game.set("result", null); await game.save() .then(function(game){ localStorage.setItem("gameId", game.id); return game.id; }, (error) => { console.log(error.message); return null; }); } searchGameInstanceWithEmptyPlayer2 = async () => { // query instance game where player2 == null var query = new Parse.Query('GameInstance'); query.equalTo("player2", '0'); games = await query.find(); if(games.length == 0) { return null; } else{ return games[0]['id']; } } subscribeInAGame = async (place,instanceId,name) => { var query = new Parse.Query('GameInstance'); query.equalTo("id", instanceId); game = await db.get('GameInstance', instanceId ); game.set(place, name); await game.save(); return; } /* incrementPointPlayer1 = async (instanceId) => { var query = new Parse.Query('GameInstance'); query.equalTo("id", instanceId); game = await db.get('GameInstance', instanceId ); let point = parseInt( game.attributes.P1Point ) + 1; game.set('P1Point', point.toString() ); // place : P1Point console.log('P1 point ( increment function ) : ' + game.attributes.P1Point); game.save(); } incrementPointPlayer2 = async (instanceId) => { var query = new Parse.Query('GameInstance'); query.equalTo("id", instanceId); game = await db.get('GameInstance', instanceId ); let point = parseInt( game.attributes.P2Point ) + 1; game.set('P2Point', point.toString() ); // place : P1Point console.log('P2 point (increment function) : ' + game.attributes.P2Point); game.save(); } */<file_sep>import React, { Component } from 'react'; import { View, StyleSheet, Image, ImageBackground} from 'react-native'; import { TouchableOpacity } from 'react-native-gesture-handler'; export default class Card extends Component { constructor(props) { super(props); } render() { const { icon, color, onPress, texture } = this.props; return ( <View style={styles.ViewCard}> <ImageBackground style={styles.backgroundImageBois} source={texture}> <TouchableOpacity onPress={onPress} style={[styles.container /*, {backgroundColor : color } */]}> <View style={styles.rect}> <Image source={icon} resizeMode="contain" style={[styles.image]} /> </View> </TouchableOpacity> </ImageBackground> </View> ); } } const styles = StyleSheet.create({ ViewCard: { marginBottom:50, }, backgroundImageBois :{ marginBottom:25, //borderRadius: 100, width: 85, height: 108, marginRight: 5, marginLeft: 5, resizeMode: "cover", justifyContent: "center", }, view: { flex: 1, }, container: { width: 90, height: 110, //backgroundColor: 'rgba(191,44,44,1)', borderRadius: 40, justifyContent: 'center', alignItems: 'center', marginRight: 5, marginLeft: 5, }, rect: { width: 89, height: 108, borderRadius: 0, //borderWidth: 1, //borderColor: 'rgba(255,255,255,1)', borderColor: 'rgba(0,00,00,1)', justifyContent: 'center', alignItems: 'center', marginTop:1, marginLeft: -10, }, image: { width: 50, height: 50, borderRadius: 20, }, });<file_sep>#build APK cd android && ./gradlew assembleRelease
535030c8002c6d704323a49b9048ac04323849ec
[ "JavaScript", "Markdown" ]
18
JavaScript
DurandSacha/shifumi-mobile-project
cce5315f01a24ab0a5f57bbc0588620c236c0de0
b562877b65f9fd02b41bea8c69f6fc10b1d8ced2
refs/heads/master
<repo_name>pavniboosa/Immediate-intermediate-functions<file_sep>/README.md # Immediate-intermediate-functions<file_sep>/IIFE.js //IMMEDIATE INVOKED FUNCTION EXPRESSIONS /* function game(){ var score=Math.random()*10; console.log(score>=5); } var i=0; for(i=0;i<5;i++){ game(); } */ //this can be done in a better way because if the only motto is t //to hide the variable then declaring the entire function is //useless //iife looks like (function (){ var score=Math.random()*10; console.log(score>=5); })(); /*When ever we are writting function() this is a function declaration so if we are not giving the name it will throw error so we need to make the system believe that it is not a function declaration but a defination ,so that we do it by putting it in the brackets and will not be able to access the variable outside of the function */ //the below statment will throw error because we are accessing the //variable outside of the function //console.log(score); //passing the parameters //lets pass the good luck (function(goodluck){ var score=Math.random()*10; console.log(score>=5-goodluck); }) (5); //the above function will always be true because the score //will always be greater than 0 5-goodluck (5)
42c389ed4258946405d5d04f306c6adaa0dd46f0
[ "Markdown", "JavaScript" ]
2
Markdown
pavniboosa/Immediate-intermediate-functions
d9c4e1fa39ef2eadf76a2616c09dc6cf42c212d6
78be8e8495d7b3dbdc4f600733e99a20579f5644
refs/heads/master
<repo_name>francois-ulrich/portfolioSite<file_sep>/webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { mode: 'development', entry: './src/index.tsx', devServer: { contentBase: path.join(__dirname, 'dist'), compress: false, stats: "errors-only", }, module: { rules: [ // CSS { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.scss$/, loader: ExtractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader", "sass-loader"], }) }, // TSX { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ }, // IMAGES { test: /\.(png|jp(e*)g|svg|gif)$/, use: [{ loader: 'url-loader', options: { limit: 8000, // Convert images < 8kb to base64 strings name: './img/[hash]-[name].[ext]', } }] }, // FONTS { test: /\.(woff|woff2|eot|ttf|otf)$/, use: [{ loader: 'file-loader', options: { name: './fonts/[hash].[ext]', } }] }, ] }, output: { filename: 'app.bundle.js', path: path.resolve(__dirname, 'dist') }, resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: [".ts", ".tsx", ".js", ".json"] }, plugins: [ new HtmlWebpackPlugin({ hash: true, template: './src/index.html', filename: './index.html' //relative to root of the application }), new ExtractTextPlugin('index.css'), ], node: { fs: "empty" }, devServer: { historyApiFallback: true, } };
d1136a761df34c85ca97c5f5632fa9f2233a35f8
[ "JavaScript" ]
1
JavaScript
francois-ulrich/portfolioSite
8cac31c5a607ee4d3f219cbef53121ebda64b61b
d0054ac70ca632d94bb5df33c4c23ea20387bbde
refs/heads/master
<repo_name>SFord88/Intro-to-R--1<file_sep>/Module #3 Intro to Data Frame.R Name <- c("Jeb", "Donald", "Ted", "Marco", "Carly", "Hillary", "Bernie") ABC_political <- c(4, 62, 51, 21, 2, 14, 15) NCB_political <- c(12, 75, 43, 19, 1, 21, 19) results <- cbind(Name, ABC_political, NCB_political) #Create a matrix with columns Name, ABC_political, and NCB_political results results.df <- data.frame(Name, ABC_political, NCB_political) #Store results as a data frame results.df r <- rowMeans(results.df[,2:3]) #Gets the mean of both ABC and NCB for each candidate r r.df<-data.frame(Name,r) #Creates a data frame with Name as first column and r as second column r.df mean(as.matrix(results.df[,2:3])) #finds the mean across candidates and across networks <file_sep>/M12 Markdown.Rmd --- title: "M12 R Markdown" author: "<NAME>" date: "3/25/2019" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## Example of how to create an R Markdown document This is an example of how to use R Markdown to create an html document. For example, I can **MAKE TEXT BOLD** and use *italics* or ~~strikethrough~~ or even superscript^superscript^ If I want to include code, I can use "```{}" to include code ```{r my_data} a <- 5 b <- 10 c <- 15 d <- 20 my_data <- c(a,b,c,d) sum(my_data) mean(my_data) ``` ## Including Plots It is also possible to embed plots. For this, I used the made up data for "my_data" that I used above: ```{r data, echo=TRUE} plot(my_data) ``` The `echo = TRUE` parameter was used so that the R code would be printed. <file_sep>/M6 DoingMath2.R # Create matrices using given values A <- matrix(c(2,0,1,3), ncol=2) B <- matrix(c(5,2,4,-1), ncol=2) A+B #Find A+B A-B #Find A-B diag(c(4,1,2,3)) #Using the diag() function to build a matrix of size 4 with the following values in the diagonal 4,1,2,3 #Create the matrix shown in the assignment x <- diag(3,ncol=5,nrow=5) x[1,2:5] <- 1 x[2:5,1] <- 2 print(x)<file_sep>/Histogram assignment.R # Create variables to store the hospital data Freq <- c(0.6,0.3,0.4,0.4,0.2,0.6,0.3,0.4,0.9,0.2) Bloodp <- c(103,87,32,42,59,109,78,205,135,176) first <- c(1,1,1,1,0,0,0,0,NA,1) second <- c(0,0,1,1,0,0,1,1,1,1) finaldecision <- c(0,1,0,1,0,1,0,1,1,1) # Create a data frame containing all the variables hospitalstats <- data.frame(Freq, Bloodp, first, second, finaldecision) # Create a histogram using the two continuous variables hist(hospitalstats$Bloodp, main="Blood pressure readings", xlab="Blood pressure") <file_sep>/M9 Visualization.R # Import primate body and brain weights data set primates <- read.csv("https://vincentarelbundock.github.io/Rdatasets/csv/DAAG/primates.csv") View(primates) # Create values Brain_Weight <- primates$Brainwt Body_Weight <- primates$Bodywt Type <- primates$X # Create a basic scatter plot of brain and body weights plot(Brain_Weight, Body_Weight, xlab="Brain Weight in g", ylab="Body Weight in Kg", type = "p", col = 4) # Load ggplot2 library(ggplot2) # Create a plot using ggplot2 ggplot(primates, aes(x=Brain_Weight, y=Body_Weight)) + geom_point(size=2, shape=22, color= "dodgerblue") + geom_text(label=Type) # Load lattice library(lattice) # Create a plot using lattice xyplot(Body_Weight~Brain_Weight, data=primates, pch=Type, main= "Body and Brain Weights of Primates", ylab="Body Weight in kg", xlab="Brain Weight in g", col="red") <file_sep>/M5 Doing Math.R # Assign values A <- matrix(1:100, nrow=10) B <- matrix(1:1000, nrow=10) # Find determinants det(A) # returns [1]0 det(B) # returns an error ... 'x' must be a square matrix # Find inverse matrices solve(A) # returns error "system is exactly singular" solve(B) # returns error "must be square" <file_sep>/Boxplots Assignment.R # Enter the data Freq<-c(0.6,0.3,0.4,0.4,0.2,0.6,0.3,0.4,0.9,0.2) Bloodp<-c(103,87,32,42,59,109,78,205,135,176) first<-c(1,1,1,1,0,0,0,0,NA,1) second<-c(0,0,1,1,0,0,1,1,1,1) finaldecision<-c(0,1,0,1,0,1,0,1,1,1) # Create a data frame with all the variables hospitalstats<-data.frame(Freq,Bloodp,first,second,finaldecision) # Create a boxplot that looks at blood pressure as the continuous variable and the final decision as the categorical variable boxplot(Bloodp~finaldecision, main="Blood Pressure and Final Decision", ylab="Blood Pressure", xlab="Final Decision: No(0) or Yes(1)") # Bonus: Create a boxplot to examine whether the frequency of the visits predicted the final decision boxplot(Freq~finaldecision, main="Frequency and Final Decision", ylab="Frequency of visits", xlab="Final Decision: No(0) or Yes(1)") <file_sep>/M7 s3 s4.R state.x77 # load state.x77 data set cor(state.x77, y = NULL, use = "everything", method = c("pearson")) # try applying a generic function isS4(state.x77) #determine if S4 typeof(state.x77) # determine type class(state.x77) #determine class s4state<-asS4(state.x77) #assign S4 to the dataset isS4(s4state) #confirm that it is S4 <file_sep>/M8 Assignment.R #Click "import dataset" in the environment window of R Studio and import assignment 6 dataset #Assign dataset to an object A6DS <- Assignment6Dataset #install and load plyr install.packages("plyr") library(plyr) #Calculate average grade split by gender y <- ddply(A6DS, "Sex", transform, Grade.Average=mean(Grade)) #Check print(y) # Write to a file write.table(y,"Sorted_Average",sep=",") # Filter by letter I NewA6DS <- subset(A6DS, grepl("[Ii]", A6DS$Name)) #Check print(NewA6DS) #Write the "I" subset to a file write.table(NewA6DS, "ISubset", sep=",")
a27fd44829a4c5e2c35e9015011a57538260d248
[ "R", "RMarkdown" ]
9
R
SFord88/Intro-to-R--1
d9886b813067866e786d526ed081f6bcc2146a26
e9377602c9f17bf941e20cd7f2a2e4db05066130
refs/heads/master
<repo_name>adarwish01/OsInstagram<file_sep>/inst.py import requests import argparse import time import os def creds(): print("OsInstagram") print("---------------------\n") print("GitHub: https://github.com/haqgg\n\n") def parser(): parser = argparse.ArgumentParser(description="[+] Usage: ./inst.py -n nickname \n | NOTE: If you dont want to save photos or parse pages, set: -sp 0 -pp 0") parser.add_argument("-n", dest="nickname") parser.add_argument("-sp", dest="sp", type=int, default=1) parser.add_argument("-pp", dest="pp", type=int, default=1) options = parser.parse_args() return options def main(nickname, sp, pp): todos = requests.get("https://www.instagram.com/" + nickname + "?__a=1").json() if todos == {}: print("[-] Page Not Found") exit() if pp: try: os.mkdir(nickname) if todos["graphql"]["user"]["edge_owner_to_timeline_media"]["count"]: os.mkdir(nickname + "/posts/") except FileExistsError: print("[-] Folder already exists. Delete or rename it") exit() parse_page(todos, pp) if pp: print("\n[+] Got ", todos["graphql"]["user"]["edge_owner_to_timeline_media"]["count"], "post(s).") if not todos["graphql"]["user"]["is_private"]: print("[+] Downloading...") get_req_photos12(todos["graphql"]["user"], sp) else: print("[-] Account is private") print("[+] Done") def get_shortcodes(whatget, howmuchget, sp): for i in range(howmuchget): req = requests.get("https://instagram.com/p/" + whatget["edges"][i]["node"]["shortcode"] + "/?__a=1").json() parse_media(req["graphql"]["shortcode_media"], whatget["edges"][i]["node"]["shortcode"], sp) def get_req_morephotos(todos, idprofile, sp): if todos["edge_owner_to_timeline_media"]["page_info"]["has_next_page"]: data_for_get_req = 'https://www.instagram.com/graphql/query/?query_hash=f2405b236d85e8296cf30347c9f08c2a' \ '&variables=%7B%22id%22%3A%22' + idprofile + '%22%2C%22first%22%3A50%2C%22after%22%3A%22' \ + todos["edge_owner_to_timeline_media"]["page_info"]["end_cursor"].split("==")[0] + \ '%3D%3D%22%7D ' json_media = requests.get(data_for_get_req).json() get_shortcodes(json_media["data"]["user"]["edge_owner_to_timeline_media"], len(str(json_media["data"]["user"]).split("'shortcode': '")) - 1, sp) get_req_morephotos(json_media["data"]["user"], idprofile, sp) # getting links of the posts def get_req_photos12(todos, sp): if todos["edge_owner_to_timeline_media"]["count"] <= 12: get_shortcodes(todos["edge_owner_to_timeline_media"], todos["edge_owner_to_timeline_media"]["count"], sp) else: get_shortcodes(todos["edge_owner_to_timeline_media"], 12, sp) get_req_morephotos(todos, todos["id"], sp) # getting infos about account def parse_page(todos, sp): print("[+] Getting info about profile") follow_inst = str(todos["graphql"]["user"]["edge_follow"]["count"]) followed_by_inst = str(todos["graphql"]["user"]["edge_followed_by"]["count"]) content_inst = str(todos["graphql"]["user"]["edge_owner_to_timeline_media"]["count"]) biography = todos["graphql"]["user"]["biography"] name = todos["graphql"]["user"]["full_name"] username = todos["graphql"]["user"]["username"] verified = str(todos["graphql"]["user"]["is_verified"]) fb = str(todos["graphql"]["user"]["connected_fb_page"]) business = str(todos["graphql"]["user"]["is_business_account"]) try: link = "\nLink: " + todos["graphql"]["user"]["external_link"] except: link = '' info = "Name: " + name + "\nUsername: " + username + "\nBiography: " + biography + "\nVerified: " + verified + "\nFollow: " + follow_inst + "\nFollowed: " + \ followed_by_inst + "\nNumber of posts: " + content_inst + link + "\nBusiness account: " + business + \ '\nConnected to facebook: ' + fb if sp: file = open(username + "/info.txt", "w", encoding="utf-8") file.write(info) file.close() print(info) # functions for comments def get_req_com(shortcode, comments, page_info, list_of_comments, m, nickname): list_of_comments += str(comments) if page_info["has_next_page"]: end_cursor = page_info["end_cursor"] data_for_get_req = 'https://www.instagram.com/graphql/query/?query_hash=f0986789a5c5d17c2400faebf16efd0d' \ '&variables=%7B%22shortcode%22%3A%22' + shortcode + '%22%2C%22first%22%3A50' \ '%2C%22after%22%3A%22' + \ end_cursor.split("==")[0] + '%3D%3D%22%7D' json_media = requests.get(data_for_get_req).json() try: comments = json_media["data"]["shortcode_media"]["edge_media_to_comment"]["edges"] page_info = json_media["data"]["shortcode_media"]["edge_media_to_comment"]["page_info"] get_req_com(shortcode, comments, page_info, list_of_comments, m, nickname) except Exception as e: if json_media['message'] == "rate limited": print("[-] Rate limit. Please wait... (8 min.)") time.sleep(480) get_req_com(shortcode, comments, page_info, list_of_comments, m, nickname) else: print("[-] Error:", "\n", e, json_media) pass else: comments = parse_comm(list_of_comments) with open(nickname + "/posts/" + str(m) + "/comments.txt", "w", encoding="utf-8") as file: file.write(comments) with open(nickname + "/all_comments.txt", "a", encoding="utf-8") as file_all_comments: file_all_comments.write(comments) def parse_comm(list_of_comments): list_comments = '' num = str(list_of_comments).split("'node':") for i in range(1, len(num)): if str(num[i]).split("'edge_liked_by': {'count': ")[1].split("}")[0] == '0': likes = '' else: likes = "\t" + str(num[i]).split("'edge_liked_by': {'count': ")[1].split("}")[0] + " like(s)" username = str(num[i]).split("'username': '")[1].split("'},")[0] try: text = str(num[i]).split("'text': '")[1].split("'")[0] except: text = str(num[i]).split(''''text': "''')[1].split('"')[0] list_comments += username + ": '" + text + "'" + likes + "\n" return list_comments def comm(json_page, m): global comments, page_info try: comments = json_page["edge_media_to_parent_comment"]["edges"] page_info = json_page["edge_media_to_parent_comment"]["page_info"] except KeyError: comments = json_page["edge_media_to_comment"]["edges"] page_info = json_page["edge_media_to_comment"]["page_info"] except Exception != KeyError as e: print("\n\n", json_page, "\n[-] Error:", e) exit() get_req_com(json_page["shortcode"], comments, page_info, '', m, json_page["owner"]["username"]) # saving infos and photoes from account def parse_media(json_page, m, sp): global text, checker_for_comment view_count = '' os.mkdir(json_page["owner"]["username"] + "/posts/" + str(m)) captions = 'Caption(s) and Data: ' print("[+] Downloading post " + str(m)) if json_page["__typename"] == "GraphVideo": view_count = str("View count = " + str(json_page["video_view_count"])) out = open(json_page["owner"]["username"] + "/posts/" + str(m) + "/video.txt", "w") out.write(str("https://instagram.com/p/" + json_page["shortcode"])) out.close() if json_page["__typename"] == "GraphImage": photo = str(json_page["display_resources"][-1]["src"]) p = requests.get(photo) if sp: with open(json_page["owner"]["username"] + "/posts/" + str(m) + "/img" + str(m) + ".jpg", "wb") as out: out.write(p.content) captions = "\n" + json_page["accessibility_caption"] if json_page["__typename"] == "GraphSidecar": for i in range(len(json_page["edge_sidecar_to_children"]["edges"])): photoes = json_page["edge_sidecar_to_children"]["edges"][i]["node"]["display_resources"][-1]["src"] p = requests.get(photoes) if sp: with open(json_page["owner"]["username"] + "/posts/" + str(m) + "/img" + str(i) + ".jpg", "wb") as out: out.write(p.content) try: captions += "Photo №" + str(i) + "-" + str(json_page["edge_sidecar_to_children"]["edges"][i] ["node"]["accessibility_caption"]) + "\n" except: view_count = str("View count = " + str(json_page["edge_sidecar_to_children"]["edges"][i] ["node"]["video_view_count"])) with open(json_page["owner"]["username"] + "/posts/" + str(m) + "/video.txt", "w") as out: out.write(str("https://instagram.com/p/" + json_page["shortcode"])) likes = "Likes: " + str(json_page["edge_media_preview_like"]["count"]) + "\n" link = "Link - " + "instagram.com/p/" + json_page["shortcode"] + "\n" location = json_page["location"] if location: with open(json_page["owner"]["username"] + "/all_locations.txt", "a", encoding="utf-8") as file: file.write("post " + str(m) + "\n" + str(location) + "\n") else: location = '' if not json_page["edge_media_to_tagged_user"]["edges"]: tagged_user = '' else: print() tagged_user = '\nTagged user(s): ' for i in range(len(str(json_page["edge_media_to_tagged_user"]).split("node"))-1): tagged_user += "@" + json_page["edge_media_to_tagged_user"]["edges"][i]["node"]["user"]["username"] + \ " (" +json_page["edge_media_to_tagged_user"]["edges"][i]["node"]["user"]["full_name"] + ")\n" with open(json_page["owner"]["username"] + "/all_tagged.txt", "a", encoding="utf-8") as file: file.write(str("post " + str(m) + ":" + tagged_user + "\n")) file = open(json_page["owner"]["username"] + "/posts/" + str(m) + "/info.txt", "w", encoding="utf-8") try: text = "text: '" + str(json_page["edge_media_to_caption"]["edges"][0]["node"]["text"]) + "'\n" except: text = "text: None\n" all_information = str( text + likes + tagged_user + "\nLocation: " + str(location) + captions + view_count + "\n" + link) file.write(all_information) file.close() try: checker_for_comment = json_page["edge_media_to_parent_comment"]["count"] except: checker_for_comment = json_page["edge_media_to_comment"]["count"] if checker_for_comment != 0: comm(json_page, m) try: options = parser() pp = options.pp sp = options.sp nickname = options.nickname creds() main(nickname, sp, pp) except KeyboardInterrupt: print("\n\n[-] Detected Ctrl + C ... Program Existed") exit() except Exception as e: with open("log.txt", "w") as fileerror: fileerror.write(str(e)) print("\n\n[-] Some problem, check nickname/log.txt") exit() <file_sep>/README.md # OsInstagram OSINT tools for Instagram. Script works without API and inst profile # How to use? python3 inst.py -n *nickname* -sp 0/1 -pp 0/1 # Exmaple python3 inst.py -n zuck -sp 0 python3 inst.py -n zuck -pp 0 # Options |options|description|default|how to change| |-------|-----------|-------|-------------| |n|nickanme| - | *nickname* |sp|Save photos|1|0 |pp|Parse posts|1|0
4ea38afb0fa8b46f901f664abed08054249c343f
[ "Markdown", "Python" ]
2
Python
adarwish01/OsInstagram
037637c16d5930a9fab18fda7ec6b595c452c2b2
8f21334f21cac4353b6da565bcb7f65b82e8fc99
refs/heads/master
<file_sep>import axios from 'axios' import runAttempts from "../utils/runAttempts"; import pathExists from 'jrf-path-exists' import namesEqual from "../utils/namesEqual"; import processUrlQuery from "../utils/processUrlQuery"; import processFilm from "../utils/processFilm"; const config = require("../../config"); const API_KEY = config.tmdb.apiKey; const URL = config.tmdb.url; const ATTEMPTS = config.tmdb.attempts; export default class TMDB { constructor({url = URL, apiKey = API_KEY, attempts = ATTEMPTS, graylog, processId} = {}) { this.url = url; this.apiKey = apiKey; this.attempts = attempts; this.graylog = graylog; this.processId = processId; } async execAxios({url}) { const func = async () => { const res = await axios.get(url); if (res.status !== 200) { throw new Error(res.statusText); } return res; }; const res = await runAttempts({func, attempts: this.attempts}); return res.data; } async findMovie({query, year, lang = 'ru', adult = false, page = 1}) { let url = `${this.url}/search/movie?api_key=${this.apiKey}`; query = processUrlQuery({query}); url += `&year=${year}&language=${lang}&query=${encodeURIComponent(query)}&page=${page}&include_adult=${adult}`; if (query.includes('пончары')) { url = `https://api.themoviedb.org/3/search/movie?api_key=${this.apiKey}&query=%D0%BF%D0%BE%D0%BD%D1%87%D0%B0%D1%80%D1%8B`; } const res = await this.execAxios({url}); const films = pathExists(res, 'results', []); if (films.length === 1) return films[0]; for (const film of films) { const equal = namesEqual({nameA: film.title, nameB: query}); if (equal) return film; } } async getMovieById({id, lang = 'ru'}) { if (!id) return; const url = `${this.url}/movie/${id}?api_key=${this.apiKey}&language=${lang}`; const res = await this.execAxios({url}); return res; } async getInfo({name, year}) { if (!name) return; let film; for (let i = 0; i < 2; i++) { film = await this.findMovie({query: name, year}); if (film) { break; } year = year - 1; } if (!film) { this.graylog.warning({ message: `tmdb not found film name: ${name}; year: ${year}`, processId: this.processId, data: {name, year} }); return; } const about = film.overview; const id = film.id; film = await this.getMovieById({id}); if (!film) { this.graylog.warning({ name: `tmdb not found film by id: ${id}; name: ${name}; year: ${year}`, processId: this.processId, data: {name, year} }); return; } film = processFilm({film, about}); return film; } } <file_sep>import pathExists from 'jrf-path-exists' export default function processFilm({film, about}) { const info = { id: pathExists(film, 'id', 0), img: pathExists(film, 'poster_path'), vote: pathExists(film, 'vote_average', 0), runtime: pathExists(film, 'runtime', 0), tagline: pathExists(film, 'tagline', ''), originalName: pathExists(film, 'original_title', ''), about: about || pathExists(film, 'overview', ''), }; const genres = pathExists(film, 'genres', []); info.genres = genres.map(el => pathExists(el, 'name')); const country = pathExists(film, 'production_countries', []); info.country = country.map(el => pathExists(el, 'iso_3166_1')); return info; } <file_sep>import {ImageAnnotatorClient} from '@google-cloud/vision'; import axios from 'axios' import pathExists from 'jrf-path-exists'; const TEXT_DETECTION = 'TEXT_DETECTION'; export class Vision { constructor({logger, clientEmail, privateKey, projectId, processId}) { this.client = new ImageAnnotatorClient({ credentials: { client_email: clientEmail, private_key: privateKey }, projectId }); this._logger = logger; this._processId = processId; } async getTextFromWebImgByUrl(url) { try { const imageBuffer = await this._getImageBufferByUrl(url); const imageBase64 = this._convertImageToBase64(imageBuffer); const result = await this._sendRequestInVision(imageBase64); const text = pathExists(result, '[0].responses[0].fullTextAnnotation.text'); return text; } catch (error) { this._logger.error({error, processId: this._processId}); } } async _getImageBufferByUrl(url) { const res = await axios.get(url, {responseType: 'arraybuffer'}); return res.data; } _convertImageToBase64(imageBuffer) { const imageBase64 = Buffer.from(imageBuffer).toString('base64'); return imageBase64; } async _sendRequestInVision(imageBase64) { const request = this._createRequest(imageBase64); const requests = [request]; const results = await this.client.batchAnnotateImages({requests}); return results; } _createRequest(imageBase64) { const request = { image: { content: imageBase64, }, features: [{type: TEXT_DETECTION}], }; return request; } }
b323a335241f0d708aeedf542ba70f0607f13034
[ "JavaScript" ]
3
JavaScript
jirufik/sredaOnlineParser
4c2f19750732aed0343d517e2a4128d9fe79e5a1
0a7dc6be216c568c22734613c9c3d88fdeb3787f
refs/heads/main
<file_sep><!-- Sticky Footer --> <footer class="sticky-footer"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <?php $file = $_SERVER['SCRIPT_FILENAME']?> <?php echo "<a target=\"_blank\" href='../displaysource.php?filename=".$file."'>" .$file."</a><br />";?> </div> </div> </footer><file_sep><?php include("../loginCheck.php"); include("../connection.php"); $dsn = "mysql:host=$Host;dbname=$DB;"; $dbh = new PDO($dsn, $UName, $PWord); $stmt = $dbh->prepare("select * from client"); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } ?> <?php include("../templateTop.html") ?> <div id="content-wrapper"> <form method="post" action="index.php"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a class="btn-block btn btn-primary" href="../clients/add.php">Add Client</a> </li> </ol> <!-- DataTables --> <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> Client Table </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Name</th> <th>Street</th> <th>Surburb</th> <th>State</th> <th>Postcode</th> <th>Email</th> <th>Mobile</th> <th>List</th> <th>Delete</th> <th>Edit</th> </tr> </thead> <tfoot> <tr> <th>Name</th> <th>Street</th> <th>Surburb</th> <th>State</th> <th>Postcode</th> <th>Email</th> <th>Mobile</th> <th>List</th> <th>Delete</th> <th>Edit</th> </tr> </tfoot> <tbody> <?php while($row = $stmt->fetch()){ ?> <tr> <td><?php echo $row[1]." ".$row[2]; ?></td> <td><?php echo $row[3]; ?></td> <td><?php echo $row[4]; ?></td> <td><?php echo $row[5]; ?></td> <td><?php echo $row[6]; ?></td> <td><?php echo $row[7]; ?></td> <td><?php echo $row[8]; ?></td> <td><?php if ($row[9]==0){ echo "No"; }else{ echo "Yes"; } ?> </td> <td> <a href="../clients/CustModify.php?clientid=<?php echo $row[0];?>&Action=Delete">Delete</a> </td> <td> <a href="../clients/CustModify.php?clientid=<?php echo $row[0];?>&Action=Update">Edit</a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <div class="card-footer small text-muted">Famox</div> </div> <!--PDF Creation--> <ol class="breadcrumb"> <li class="breadcrumb-item "> <a class="btn-block btn btn-primary" target="_blank" href="list.php">Generate PDF</a> </li> </ol> </div> </form> <?php include("../displayPHP.php") ?> </div> <?php include("../templateBottom.html") ?> <script> $('#dataTable').dataTable( { "columns": [ null, { "orderable": false }, null, null, null, null, null, null, { "orderable": false }, { "orderable": false } ] } ); </script> <?php function logout() { unset($_SESSION["access_status"]); header("Location: ../index.html"); } if (isset($_GET['logout'])) { logout(); } ?><file_sep><?php include("../loginCheck.php"); include("../connection.php"); include("../templateTop.html"); $dsn = "mysql:host=$Host;dbname=$DB;"; $dbh = new PDO($dsn, $UName, $PWord); $result=$_GET["key"]; $query_rs= "SELECT * FROM category WHERE category_name LIKE '%$result%'"; $rs=$dbh->prepare($query_rs) ; if(!$rs->execute()) { $err = $rs->errorInfo(); echo "Error select record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } $stmt = $dbh->prepare("drop table searchtable;"); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } $stmt = $dbh->prepare("CREATE TABLE searchTable AS SELECT * FROM category WHERE category_name LIKE '%$result%'"); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } $stmt = $dbh->prepare("SELECT pc.product_id,product_name,product_purchase_price,product_sale_price,product_country_of_origin FROM product inner join product_category pc on product.product_id = pc.product_id inner join searchtable s on pc.category_id = s.category_id"); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } ?> <div id="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <div> <a class="btn-block btn btn-primary" href="../products/add.php">Add Product</a> </div> </li> </ol> <ol class="breadcrumb"> <li class="breadcrumb-item"> <!-- Search form --> <form class="form-inline active-purple-3 active-purple-4" method="get" action="?"> <i class="fas fa-search" aria-hidden="true"></i> <input class="form-control form-control-sm ml-3 w-75" name="key" type="text" value="<?php echo $_GET["key"];?>" placeholder="Search" aria-label="Search"> <!--<a href="../products/searchResult.php?key=<?php /*echo $_GET["key"]; */?>">Search</a>--> <input class="btn btn-primary" type="submit" value="Search"> </form> </li> </ol> <!-- DataTables --> <div class="card mb-3"> <form method="post" action="index.php"> <div class="card-header"> <i class="fas fa-table"></i> Product Table </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Product name</th> <th>Purchase price($)</th> <th>Sale price($)</th> <th>Country</th> <th>Delete</th> <th>Edit</th> </tr> </thead> <tfoot> <tr> <th>Product name</th> <th>Purchase price($)</th> <th>Sale price($)</th> <th>Country</th> <th>Delete</th> <th>Edit</th> </tr> </tfoot> <tbody> <?php while($row = $stmt->fetch()){ ?> <tr> <!--<td><?php /*echo $row->product_name; */?></td> <td><?php /*echo "$".$row->product_purchase_price; */?></td> <td><?php /*echo "$".$row->product_sale_price; */?></td> <td><?php /*echo $row->product_country_of_origin; */?></td>--> <td><?php echo $row[1]; ?></td> <td><?php echo "$".$row[2]; ?></td> <td><?php echo "$".$row[3]; ?></td> <td><?php echo $row[4]; ?></td> <td> <a href="../products/ProductModify.php?productId=<?php echo $row[0];?>&Action=Delete">Delete</a> </td> <td> <a href="../products/ProductModify.php?productId=<?php echo $row[0];?>&Action=Update">Edit</a> </td> </tr> <?php } //$stmt->closeCursor(); ?> </tbody> </table> </div> </div> <div class="card-footer small text-muted">Famox</div> </form> </div> </div> <!-- /.container-fluid --> <?php include("../displayPHP.php") ?> </div> <!-- /.content-wrapper --> <?php include("../templateBottom.html") ?> <script> $('#dataTable').dataTable( { searching:false, "columns": [ null, null, null, null, { "orderable": false }, { "orderable": false } ] } ); </script> <file_sep><?php include("../loginCheck.php"); include("../connection.php"); $dsn = "mysql:host=$Host;dbname=$DB;"; $dbh = new PDO($dsn, $UName, $PWord); $stmt = $dbh->prepare("select * from client where client_mailinglist!= 0"); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } include("../templateTop.html"); ?> <div id="content-wrapper"> <div class="container-fluid"> <!-- Page Content --> </div> <form method="post" action="email.php"> <div class="row"> <div class="col-lg-4"> <div class="card mb-3"> <div class="card-header"> <i class="fas fa-chart-pie"></i> Mailing List</div> <div class="card-body"> <table class="table-bordered"> <tr> <th>Client Name</th> <th style="text-align:center">Email</th> <th>Send</th> </tr> <?php while($row = $stmt->fetch()){ ?> <tr> <td><?php echo $row[1]," ",$row[2]; ?></td> <td style="text-align:center"><?php echo $row[7]; ?></td> <td style="text-align:center" ><input type="checkbox" name="check[]" value="<?php echo $row[0]; ?>"></td> </tr> <?php } $stmt->closeCursor(); ?> </table><p/> </div> </div> </div> <?php if (!isset($_POST["check"])) {?> <div class="col-lg-8"> <div class="card mb-3"> <div class="card-header"> <i class="fas fa-chart-bar"></i> Send Email</div> <div class="card-body"> Subject:<br> <input class="border" type="text" name="subject" size="50" required><br> Message:<br> <td> <textarea class="border" cols="68" name="message" rows="8" required></textarea> </td> <br><br> <input type="submit" value="Send" class="btn btn-primary"> <input type="reset" value="Reset" class="btn btn-secondary"> </div> </div> </div> </div> </form> <?php }else{ foreach($_POST["check"] as $id) { $query="Select client_email FROM client WHERE client_id ='$id'"; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } else if($stmt->execute()) { $row = $stmt->fetch(); $from = "From: <NAME><<EMAIL>>"; $to = $row[0]; $msg = $_POST["message"]; $subject = $_POST["subject"]; if(mail($to, $subject, $msg, $from)) { echo "Mail Sent: $row[0]<br/>"; } else { echo "Error Sending Mail:$row[0]"; } } } echo "<br><div><button href='email.php'>Back to mail box</button></div>"; } ?> </div> <?php include("../displayPHP.php") ?> </div> <!-- /.content-wrapper --> </div> <!-- /#wrapper --> <?php include("../templateBottom.html");?> <file_sep><link href="../css/sb-admin.css" rel="stylesheet"> <?php /** * Created by PhpStorm. * User: janet * Date: 8/09/2017 * Time: 2:51 AM */ class CreatePDF { function CustomerPDF($header, $headerWidth, $data) { define ('K_PATH_IMAGES', 'img/'); // create new PDF document $pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true); // set document header information. This appears at the top of each page of the PDF document $pdf->SetHeaderData("Famox.png","50", "Client List", ''); // set header and footer fonts $pdf->setHeaderFont(array('helvetica', '', 20)); //set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); //set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); // add a page $pdf->AddPage(); $pdf->Ln(); $table = '<table class="table-bordered" align="center" class="" cellpadding="5" cellspacing="5" border="0">'; $table.='<tr bgcolor="#336888">'; for($i = 0; $i < sizeof($header); ++$i) { $table.='<td width="'.$headerWidth[$i].'">'.$header[$i].'</td>'; } $table.="</tr>"; $rowCount=0; foreach($data as $row) { if($rowCount%2==0) { $table.='<tr valign="top" bgcolor="#ACC5D3">'; } else { $table.='<tr valign="top">'; } $table.="<td>$row[client_id]</td>"; $table.="<td>$row[client_gname] $row[client_fname]</td>"; $table.="<td>$row[client_street]</td>"; $table.="<td>$row[client_mobile]</td>"; $table.="</tr>"; $rowCount++; } $table .= "</table>"; $pdf->writeHTML($table, false, false, false, false, 'L'); //add new line after text written //fill - paint background //reset last cell height //add current cell padding //alignment $saveDir= dirname($_SERVER["SCRIPT_FILENAME"])."/PDFS/"; if($pdf->Output($saveDir.'Customers.pdf','F')); { return $table; } exit(); } } <file_sep><?php include("../loginCheck.php"); include("../templateTop.html"); if (empty($_POST["ppp"])) { ?> <div id="content-wrapper"> <div class="container"> <form method="POST" action="add.php" enctype="multipart/form-data" name="addProductForm" onsubmit="return validateForm()"> <center><h3>Product details amendment</h3></center> <table class="table table-bordered" align="center" cellpadding="3"> <tr> <td><b>Product name</b></td> <td><input class="border" type="text" name="pname" size="25" required> </td> </tr> <tr> <td><b>Purchase price</b></td> <td>$<input class="border" type="text" name="ppp" size="10" required> </td> </tr> <tr> <td><b>Sale price</b></td> <td>$<input class="border" type="text" name="psp" size="10" required></td> </tr> <tr> <td><b>Country of origin</b></td> <td><input class="border" type="text" name="pco" size="15" required></td> </tr> <tr> <td><b>Product image</b></td> <td><input class="border" type="file" size="50" name="images[]" multiple></td> </tr> </table> <br><br/> <table align="center"> <tr> <td><input class="btn btn-primary" type="submit" value="Submit" ></td> <td><input class="btn btn-secondary" type="button" value="Return to List" OnClick="window.location='index.php?key='"></td> </tr> </table> <?php include("../connection.php"); $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); $query="SELECT * FROM category "; $stmt = $dbh->prepare($query); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } ?> <hr> <form method="post" name="editForm" action="ProductModify.php"> <table align="center" border="1" cellpadding="5"> <tr> <th>CATEGORY</th> <th></th> </tr> <?php while ($Titles = $stmt->fetchObject()) { ?> <tr> <td><?php echo $Titles->category_name; ?></td> <td align="center"><input type="checkbox" name="check[]" value="<?php echo $Titles->category_id; ?>" > </td> </tr> <?php } ?> </table><p /> </form> </form> <?php include("../displayPHP.php") ?> </div> </div> <?php include("../templateBottom.html") ?> <?php }else{ include("../connection.php"); $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); $query = "INSERT INTO product (product_name, product_purchase_price, product_sale_price, product_country_of_origin) VALUES ('$_POST[pname]','$_POST[ppp]', '$_POST[psp]', '$_POST[pco]')"; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; }else{ if(!empty($_POST['check'])){ foreach($_POST["check"] as $change) { $stmt = $dbh->prepare( "INSERT INTO product_category( category_id,product_id) values ('$change',last_insert_id())"); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } } } $stmt = $dbh->prepare("SELECT LAST_INSERT_ID() INTO @lastID"); $stmt->execute(); $allowTypes = array('jpg','png','jpeg','gif'); $targetDir = "../product_images/"; if(!empty(array_filter($_FILES['images']['name']))){ foreach ($_FILES['images']['name'] as $key=>$val){ $fileName = basename($_FILES['images']['name'][$key]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)){ if(!move_uploaded_file($_FILES["images"]["tmp_name"][$key], $targetFilePath)){ echo "ERROR: Could Not Move File: $fileName into Directory"; }else{ $queryImage = "INSERT INTO product_image (product_id, image_name) VALUES (@lastID,'$fileName')"; $stmt = $dbh->prepare($queryImage); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; }else{ header("Location: index.php?key="); } } } } } header("Location: index.php?key="); } } ?> <script> //JavaScript Validation function validateForm() { let productName = document.forms["addProductForm"]["pname"].value; if(!/^[a-zA-Z0-9]+$/.test(productName)){ alert("Please Check Your Product Name. Do not include special characters"); return false; } let country = document.forms["addProductForm"]["pco"].value; if(!/^[a-zA-Z]+$/.test(country)){ alert("Please Check Product Country Name. Do not include special characters") return false; } //It returns -1 if the argument passed a negative number. let purchasePrice = document.forms["addProductForm"]["ppp"].value; if ( Number(purchasePrice)<0 || purchasePrice.length>10 || isNaN(purchasePrice)) { alert("Please Check Your Product Purchase Price."); return false; } let salePrice = document.forms["addProductForm"]["psp"].value; if (Number(salePrice) < 0 || salePrice.length>10 || isNaN(salePrice)) { alert("Please Check Your Product Sale Price."); return false; } } </script> <file_sep><?php include("../loginCheck.php"); include("../templateTop.html"); ?> <?php if (empty($_POST["fname"])) { ?> <div class="container"> <form method="POST" action="add.php"> <center><h3>Customer details amendment</h3></center> <table class="table table-bordered" align="center" cellpadding="3"> <tr> <td><b>Firstname</b></td> <td><input class="border" type="text" name="fname" size="20" required> </td> </tr> <tr> <td><b>Surname</b></td> <td><input class="border" type="text" name="sname" size="20" required> </td> </tr> <tr> <td><b>Street</b></td> <td><input class="border" type="text" name="street" size="45"></td> </tr> <tr> <td><b>Suburb</b></td> <td><input class="border" type="text" name="suburb" size="20" ></td> </tr> <tr> <td><b>State</b></td> <td><input class="border" type="text" name="state" size="15"> </td> </tr> <tr> <td><b>Postcode</b></td> <td><input class="border" type="text" name="postcode" size="10"> </td> </tr> <tr> <td><b>Email</b></td> <td><input class="border" type="email" name="email" size="30" required> </td> </tr> <tr> <td><b>Mobile</b></td> <td><input class="border" type="number" name="mobile" size="15"></td> </tr> <tr> <td><b>Mailing List</b></td> <td> <div> <select name="mailinglist"> <option value=1>Yes</option> <option value=0>No</option> </select> </div> </td> <!-- <td><input class="border" type="number" name="mailinglist" size="5"></td>--> </tr> </table> <br><br/> <table align="center"> <tr> <td><input class="btn btn-primary" type="submit" value="Submit"></td> <td><input class="btn btn-secondary" type="button" value="Return to List" OnClick="window.location='index.php'"></td> </tr> </table> </form> <?php include("../displayPHP.php") ?> </div> <?php }else{ include("../connection.php"); $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); $query = "INSERT INTO client (client_gname, client_fname, client_street, client_suburb,client_state,client_pc,client_email,client_mobile,client_mailinglist) VALUES ('$_POST[fname]','$_POST[sname]', '$_POST[street]', '$_POST[suburb]', '$_POST[state]', '$_POST[postcode]', '$_POST[email]', '$_POST[mobile]', '$_POST[mailinglist]')"; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); }else{ ?> <script language="JavaScript"> alert("Customer record successfully added"); </script> <?php header("Location: index.php"); } } ?> <?php include("../templateBottom.html"); ?> <file_sep><?php include("../loginCheck.php"); include("../templateTop.html"); ?> <script language="javascript"> function confirm_delete() { window.location='categoryModify.php?categoryId=<?php echo $_GET["categoryId"]; ?>&Action=ConfirmDelete'; } </script> <?php include("../connection.php"); $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); $query="SELECT * FROM category WHERE category_id =".$_GET["categoryId"]; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } $row=$stmt->fetchObject(); $strAction = $_GET["Action"]; switch($strAction) { case "Update": ?> <div class="container"> <form method="post" action="categoryModify.php?categoryId=<?php echo $_GET["categoryId"]; ?>&Action=ConfirmUpdate"> <center><h3>Category details amendment</h3><br /></center><p /> <table align="center" cellpadding="3"> <tr /> <td><b>Category. No.</b></td> <td><?php echo $row->category_id; ?></td> </tr> <tr> <td><b>Category. Name</b></td> <td><input class="border" type="text" name="cn" size="30" value="<?php echo $row->category_name; ?>"></td> </tr> </table> <br/> <table align="center"> <tr> <td><input class="btn btn-primary" type="submit" value="Update Category"></td> <td><input class="btn btn-secondary" type="button" value="Return to List" OnClick="window.location='index.php'"></td> </tr> </table> </form> </div> <?php break; case "ConfirmUpdate": $query="UPDATE category set category_name='$_POST[cn]' WHERE category.category_id =".$_GET["categoryId"]; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } header("Location: index.php"); break; case "Delete": ?> <div class="container"> <center><h3>Confirm deletion of the following category record</h3><br/></center><p /> <table align="center" cellpadding="3"> <tr /> <td><b>Category. No.</b></td> <td><?php echo $row->category_id; ?></td> </tr> <tr> <td><b>Name</b></td> <td><?php echo "$row->category_name"; ?></td> </tr> </table> <br/> <table align="center"> <tr> <td><input class="btn btn-primary" type="button" value="Confirm" OnClick="confirm_delete();"> <td><input class="btn btn-secondary" type="button" value="Cancel" OnClick="window.location='index.php'"></td> </tr> </table> </div> <?php break; case "ConfirmDelete": $query="DELETE FROM category WHERE category_id =".$_GET["categoryId"]; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } else if($stmt->execute()) { ?> <div class="container"> <center> <h3>The following customer record has been successfully deleted</h3><p/> <?php echo "Category No. $row->category_id"; echo "</center><p />"; } else { echo "<center>Error deleting customer record<p /></center>"; } echo "<center><input class='btn btn-secondary' type='button' value='Return to List' OnClick='window.location=\"index.php\"'></center>"; break; } $stmt->closeCursor(); ?> </div> <?php include("../displayPHP.php") ?> <?php include("../templateBottom.html");?> <file_sep><?php include("../loginCheck.php"); include("../templateTop.html"); include("../connection.php"); $dsn = "mysql:host=$Host;dbname=$DB;"; $dbh = new PDO($dsn, $UName, $PWord); $stmt = $dbh->prepare("select * from product_image"); $stmt->execute(); $currdir = dirname($_SERVER["SCRIPT_FILENAME"]); $dir = opendir($currdir); if(empty($_POST["delete"])) { ?> <div id="content-wrapper"> <div class="container-fluid"> <form method="post" action="displayImages.php"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <input class='btn btn-primary' type='submit' value='Delete Selected Files'> </li> </ol> <div class="row"> <?php while($file = readdir($dir)) { if(fnmatch("*.jpg",$file)|| fnmatch("*.png",$file)){ ?> <div class="col-md-3"> <div class="thumbnail"> <!-- --><?php //echo $file ?> <?php echo '<img src="'.$file.'" style="width: 80%"/><br/>' ;?> <div class="form-check"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" name="delete[]" value="<?= $file ?>"> <?php $sql = "select product_id from product_image where image_name='" . $file . "'"; $stmtProduct = $dbh->prepare("select * from product where product_id="."(".$sql.")"); $stmtProduct->execute(); $productRow=$stmtProduct->fetch(); echo "Product Name: $productRow[1]"; echo "<br>Purchase Price: $$productRow[2]"; echo "<br>Sale Price: $$productRow[3]"; echo "<br>Country: $productRow[4]"; ?> </label> </div> </div> </div> <?php } } ?> </div> </form> </div> </div> <?php } else {?> <div class="container-fluid"> <?php foreach($_POST["delete"] as $filename ) { if(unlink($filename)) { $query = "DELETE FROM product_image WHERE image_name ='" . $filename . "'"; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "<h4 align='center'>Error deleting record to database – contact System Administrator Error is:</h4> <b><h5 align='center'>" . $err[2] . "</h5></b>"; } else { echo "<center>Image File ".$filename." has been deleted<br></center>"; } }else{ echo "ERROR: Can't Delete Image File.$filename"; } } echo "<center><input class='btn btn-secondary' type='button' value='Return to List' OnClick='window.location=\"displayImages.php\"'></center>"; } closedir($dir); ?> </div> </form> </div> <?php include("../displayPHP.php") ?> <?php include("../templateBottom.html") ?><file_sep><?php include("../loginCheck.php"); include("../templateTop.html"); if (empty($_POST["cn"])) { ?> <div class="container"> <form method="POST" action="add.php"> <h3 align="center">Category details amendment</h3> <table class="" align="center" cellpadding="3"> <tr> <td><b>category_name</b></td> <td><input class="border" type="text" name="cn" size="25" required> </td> </tr> </table> <br><br/> <table align="center"> <tr> <td><input class="btn btn-primary" type="submit" value="Submit"></td> <td><input class="btn btn-secondary" type="button" value="Return to List" OnClick="window.location='index.php'"></td> </tr> </table> </form> </div> <?php include("../displayPHP.php") ?> <?php include("../templateBottom.html"); }else{ include("../connection.php"); $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); $query = "INSERT INTO category (category_name) VALUES ('$_POST[cn]')"; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); }else{ ?> <script language="JavaScript"> alert("category record successfully added"); </script> <?php header("Location: index.php"); } } ?><file_sep><?php include("../loginCheck.php"); include("../templateTop.html") ?> <?php include("../connection.php"); $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); $query="SELECT * FROM product WHERE product_id =".$_GET["productId"]; $sql="SELECT * FROM category"; $stmt = $dbh->prepare($query); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error select record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } $row=$stmt->fetchObject(); $strAction = $_GET["Action"]; switch($strAction) { case "Update": ?> <div id="content-wrapper"> <div class="container-fluid"> <form method="post" enctype="multipart/form-data" name="editProductForm" onsubmit="return validateForm()" action="ProductModify.php?productId=<?php echo $_GET["productId"]; ?>&Action=ConfirmUpdate"> <center><h4>Product details amendment</h4><br /></center><p /> <table align="center" cellpadding="3"> <tr /> <td><b>Product. No.</b></td> <td><?php echo $row->product_id; ?></td> </tr> <tr> <td><b>Product. Name</b></td> <td><input type="text" name="pname" size="30" value="<?php echo $row->product_name; ?>"></td> </tr> <tr> <td><b>Product. Purchse Price</b></td> <td><input type="number" name="ppp" size="30" value="<?php echo $row->product_purchase_price; ?>"></td> </tr> <tr> <td><b>Product. Sale Price</b></td> <td><input type="number" name="psp" size="40" value="<?php echo $row->product_sale_price; ?>"></td> </tr> <tr> <td><b>Product. Country of origin</b></td> <td><input type="text" pattern="[a-zA-Z]*" name="pco" size="10" value="<?php echo $row->product_country_of_origin; ?>"></td> </tr> <tr> <?php $query="SELECT * FROM product_image WHERE product_id=".$row->product_id; $stmt = $dbh->prepare($query); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error select record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } while($rowImage = $stmt->fetch()){ ?> <td><b>Image</b></td> <td><img src="../product_images/<?= $rowImage[2] ?>" style="width: 20%"/></td> <?php // echo "<td>$rowImage[2]</td>"; // echo ""; } ?> </tr> <tr> <td><b>Update image</b></td> <td><input class="border" type="file" size="50" name="images[]" multiple></td> </tr> </table> <br/> <table align="center"> <tr> <td><input class="btn btn-primary" type="submit" value="Update Product" ></td> <td><input class="btn btn-secondary" type="button" value="Return to List" OnClick="window.location='index.php?key='"></td> </tr> </table> <?php $query="SELECT * FROM category "; $stmt = $dbh->prepare($query); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error select record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } $stmtI = $dbh->prepare("SELECT * FROM product_category where product_id=".$_GET["productId"]); if(!$stmtI->execute()){ $err = $stmtI->errorInfo(); echo "Error select record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } $aList=[]; while( $sql=$stmtI->fetchObject() ) {?><?php array_push($aList,$sql->category_id); } function pChecked($v1,$list){ $pChecked=""; for($i=0;$i<sizeof($list);$i++) { if($v1==$list[$i]) { $pChecked="checked"; } } return $pChecked; } ?> <hr> <form method="post" name="editForm" action="ProductModify.php"> <table align="center" border="1" cellpadding="5"> <tr> <th>CATEGORY</th> <th></th> </tr> <?php while ($Titles = $stmt->fetchObject()) { ?> <tr> <td><?php echo $Titles->category_name; ?></td> <td align="center"><input type="checkbox" name="check[]" value="<?php echo $Titles->category_id; ?>" <?php echo pChecked($Titles->category_id, $aList) ?>> </td> </tr> <?php } ?> </table><p /> </form> </form> </div> </div> <?php break; case "ConfirmUpdate": $query="UPDATE product set product_name='$_POST[pname]', product_purchase_price='$_POST[ppp]', product_sale_price='$_POST[psp]', product_country_of_origin='$_POST[pco]' WHERE product.product_id =".$_GET["productId"]; $stmt = $dbh->prepare($query); $cId=$_GET["productId"]; if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error update record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } else{ $stmt = $dbh->prepare( "DELETE FROM product_category where product_id=$cId"); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error delete record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } if(!empty($_POST['check'])){ foreach($_POST["check"] as $change) { $stmt = $dbh->prepare( "INSERT INTO product_category( category_id,product_id) values ('$change','$cId')"); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } } } } if(!isset($_POST['images']['name'])){ //delete related images $sql="SELECT * FROM product_image WHERE product_id=".$cId; $stmt = $dbh->prepare($sql); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } $targetDir = "../product_images/"; while($rowDeleteImg = $stmt->fetch()){ echo "<h1>$rowDeleteImg[2]</h1>"; $targetFilePath = $targetDir.$rowDeleteImg[2]; if(unlink($targetFilePath)) { $sql="DELETE FROM product_image WHERE product_id=".$_GET["productId"]; $stmt = $dbh->prepare($sql); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "<h4 align='center'>Error deleting record to database – contact System Administrator Error is:</h4> <b><h5 align='center'>" . $err[2] . "</h5></b>"; } else { echo "<center>Image File has been deleted<br></center>"; } }else{ echo "ERROR: Can't Delete Image File.$rowDeleteImg"; } } //insert new images $allowTypes = array('jpg','png','jpeg','gif'); foreach ($_FILES['images']['name'] as $key=>$val){ $fileName = basename($_FILES['images']['name'][$key]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)){ if(!move_uploaded_file($_FILES["images"]["tmp_name"][$key], $targetFilePath)){ echo "ERROR: Could Not Move File: $fileName into Directory"; }else{ $queryImage = "INSERT INTO product_image (product_id, image_name) VALUES ('$cId','$fileName')"; $stmt = $dbh->prepare($queryImage); if(!$stmt->execute()){ $err = $stmt->errorInfo(); echo "Error insert record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; }else{ header("Location: index.php?key="); } } } } } header("Location: index.php?key="); break; case "Delete": ?> <div class="container-fluid"> <center><h4>Confirm deletion of the following product record</h4><br /></center><p /> <table align="center" cellpadding="3"> <tr /> <td><b>Product. No.</b></td> <td><?php echo $row->product_id; ?></td> </tr> <tr> <td><b>Name</b></td> <td><?php echo "$row->product_name"; ?></td> </tr> </table> <br/> <table align="center"> <tr> <td><input type="button" class="btn btn-primary" value="Confirm" OnClick="confirm_delete();"> <td><input type="button" class="btn btn-secondary" value="Cancel" OnClick="window.location='index.php?key='"></td> </tr> </table> </div> <?php break; case "ConfirmDelete": ?> <div class="container-fluid"> <?php $BaseDir = '../product_images/'; $images_path = realpath($BaseDir); $old = getcwd(); // Save the current directory chdir($images_path); $queryImageFile="SELECT * FROM product_image WHERE product_id=".$_GET["productId"]; $stmtImageFile = $dbh->prepare($queryImageFile); if($stmtImageFile->execute()){ while ($image_row = $stmtImageFile->fetch()){ unlink($image_row[2]); } }else{ echo "Error select record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } $queryImage="DELETE FROM product_image WHERE product_id =".$_GET["productId"]; $stmtImage = $dbh->prepare($queryImage); if(!$stmtImage->execute()){ $err = $stmtImage->errorInfo(); echo "Error delete record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; } else{ echo "<br><h5 align='center'>Successfully delete related images.</h5>"; } chdir($old); // Restore the old working directory $query="DELETE FROM product_category WHERE product_id =".$_GET["productId"]; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } $query="DELETE FROM product WHERE product_id =".$_GET["productId"]; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } else if($stmt->execute()) { ?> <h4 align="center">The following product record has been successfully deleted</h4><p/><br> <?php echo "<div align='center'>Product No. $row->product_id <br>$row->product_name<br></div>"; echo "</center><p/>"; } else { echo "<center>Error deleting product record<p /></center>"; } echo "<center><input type='button' value='Return to List' OnClick='window.location=\"index.php?key=\"'></center>"; break; } ?> </div> <?php include("../displayPHP.php") ?> <?php include('../templateBottom.html'); ?> <script> function confirm_delete() { window.location='ProductModify.php?productId=<?php echo $_GET["productId"]; ?>&Action=ConfirmDelete'; } function check(id,check) { if (check) { $('.' +id).find('input[type="checkbox"]').prop('checked', true); } else { $('.' +id).find('input[type="checkbox"]').removeAttr('checked'); } } function validateForm() { let productName = document.forms["editProductForm"]["pname"].value; if(!/^[a-zA-Z0-9]+$/.test(productName)){ alert("Please Check Your Product Name. Do not include special characters"); return false; } let country = document.forms["editProductForm"]["pco"].value; if(!/^[a-zA-Z]+$/.test(country)){ alert("Please Check Product Country Name. Do not include special characters") } //It returns -1 if the argument passed a negative number. let purchasePrice = document.forms["editProductForm"]["ppp"].value; if ( Number(purchasePrice)<0 || purchasePrice.length>10 || isNaN(purchasePrice)) { alert("Please Check Your Product Purchase Price."); return false; } let salePrice = document.forms["editProductForm"]["psp"].value; if (Number(salePrice) < 0 || salePrice.length>10 || isNaN(salePrice)) { alert("Please Check Your Product Sale Price."); return false; } } </script> <file_sep><?php //$file = $_GET["filename"]; //echo "<h1>Source Code for: ".$file."</h1>"; ////open file for reading only // ////retrieve table which translates HTML tags to entities, eg convert < to &lt; // $line = file_get_contents($file); // $trans = get_html_translation_table(HTML_ENTITIES); ////get one line from file $fp // ////performs translation/sub string replacement based on translation table // $line = strtr($line,$trans); ////replace tab character with 4 HTML spaces to maintain some formatting // $line = str_replace("\t","&nbsp;&nbsp;&nbsp;&nbsp;",$line); // $line = str_replace("\n","<br/>",$line); ////echo line to screen, followed by break // echo $line."<br />"; // $file = $_GET["filename"]; echo "<h1>Source Code for: " . $file . "</h1>"; highlight_file($file); <file_sep><?php include("../loginCheck.php"); include("../connection.php"); $dsn = "mysql:host=$Host;dbname=$DB;"; $dbh = new PDO($dsn, $UName, $PWord); $stmt = $dbh->prepare("select * from project"); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } include("../templateTop.html") ?> <div id="content-wrapper"> <form method="post" action="index.php"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a class="btn-block btn btn-primary" href="../projects/add.php">Add Project</a> </li> </ol> <!-- DataTables --> <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> Project Table </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Project description</th> <th>Country</th> <th>City</th> <th>Delete</th> <th>Edit</th> </tr> </thead> <tfoot> <tr> <th>Project description</th> <th>Country</th> <th>City</th> <th>Delete</th> <th>Edit</th> </tr> </tfoot> <tbody> <?php while($row = $stmt->fetch()){ ?> <tr> <td><?php echo $row[1]; ?></td> <td><?php echo $row[2]; ?></td> <td><?php echo $row[3]; ?></td> <td> <a href="../projects/ProjectModify.php?projectId=<?php echo $row[0];?>&Action=Delete">Delete</a> </td> <td> <a href="../projects/ProjectModify.php?projectId=<?php echo $row[0];?>&Action=Update">Edit</a> </td> </tr> <?php } //$stmt->closeCursor(); ?> </tbody> </table> </div> </div> <div class="card-footer small text-muted">Famox</div> </div> </div> </form> <!-- /.container-fluid --> <?php include("../displayPHP.php") ?> </div> <?php include("../templateBottom.html") ?> <script> $('#dataTable').dataTable( { "columns": [ null, null, null, { "orderable": false,"bSearchable": false }, { "orderable": false,"bSearchable": false} ] } ); </script> <file_sep><?php include("../loginCheck.php"); require "../vendor/autoload.php"; include("../connection.php"); include("CreatePDF.php"); include("../templateTop.html") ?> <div id="content-wrapper"> <div class="container"> <h1 align="center">Create PDF</h1> <?php $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); $stmt = $dbh->prepare("SELECT * FROM client ORDER BY client_id"); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } $allRows=$stmt->fetchAll(PDO::FETCH_ASSOC); //Column titles $header = array('Cust. No', 'Name', 'Address', 'Contact'); //Column Widths $headerWidth=array(100,250,300,200); //create new instance of my CreatePDF class $PDF = new CreatePDF(); //pass it headers, headerWidth and data $table = $PDF->CustomerPDF($header, $headerWidth, $allRows); echo $table; ?> <br/> <center><button class="btn-primary btn" OnClick="window.location='PDFs/Customers.pdf'">Click here to see PDF</button></center> <br/> </div> <?php include("../displayPHP.php") ?> </div> <?php include("../templateBottom.html") ?> <file_sep><?php include("../loginCheck.php"); include('../templateTop.html'); ?> <script language="javascript"> function confirm_delete() { window.location='CustModify.php?clientid=<?php echo $_GET["clientid"]; ?>&Action=ConfirmDelete'; } </script> <?php include("../connection.php"); $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); $query="SELECT * FROM client WHERE client_id =".$_GET["clientid"]; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } $row=$stmt->fetchObject(); $strAction = $_GET["Action"]; switch($strAction) { case "Update": ?> <div id="content-wrapper"> <div class="container-fluid"> <form method="post" action="CustModify.php?clientid=<?php echo $_GET["clientid"]; ?>&Action=ConfirmUpdate"> <center><h3>Customer details amendment</h3><br /></center><p /> <table class="table table-bordered" align="center" cellpadding="3"> <tr /> <td><b>Client. No.</b></td> <td><?php echo $row->client_id; ?></td> </tr> <tr> <td><b>Client. Firstname</b></td> <td><input class="border" type="text" name="fname" size="30" value="<?php echo $row->client_gname; ?>"></td> </tr> <tr> <td><b>Client. Surname</b></td> <td><input class="border" type="text" name="sname" size="30" value="<?php echo $row->client_fname; ?>"></td> </tr> <tr> <td><b>Address</b></td> <td><input class="border" type="text" name="street" size="40" value="<?php echo $row->client_street; ?>"></td> </tr> <tr> <td><b>Suburb</b></td> <td><input class="border" type="text" name="suburb" size="10" value="<?php echo $row->client_suburb; ?>"></td> </tr> <tr> <td><b>State</b></td> <td><input class="border" type="text" name="state" size="10" value="<?php echo $row->client_state; ?>"> </td> </tr> <tr> <td><b>Postcode</b></td> <td><input class="border" type="text" name="postcode" size="10" value="<?php echo $row->client_pc; ?>"> </td> </tr> <tr> <td><b>Email</b></td> <td><input class="border" type="text" name="email" size="30" value="<?php echo $row->client_email; ?>"> </td> </tr> <tr> <td><b>Mobile</b></td> <td><input class="border" type="text" name="mobile" size="15" value="<?php echo $row->client_mobile; ?>"></td> </tr> <tr> <td><b>Mailing List</b></td> <td> <div> <select name="mailinglist"> <?php if($row->client_mailinglist ==0){ echo "<option value=1>Yes</option> <option value=0 selected>No</option>"; }else{ echo "<option value=1 selected>Yes</option> <option value=0>No</option> "; } ?> </select> </div> </td> </tr> </table> <br/> <table align="center"> <tr> <td><input class="btn btn-primary" type="submit" value="Update"></td> <td><input class="btn btn-secondary" type="button" value="Return to List" OnClick="window.location='index.php'"></td> </tr> </table> </form> </div> <?php include("../displayPHP.php") ?> </div> <?php break; case "ConfirmUpdate": $query="UPDATE client set client_gname='$_POST[fname]', client_fname='$_POST[sname]', client_street='$_POST[street]', client_suburb='$_POST[suburb]',client_state='$_POST[state]',client_pc='$_POST[postcode]', client_email='$_POST[email]',client_mobile='$_POST[mobile]', client_mailinglist='$_POST[mailinglist]' WHERE client_id =".$_GET["clientid"]; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } header("Location: index.php"); break; case "Delete": ?> <div id="content-wrapper"> <div class="container-fluid"> <center><h3>Confirm deletion of the following customer record</h3></center> <br> <table class="table-bordered " align="center"> <tr> <td><b>Client. No.</b></td> <td><?php echo $row->client_id; ?></td> </tr> <tr> <td><b>Name</b></td> <td><?php echo "$row->client_gname $row->client_fname"; ?></td> </tr> </table> <br> <table align="center"> <tr> <td><input class="btn btn-primary" type="button" value="Confirm" OnClick="confirm_delete();"> <td><input class="btn btn-secondary" type="button" value="Cancel" OnClick="window.location='index.php'"></td> </tr> </table> </div> <?php include("../displayPHP.php") ?> </div> <?php break; case "ConfirmDelete": $query="DELETE FROM client WHERE client_id =".$_GET["clientid"]; $stmt = $dbh->prepare($query); if($stmt->execute()) { ?> <div class="container-fluid"> <h3 align="center">The following customer record has been successfully deleted</h3><p /> <?php echo "<h5 align='center'>Customer No. $row->client_id $row->client_gname $row->client_fname</h5>"; echo "</center><p />"; } else { $err = $stmt->errorInfo(); echo "Error delete record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } echo "<center><input class='btn btn-secondary' type='button' value='Return to List' OnClick='window.location=\"index.php\"'></center>"; break; } $stmt->closeCursor(); ?> </div> <?php include('../templateBottom.html'); ?> <file_sep>Authors:<br> <NAME><br> <NAME><br><br> Please modify connection.php file to access your database <file_sep><?php session_start(); ob_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Famox - Login</title> <!-- Custom fonts for this template--> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Custom styles for this template--> <link href="css/sb-admin.css" rel="stylesheet"> </head> <body class="bg-dark"> <?php if(empty($_POST["uname"])) { ?> <div class="container"> <div class="card card-login mx-auto mt-5"> <div class="card-header">Login</div> <div class="card-body"> <form method="post" action="login.php"> <div class="form-group"> <div class="form-label-group"> <input type="text" id="inputEmail" name="uname" class="form-control" placeholder="User name" required="required" autofocus="autofocus"> <label for="inputEmail">User name</label> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="password" id="inputPassword" name="pword" class="form-control" placeholder="Password" required="required"> <label for="inputPassword">Password</label> </div> </div> <div class="form-group"> <hr> </div> <input class="btn btn-primary btn-block" type="submit" value="Login" > </form> </div> </div> </div> <?php }else{ include("connection.php"); $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); $stmt = $dbh->prepare("SELECT uname FROM admin WHERE uname = ? AND pword = ?"); $pword = hash('sha1', $_POST["pword"]); $stmt->execute([$_POST["uname"], $pword]); $result = $stmt->fetchObject(); if(!empty($result)) { echo "Welcome to our site $result->uname"; $_SESSION["access_status"] = true; header("Location:clients/index.php"); } else { ?> <div class="container"> <div class="card card-login mx-auto mt-5"> <div class="card-header">Login</div> <div class="card-body"> <form action="login.php"> <div align="center" class="alert alert-danger" role="alert"> Login Details Incorrect </div> <div class="form-group"> <hr> </div> <input class="btn btn-secondary btn-block" type="submit" value="Try Again" > </form> </div> </div> </div> <?php } } ?> </body> </html> <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <script language="javascript"> function displayError() { alert("Sorry, Login details incorrect") } </script><file_sep><?php include("../loginCheck.php"); include("../connection.php"); $dsn= "mysql:host=$Host;dbname=$DB"; $dbh = new PDO($dsn,$UName,$PWord); if(empty($_POST["check"])) { $query="SELECT * FROM product "; $stmt = $dbh->prepare($query); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } /* $row=$stmt->fetchObject();*/ /*$strAction = $_GET["Action"];*/ ?> <?php include("../templateTop.html") ?> <div id="content-wrapper"> <div class="container"> <h3 align="center"><b>Product Details</b></h3> <form method="post" action="multipleEdit.php"> <table class="table-bordered" border="1" cellpadding="5" align="center"> <tr> <th>ID</th> <th>Name</th> <th>Edit</th> <th>Sale Price</th> </tr> <?php while ($Titles= $stmt->fetchObject()) { ?> <tr> <td><?php echo $Titles->product_id; ?></td> <td><?php echo $Titles->product_name; ?></td> <td align="center"><input type="checkbox" name="check[]" value="<?php echo $Titles->product_id; ?>"></td> <td align="center">$<input class="border" type="text" size="8" name="<?php echo $Titles->product_id; ?>" value="<?php echo $Titles->product_sale_price; ?>"></td> </tr> <?php } ?> </table> <hr> <div align="center"> <input class="btn btn-primary" type="submit" value="Update Selected Titles"> </div> </form> </div> </div> <?php } else { foreach($_POST["check"] as $change) { //echo "ISBN is $isbn<br />"; //echo "Cost Price is $_POST[$isbn]<br /><br />"; $stmt = $dbh->prepare("UPDATE product set product_sale_price = $_POST[$change] where product_id='$change'"); if(!$stmt->execute()) { $err = $stmt->errorInfo(); echo "Error adding record to database – contact System Administrator Error is: <b>" . $err[2] . "</b>"; $stmt->execute(); } } header("Location: index.php?key="); } $stmt->closeCursor(); ?> <?php include("../displayPHP.php") ?> <?php include("../templateBottom.html"); ?><file_sep><?php session_start(); ob_start(); if($_SESSION["access_status"] != true){ header("Location: ../login.php"); exit; } ?><file_sep># drop table PRODUCT_CATEGORY; # drop table PRODUCT_IMAGE; # drop table CLIENT; # drop table CATEGORY; # drop table PRODUCT; # drop table PROJECT; # drop table ADMIN; create table client ( client_id int auto_increment primary key, client_gname varchar(50) not null, client_fname varchar(50) not null, client_street char(100) null, client_suburb varchar(50) null, client_state varchar(20) null, client_pc varchar(4) null, client_email varchar(50) null, client_mobile varchar(12) null, client_mailinglist tinyint(1) null ); create table category ( category_id int auto_increment primary key, category_name varchar(100) not null ); create table product ( product_id int auto_increment primary key, product_name varchar(100) not null, product_purchase_price double(11,2) null, product_sale_price double(11,2) null, product_country_of_origin varchar(40) null ); create table product_category ( product_id int not null, category_id int not null, primary key (product_id, category_id), constraint CATEGORY_PRODUCT_id_fk foreign key (category_id) references category (category_id), constraint PRODUCT_CATEGORY_id_fk foreign key (product_id) references product (product_id) ); create table project ( project_id int auto_increment primary key, project_desc varchar(100) not null, project_country varchar(50) null, project_city varchar(50) null ); create table product_image ( image_id int auto_increment primary key, product_id int not null, image_name varchar(40) not null, constraint PRODUCT_IMAGE_PRODUCT_id_fk foreign key (product_id) references product (product_id) ); create table admin ( admin_id int auto_increment primary key, uname varchar(255) null, pword varchar(255) null ); create table searchtable ( category_id int default 0 not null, category_name varchar(100) not null );
ee77a6f61548e488ae94f29977b0fa8b51665c15
[ "Markdown", "SQL", "PHP" ]
20
PHP
xingdongcai/webman
e806f2654d6fd349a508845a38b68c65579e6081
ae70c556549c6d52b86bbe9a0cf3eb33d33cfab5
refs/heads/master
<repo_name>haoankang/SpringA4<file_sep>/Chapter_16/src/main/java/ank/sixteen/config/DataConfig.java package ank.sixteen.config; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import javax.transaction.TransactionManager; import static org.springframework.beans.factory.annotation.Autowire.BY_NAME; @Configuration @EnableJpaRepositories(basePackages = "ank.sixteen.dao") public class DataConfig { @Bean public DataSource dataSource(){ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://10.100.1.210:3306/hak_test"); dataSource.setUsername("root"); dataSource.setPassword("<PASSWORD>"); dataSource.setInitialSize(2); dataSource.setMaxTotal(3); return dataSource; } @Bean public JpaVendorAdapter jpaVendorAdapter(){ HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setDatabase(Database.MYSQL); jpaVendorAdapter.setShowSql(true); jpaVendorAdapter.setGenerateDdl(false); jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL57Dialect"); return jpaVendorAdapter; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter){ LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource); entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter); entityManagerFactoryBean.setPackagesToScan("ank.sixteen.dto"); return entityManagerFactoryBean; } static class EMF{ @Autowired public EntityManagerFactory entityManagerFactory; @Bean public PlatformTransactionManager transactionManager(){ JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } } } <file_sep>/Chapter_13/src/main/java/t/l/repository/UserRepository.java package t.l.repository; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import t.l.dto.User; public interface UserRepository { public int addUser(User user); @Cacheable("kaka") public User queryById(Integer id); public int updateUser(User user); public int deleteUser(User user); @CacheEvict(value = "kaka", key = "#user.id") public void evictUser(User user); } <file_sep>/Chapter_15/src/main/java/ank/hao/webservice/config/RootConfig.java package ank.hao.webservice.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter; @Configuration @ComponentScan("ank.hao.webservice") public class RootConfig { @Bean public SimpleJaxWsServiceExporter jaxWsServiceExporter(){ SimpleJaxWsServiceExporter simpleJaxWsServiceExporter = new SimpleJaxWsServiceExporter(); simpleJaxWsServiceExporter.setBaseAddress("http://localhost:8888/services/"); return simpleJaxWsServiceExporter; } } <file_sep>/Chapter_13/src/test/java/t/l/repository/t/l/JdbcDemo.java package t.l.repository.t.l; import org.junit.Test; import t.l.dto.User; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class JdbcDemo { @Test public void test() throws Exception{ String url = "jdbc:mysql://10.100.1.210:3306/hak_test"; String user = "root"; String pwd = "<PASSWORD>"; //1. 注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2. 获取连接 Connection connection = DriverManager.getConnection(url,user,pwd); //3. 通过数据库连接操作数据库 PreparedStatement ps = connection.prepareStatement("select * from user"); ResultSet resultSet = ps.executeQuery(); //4. 遍历结果 while(resultSet.next()){ User user1 = new User(); user1.setId(resultSet.getInt("id")); user1.setName(resultSet.getString("name")); user1.setAge(resultSet.getInt("age")); System.out.println(user1); } resultSet.close(); ps.close(); connection.close(); } } <file_sep>/Chapter_15/src/test/java/ank/hao/hessian/DemoConfig.java package ank.hao.hessian; import ank.hao.hessian.service.PeopleService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.remoting.caucho.HessianProxyFactoryBean; @Configuration @ComponentScan("ank.hao.hessian") public class DemoConfig { @Bean public HessianProxyFactoryBean peopleService(){ HessianProxyFactoryBean proxyFactoryBean = new HessianProxyFactoryBean(); proxyFactoryBean.setServiceUrl("http://localhost:8080/people.service"); proxyFactoryBean.setServiceInterface(PeopleService.class); return proxyFactoryBean; } } <file_sep>/Chapter_15/src/main/java/ank/hao/webservice/service/PeopleService.java package ank.hao.webservice.service; import javax.jws.WebMethod; import javax.jws.WebService; @WebService public interface PeopleService { @WebMethod void say(); @WebMethod String study(); } <file_sep>/Chapter_11/src/main/java/ank/orm/hibernate/config/InitializeConfig.java package ank.orm.hibernate.config; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import javax.sql.DataSource; import java.util.Properties; @Configuration @ComponentScan("ank.orm.hibernate") public class InitializeConfig { @Bean public DataSource dataSource(){ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://10.100.1.210:3306/hak_test"); dataSource.setUsername("root"); dataSource.setPassword("<PASSWORD>"); dataSource.setInitialSize(2); dataSource.setMaxTotal(3); return dataSource; } @Bean public LocalSessionFactoryBean sessionFactoryBean(DataSource dataSource){ LocalSessionFactoryBean sfb = new LocalSessionFactoryBean(); sfb.setDataSource(dataSource); sfb.setPackagesToScan(new String[]{"ank.orm.hibernate.domain"}); Properties properties = new Properties(); properties.setProperty("hibernate.dialect","org.hibernate.dialect.H2Dialect"); sfb.setHibernateProperties(properties); return sfb; } @Bean public BeanPostProcessor persistenceTranslation(){ return new PersistenceExceptionTranslationPostProcessor(); } } <file_sep>/Chapter_16/src/test/java/ank/sixteen/controller/MessageConverterTest.java package ank.sixteen.controller; import ank.sixteen.dto.User; import net.bytebuddy.asm.Advice; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriTemplateHandler; import java.util.HashMap; import java.util.Map; @RunWith(SpringJUnit4ClassRunner.class) @SpringJUnitConfig(TestConfig.class) public class MessageConverterTest { @Autowired private RestTemplate restTemplate; @Test public void test(){ ResponseEntity<User> responseEntity = restTemplate.getForEntity("http://localhost:8081/user/getUserById/3",User.class, (Object) null); System.out.println("kaf"); } } @Configuration class TestConfig{ @Bean public RestTemplate restTemplate(){ RestTemplate restTemplate = new RestTemplate(); Map<String,String> map = new HashMap<>(); //map.put("url","http://localhost:8081"); restTemplate.setDefaultUriVariables(map); return restTemplate; } } <file_sep>/Chapter_11/src/main/java/ank/orm/jpa/config/InitializeConfig.java package ank.orm.jpa.config; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import javax.inject.Inject; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.util.Properties; @Configuration @ComponentScan("ank.orm.jpa") //@EnableTransactionManagement @EnableJpaRepositories(basePackages = "ank.orm.jpa.repository", entityManagerFactoryRef = "entityManagerFactoryBean") public class InitializeConfig { @Bean public DataSource dataSource(){ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://10.100.1.210:3306/hak_test"); dataSource.setUsername("root"); dataSource.setPassword("<PASSWORD>"); dataSource.setInitialSize(2); dataSource.setMaxTotal(3); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter){ LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource); entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter); entityManagerFactoryBean.setPersistenceUnitName("user"); entityManagerFactoryBean.setPackagesToScan("ank.orm.jpa.domain"); return entityManagerFactoryBean; } @Bean public JpaVendorAdapter jpaVendorAdapter(){ HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); adapter.setDatabase(Database.MYSQL); adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect"); adapter.setShowSql(true); adapter.setGenerateDdl(false); return adapter; } @Bean public BeanPostProcessor beanPostProcessor(){ return new PersistenceExceptionTranslationPostProcessor(); } @Bean public PersistenceAnnotationBeanPostProcessor beanPostProcessor2(){ return new PersistenceAnnotationBeanPostProcessor(); } @Bean public JpaTransactionManager transactionManager() { return new JpaTransactionManager(); // does this need an emf??? } // @Configuration // @EnableTransactionManagement // public static class TransactionConfig implements TransactionManagementConfigurer { // @Inject // private EntityManagerFactory entityManagerFactoryBean; // // public PlatformTransactionManager annotationDrivenTransactionManager() { // JpaTransactionManager transactionManager = new JpaTransactionManager(); // transactionManager.setEntityManagerFactory(entityManagerFactoryBean); // return transactionManager; // } // } } <file_sep>/Chapter_14/src/main/java/thirteen/config/SecurityConfig.java package thirteen.config; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends GlobalMethodSecurityConfiguration{ @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("<PASSWORD>").roles("USER"); } } <file_sep>/Chapter_15/src/main/java/ank/hao/webservice/config/ServletConfig.java package ank.hao.webservice.config; import ank.hao.hessian.service.PeopleService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.remoting.caucho.HessianServiceExporter; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import java.util.Properties; @Configuration public class ServletConfig extends WebMvcConfigurationSupport { } <file_sep>/Chapter_16/src/main/java/ank/sixteen/service/UserService.java package ank.sixteen.service; import ank.sixteen.dto.User; import java.util.List; public interface UserService { List<User> queryList(); User getUserById(Integer id); } <file_sep>/Chapter_09/src/main/java/ank/hao/config/RootConfig.java package ank.hao.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("ank.hao.security") public class RootConfig { } <file_sep>/Chapter_11/src/main/java/ank/orm/hibernate/repository/HibernateUserRepository.java package ank.orm.hibernate.repository; import ank.orm.hibernate.domain.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class HibernateUserRepository implements UserRepository { @Autowired private SessionFactory sessionFactory; private Session getSession(){ return sessionFactory.openSession(); } public void add(User user) { getSession().saveOrUpdate(user); } public int update(User user) { return 0; } public int delete(User user) { return 0; } } <file_sep>/Chapter_16/src/main/java/ank/sixteen/service/UserServiceImpl.java package ank.sixteen.service; import ank.sixteen.dao.UserDao; import ank.sixteen.dto.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public List<User> queryList() { return userDao.findAll(); } @Override public User getUserById(Integer id) { return userDao.findById(id).get(); } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ank.hao</groupId> <artifactId>SpringA4</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>Chapter_07</module> <module>Chapter_08</module> <module>Chapter_09</module> <module>Chapter_10</module> <module>Chapter_11</module> <module>Chapter_12</module> <module>Chapter_13</module> <module>Chapter_14</module> <module>Chapter_16</module> <module>Chapter_15</module> <module>Chapter_21</module> </modules> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!--&lt;!&ndash; https://mvnrepository.com/artifact/org.springframework/spring-context &ndash;&gt; <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.4.RELEASE</version> </dependency> &lt;!&ndash; https://mvnrepository.com/artifact/org.springframework/spring-webmvc &ndash;&gt; <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.4.RELEASE</version> </dependency> &lt;!&ndash; https://mvnrepository.com/artifact/ch.qos.logback/logback-classic &ndash;&gt; <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> <scope>test</scope> </dependency> &lt;!&ndash; https://mvnrepository.com/artifact/junit/junit &ndash;&gt; <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> &lt;!&ndash; https://mvnrepository.com/artifact/org.springframework/spring-test &ndash;&gt; <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.4.RELEASE</version> <scope>test</scope> </dependency> &lt;!&ndash; https://mvnrepository.com/artifact/org.slf4j/slf4j-api &ndash;&gt; <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> &lt;!&ndash; https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api &ndash;&gt; <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0</version> <scope>provided</scope> </dependency>--> </dependencies> </project><file_sep>/Chapter_11/src/test/JpaDemo.java import ank.orm.jpa.config.InitializeConfig; import ank.orm.jpa.domain.User; import ank.orm.jpa.repository.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceUnit; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = InitializeConfig.class) public class JpaDemo { @PersistenceContext private EntityManager entityManager; @Autowired private UserRepository userRepository; @Test public void test(){ User user = new User("jpa",46); userRepository.saveAndFlush(user); System.out.println("kaka"); } } <file_sep>/Chapter_15/src/main/java/ank/hao/webservice/WSServer.java package ank.hao.webservice; import ank.hao.webservice.config.RootConfig; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter; public class WSServer { public static void main(String[] args) throws InterruptedException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RootConfig.class); SimpleJaxWsServiceExporter exporter = context.getBean(SimpleJaxWsServiceExporter.class); exporter.publishEndpoints(); Thread.sleep(1000000000); } } <file_sep>/Chapter_15/src/main/java/ank/hao/hessian/config/ServletConfig.java package ank.hao.hessian.config; import ank.hao.hessian.service.PeopleService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.remoting.caucho.HessianServiceExporter; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import java.util.Properties; @Configuration @ComponentScan("ank.hao.hessian") public class ServletConfig extends WebMvcConfigurationSupport { @Bean public HessianServiceExporter hessianServiceExporter(PeopleService peopleService){ HessianServiceExporter hessianServiceExporter = new HessianServiceExporter(); hessianServiceExporter.setService(peopleService); hessianServiceExporter.setServiceInterface(PeopleService.class); return hessianServiceExporter; } @Bean public HandlerMapping handlerMapping(){ SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); Properties mappings = new Properties(); mappings.setProperty("/people.service","hessianServiceExporter"); mapping.setMappings(mappings); return mapping; } } <file_sep>/Chapter_21/src/main/resources/application.properties management.endpoints.enabled-by-default=true spring.datasource.url=jdbc:mysql://10.100.1.210:3306/hak_test spring.datasource.username=root spring.datasource.password=<PASSWORD><file_sep>/Chapter_16/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>SpringA4</artifactId> <groupId>ank.hao</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>Chapter_16</artifactId> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>2.0.7.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.3.0</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <!-- https://mvnrepository.com/artifact/org.eclipse.persistence/javax.persistence --> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> <version>2.2.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.3.0.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> </dependencies> </project><file_sep>/Chapter_11/src/test/HibernateDemo.java import ank.orm.hibernate.config.InitializeConfig; import ank.orm.hibernate.domain.User; import ank.orm.hibernate.repository.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringJUnitConfig(InitializeConfig.class) public class HibernateDemo { @Autowired private UserRepository userRepository; @Test public void test(){ User user = new User("hibernate",45); userRepository.add(user); } } <file_sep>/Chapter_16/src/main/java/ank/sixteen/controller/UserController.java package ank.sixteen.controller; import ank.sixteen.dto.User; import ank.sixteen.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/list") public String list(ModelMap modelMap){ modelMap.put("list",userService.queryList()); return "home"; } @RequestMapping(value = "/getUserById/{id}", method = RequestMethod.GET) @ResponseBody public User getUserById(@PathVariable Integer id){ User user = null; user = userService.getUserById(id); return user; } } <file_sep>/Chapter_14/src/main/java/thirteen/service/UserService.java package thirteen.service; public interface UserService { public void testSecured(); } <file_sep>/Chapter_15/src/main/java/ank/hao/webservice/service/PeopleServiceEndpoint.java //package ank.hao.webservice.service; // //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.stereotype.Component; // //import javax.jws.WebMethod; //import javax.jws.WebService; // //@Component //@WebService(serviceName = "PeopleService") //public class PeopleServiceEndpoint { // // @Autowired // private PeopleService peopleService; // // @WebMethod // public void say(){ // peopleService.say(); // } // // @WebMethod // public String study(){ // return peopleService.study(); // } //} <file_sep>/Chapter_16/src/test/java/ank/sixteen/controller/UserControllerTest.java package ank.sixteen.controller; import ank.sixteen.config.InitialConfig; import ank.sixteen.dto.User; import ank.sixteen.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvcBuilder; import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; import org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @SpringJUnitWebConfig(InitialConfig.class) public class UserControllerTest { @Autowired private UserService userService; @Test public void test(){ List<User> list = userService.queryList(); System.out.println(list); } }
3b9caf21332cd96fae5d3973c131573cfe93d9b7
[ "Java", "Maven POM", "INI" ]
26
Java
haoankang/SpringA4
8b4aaf1b545a775ee60e02efac493ffaf962186f
ce7e72e6376369eeadf548bfa008a933cc210ed2
refs/heads/master
<file_sep>/** * Created by sasha on 22.07.17. */ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; @Entity @Table(name = "points") public class Point implements Serializable{ @Id @Column(name="id") private long id; @Column(name="x") private float x; @Column(name="y") private float y; @Column(name="r") private float r; @Column(name="isin") private boolean isInside; public Point() {} public Point(float x, float y, float r){ this.x=x; this.y=y; this.r=r; isInside=true; } public boolean isInside() { return isInside; } public void setInside(float r) { if(check(r)) isInside=true; else isInside=false; } public long getId() { return id; } public void setId(long id) { this.id = id; } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public float getR() { return r; } public void setR(float r) { this.r = r; } public boolean check(float r){ if(x>=-r&&x<=0){ if(y<r&&y>0){ return true; } if((x*x+y*y)<=r*r) { return true; } } if(x>=0 &&x<=r/2){ if(y>=0&&y<=(-2*x+2)){ return true; } } return false; } }<file_sep>import Ember from 'ember'; export default Ember.Controller.extend({ init:function(){ this._super(); }, points:[], usl:true, xVal: 1, yVal: '', rVal: 2, img:'', isValid : Ember.computed.match('yVal',/^[-+]?[0-9]+([\.,]?[0-9]+)?$/), isDisabled: Ember.computed.not('isValid'), requestURL: 'http://localhost:8080/lab9backend_war_exploded', ajax: Ember.inject.service(), onload:function() { Ember.$.ajax({ type: "GET", url: "http://localhost:8080/lab8Maven_war_exploded/rest/point/img", dataType: "json", crossDomain: true, success: function (data) { this.set("img",data.responseText) //this.set("img",JSON.parse(data)); }.bind(this), error:function(data){ this.set("img",data.responseText); }.bind(this) }); Ember.$.ajax({ type: "GET", url: "http://localhost:8080/lab8Maven_war_exploded/rest/point/getPoints", dataType: "json", crossDomain: true, success: function (data) { this.set("points",data); }.bind(this), error:function(data){ this.set("points",data); }.bind(this) }); }.on('init'), actions: { setX: function (value) { this.set("xVal", value); //Ember.$('.initbtn').trigger('click'); }, setR: function (value) { this.set("rVal", value) }, setY: function (value) { this.set("yVal", value) }, clearButton(){ Ember.$.ajax({ type: "GET", url: "http://localhost:8080/lab8Maven_war_exploded/rest/point/reset", dataType: "json", crossDomain: true, success: function () { //alert(data); this.onload(); }.bind(this) }); } } }); <file_sep>/** * Created by sasha on 17.08.17. */ public class CheckPoints { } <file_sep> import org.hibernate.Session; import javax.ejb.Stateless; import javax.faces.convert.Converter; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.Query; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Stateless public class DBOperations implements Serializable { public void addPoint(Point point){ EntityManager em= HibernateUtil.getEntityManager(); em.getTransaction().begin(); em.persist(point); em.getTransaction().commit(); } public void deleteAllPoints(){ EntityManager em= HibernateUtil.getEntityManager(); em.getTransaction().begin(); Query query=em.createNativeQuery("DELETE FROM points"); query.executeUpdate(); em.getTransaction().commit(); } public ArrayList<Point> readAllTable(){ EntityManager em= HibernateUtil.getEntityManager(); em.getTransaction().begin(); ArrayList<Point> points=new ArrayList<Point>(); Query query=em.createQuery("SELECT p from Point p "); em.getTransaction().commit(); List list =query.getResultList(); for(Object obj : list) points.add((Point)obj); return points; } public void addUser(LabUser user) { EntityManager em= HibernateUtil.getEntityManager(); em.getTransaction().begin(); em.persist(user); em.getTransaction().commit(); } public boolean userExists(String userName){ EntityManager em= HibernateUtil.getEntityManager(); em.getTransaction().begin(); Query query=em.createQuery("SELECT l FROM LabUser l WHERE login='"+userName+"'"); em.getTransaction().commit(); List list =query.getResultList(); if(list.isEmpty()) return false; else return true; } public boolean checkPassword(LabUser user){ EntityManager em= HibernateUtil.getEntityManager(); em.getTransaction().begin(); Query query=em.createQuery("SELECT l FROM LabUser l WHERE login='"+user.getLogin()+"'"); em.getTransaction().commit(); List list =query.getResultList(); for(Object obj : list){ if(((LabUser)obj).getPassword().equals(user.getPassword())) return true; } return false; } } <file_sep># lab9 Ember+EJB lab8Maven => backend lab9 => frontend <file_sep>import Ember from 'ember'; export default Ember.Controller.extend({ login:'', password:'', repeated:'', notValidLogin:Ember.computed.empty('login'), notValidPassword:Ember.computed.empty('password'), isValidRepeated:Ember.computed.equal('repeated','password'), notValidRepeated:Ember.computed.not('isValidRepeated'), disableLogin:Ember.computed.or('notValidLogin','notValidPassword'), disableRegister:Ember.computed.or('disableLogin','isValidRepeated'), actions:{ btnRegister(login,password){ Ember.$.ajax({ type: "GET", url: "http://localhost:8080/lab8Maven_war_exploded/rest/point/addUser/" + login + "/" + password, dataType: "json", crossDomain: true, success: function (data) { if(data) alert("registered"); else alert("login already exists"); } }); }, btnLogin(login,password){ Ember.$.ajax({ type: "GET", url: "http://localhost:8080/lab8Maven_war_exploded/rest/point/checkUser/" + login + "/" + password, dataType: "json", crossDomain: true, success: function (data) { if(data){ this.transitionToRoute('main-page'); } else alert("no"); }.bind(this) }); } } }); <file_sep>import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by sasha on 17.08.17. */ @Entity @Table(name = "users") public class LabUser implements Serializable { @Id @Column(name="id") private long id; @Column(name="login") private String login; @Column(name="password") private String password; public LabUser(){} public LabUser(String login,String password){ this.login=login; try { MessageDigest messageDigest=MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(password.getBytes(Charset.forName("UTF8"))); byte[] resultByte=messageDigest.digest(); this.password= new String(Hex.encodeHex(resultByte)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } } <file_sep>import Ember from 'ember'; export default Ember.Route.extend({ actions:{ submitButton(x,y,r){ Ember.$.ajax({ type: "GET", url: "http://localhost:8080/lab8Maven_war_exploded/rest/point/add/" + x + "/" + y + "/" + r, dataType: "json", crossDomain: true, success: function () { //this.controllerFor('main-page').set("points",data); this.controllerFor('main-page').onload(); }.bind(this) }); }, imgClick(){ var r=this.controllerFor('main-page').get("rVal"); var x=Number(((event.offsetX-190)*r/136).toFixed(2)); var y=Number(((190-event.offsetY)*r/136).toFixed(2)); this.send("submitButton",x,y,r) }, exitButton(){ this.transitionTo('index'); } } });
36fd50836cc6b49af3c0c71aec400057e0d8cd27
[ "JavaScript", "Java", "Markdown" ]
8
Java
AleksandrFomin/lab9
376dfed63f5bfc1c121fe802ec4f132d1fc27098
7ba722c2894a4515aeb2496a1a83c5aae49423e6
refs/heads/master
<repo_name>bpourkazemi/dotfiles<file_sep>/README.md # Dotfiles My repository of dotfiles to use across hosts <file_sep>/install.sh #! /bin/sh if [ ! -f dot_vimrc ]; then # Remote installation echo "\033[0;34mCloning dotfiles...\033[0m" hash git >/dev/null && /usr/bin/env git clone https://github.com/rodrigosetti/dotfiles.git $HOME/dev/github/.dotfiles || { echo "git not installed" exit } cd $HOME/.dotfiles fi # For every dot_* file in installation for REP_FILE in `ls -d dot_*`; do DOT_FILE=`echo "$REP_FILE" | sed 's/^dot_/./'` # If file in home directory is a link, then we remove it if [ -L "$HOME/$DOT_FILE" ]; then rm -v "$HOME/$DOT_FILE" fi # If file in home does not exists as file or directory, create the link if [ ! -f "$HOME/$DOT_FILE" -a ! -d "$HOME/$DOT_FILE" ]; then ln -vs "`pwd`/$REP_FILE" "$HOME/$DOT_FILE" else echo "File exists and is not a link, not writing: $HOME/$DOT_FILE" > /dev/stderr fi done ###### Installs vim-plug curl -fLo $HOME/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim ###### Installs oh-my-zsh if [ ! -d $HOME/.oh-my-zsh ]; then curl -L http://install.ohmyz.sh | sh fi
cba7addf44cb41ebeb45c696bac159b657267b64
[ "Markdown", "Shell" ]
2
Markdown
bpourkazemi/dotfiles
a6e304561248ed130b22fb4a44f793d8d062b7b6
b7e92803f206fab8b50571c0d19d242b061aead5
refs/heads/master
<repo_name>muizidn/AppSPM<file_sep>/Sources/StaticLib/include/staticlib.h ../../../StaticLib/includes/staticlib.h<file_sep>/StaticLib/src/staticlib.c #include <stdio.h> #include "staticlib.h" void run_from_staticlib(void) { printf("This is from StaticLib\n"); }<file_sep>/Sources/App/UsingNIO.swift import Foundation import NIO <file_sep>/Sources/cli/main.swift import Foundation import App App().run() <file_sep>/Sources/CxxWrapper/cxxwrapper.cpp #include "cxxwrapper.h" #include "../CxxLib/cxxlib.h" void run_from_cxxwrapper(void) { cxxlib::run_from_cxx(); }<file_sep>/Sources/CLib/clib.h void run_from_c(void);<file_sep>/Sources/App/App.swift import Foundation import CLib import CxxWrapper import StaticLib public struct App { public init() {} public func run() { run_from_c() run_from_cxxwrapper() run_from_staticlib() } } <file_sep>/Sources/CxxLib/cxxlib.cpp #include <iostream> #include "cxxlib.h" namespace cxxlib { void run_from_cxx(void) { #if UPPERCASE std::cout << "THIS ONE FROM CXXLIB" << std::endl; #else std::cout << "This one from CxxLib" << std::endl; #endif } }<file_sep>/Rakefile task :staticlib do Dir.chdir "StaticLib" puts `rm *.o` puts `rm *.a` puts `clang -c src/staticlib.c` puts `ar rcs staticlib.a staticlib.o` Dir.chdir '..' puts "task: staticlib done" end def carthage_options kOpts = [ "--cache-builds", "--no-use-binaries", "--platform", "macOS" ] kOpts.map { |i| i }.join(" ") end task :carthagebuild do puts `carthage update #{carthage_options}` puts "task: carthagebuild done" end def swift_options kOpts = { "-Xswiftc" => [ "-F./Carthage/Build/Mac" ], "-Xlinker" => [ "./StaticLib/staticlib.a", "-rpath", "./Carthage/Build/Mac" ] } kOpts.map { |key, value| value.map { |i| "#{key} #{i}" }.join(" ") }.join(" ") end task :swiftbuild do puts `swift build #{swift_options}` puts "task: swiftbuild done" end task :run do puts "task: run starts" puts `./.build/x86_64-apple-macosx/debug/app` end task :bootstrap do puts `carthage update --no-build` dirs = Dir.glob("Carthage/Checkouts/**").select { |f| File.directory? f } dirs.each do |dir| kPackageManifest = Dir.glob("#{dir}/Package.swift") kXcodeproj = Dir.glob("#{dir}/*.xcodeproj") if kXcodeproj.empty? && !kPackageManifest.empty? pwd = Dir.pwd Dir.chdir dir puts `swift package generate-xcodeproj` Dir.chdir pwd end end puts "task: bootstrap done" end<file_sep>/README.md # App A description of this package. http://ankit.im/swift/2016/05/21/creating-objc-cpp-packages-with-swift-package-manager/<file_sep>/StaticLib/src/staticlib.h ../includes/staticlib.h<file_sep>/Sources/CLib/clib.c #include <stdio.h> #include "clib.h" void run_from_c(void) { #if UPPERCASE printf("THIS ONE FROM CLIB\n"); #else printf("This one from Clib\n"); #endif }<file_sep>/StaticLib/includes/staticlib.h void run_from_staticlib(void);<file_sep>/Sources/CxxLib/cxxlib.h namespace cxxlib { void run_from_cxx(void); }
ee2dd1402c479b3d6e2ccb17d4fab876a89b079e
[ "Ruby", "Swift", "Markdown", "C", "C++" ]
14
C
muizidn/AppSPM
390f6918d6b44d5952b0abe8a4433016e197d766
01b6ee1d60916df60e134d5df0d1d475bf152d03
refs/heads/master
<file_sep> public enum Aggregation: Hashable { case avg(Expression, distinct: Bool) case count(Expression?, distinct: Bool) case min(Expression, distinct: Bool) case max(Expression, distinct: Bool) case sample(Expression, distinct: Bool) case sum(Expression, distinct: Bool) case groupConcat(Expression, distinct: Bool, separator: String?) public var distinct: Bool { switch self { case .avg(_, let distinct), .count(_, let distinct), .min(_, let distinct), .max(_, let distinct), .sample(_, let distinct), .sum(_, let distinct), .groupConcat(_, let distinct, _): return distinct } } public var expression: Expression? { switch self { case .count(let expression, _): return expression case .avg(let expression, _), .min(let expression, _), .max(let expression, _), .sample(let expression, _), .sum(let expression, _), .groupConcat(let expression, _, _): return expression } } } extension Aggregation: SPARQLSerializable { private var sparqlFunctionName: String { switch self { case .avg: return "AVG" case .count: return "COUNT" case .min: return "MIN" case .max: return "MAX" case .sample: return "SAMPLE" case .sum: return "SUM" case .groupConcat: return "GROUP_CONCAT" } } public func serializeToSPARQL(depth: Int, context: Context) throws -> String { var inner = distinct ? "DISTINCT " : "" if let expression = expression { inner += try expression.serializeToSPARQL(depth: 0, context: context) } else { inner += "*" } if case let .groupConcat(_, _, separator?) = self { let escapedSeparator = separator .replacingOccurrences(of:"\"", with: "\\\"") inner += "; SEPARATOR=\"\(escapedSeparator)\"" } return "\(sparqlFunctionName)(\(inner))" } } <file_sep>import XCTest @testable import SPARQL import DiffedAssertEqual final class SPARQLTests: XCTestCase { func testBasic() throws { let query = Query(op: .project( ["a"], .bgp([ Triple( subject: .iri("a"), predicate: .node(.iri(RDF.type)), object: .literal(.withDatatype("1", .integer)) ), ]) ) ) let context = Context(prefixMapping: [ "rdf": RDF.base, "xsd": XSD.base, ]) let result = try query.serializeToSPARQL(depth: 0, context: context) let expected = """ SELECT ?a { <a> a 1 . } """ diffedAssertEqual( expected.trimmingCharacters(in: .whitespacesAndNewlines), result.trimmingCharacters(in: .whitespacesAndNewlines) ) } func testProjectFilterIsNotHaving() throws { let query = Query(op: .project( ["a"], .filter( .equals(.node(.variable("a")), .node(.true)), .bgp([ Triple( subject: .variable("a"), predicate: .node(.iri(RDF.type)), object: .literal(.withDatatype("1", .integer)) ), ]) ) ) ) let context = Context(prefixMapping: [ "rdf": RDF.base, "xsd": XSD.base, ]) let result = try query.serializeToSPARQL(depth: 0, context: context) let expected = """ SELECT ?a { ?a a 1 . FILTER (?a = true) } """ diffedAssertEqual( expected.trimmingCharacters(in: .whitespacesAndNewlines), result.trimmingCharacters(in: .whitespacesAndNewlines) ) } func testComplex() throws { let query = Query(op: .distinct( .project( ["a"], .orderBy( .union( .minus( .join( .filter( .and( .equals(.node(.variable("a")), .node(.literal(.plain("foo")))), .not(.functionCall("isIRI", [.node(.variable("a"))])) ), .bgp([ Triple( subject: .iri("a"), predicate: .node(.iri(RDF.type)), object: .literal(.withDatatype("1", .integer)) ), Triple( subject: .variable("1"), predicate: .path(.negated([.forward(RDF.type)])), object: .literal(.withLanguage("test", "en")) ), ]) ), .bgp([ Triple( subject: .variable("a"), predicate: .node(.variable("b")), object: .variable("c") ) ]) ), .bgp([ Triple( subject: .iri("x"), predicate: .node(.iri("y")), object: .iri("z") ) ]) ), .leftJoin( .bgp([ Triple( subject: .iri("a"), predicate: .node(.iri("b")), object: .iri("c") ) ]), .bgp([ Triple( subject: .iri("d"), predicate: .node(.iri("e")), object: .literal(.withDatatype("1999", .custom(XSD.gYear))) ) ]), .node(.literal(.withDatatype("true", .boolean))) ) ), [ OrderComparator(order: .ascending, expression: .node(.variable("a"))), OrderComparator(order: .descending, expression: .node(.variable("b"))), ] ) ) ) ) let context = Context(prefixMapping: [ "rdf": RDF.base, "xsd": XSD.base, ]) let result = try query.serializeToSPARQL(depth: 0, context: context) let expected = """ SELECT DISTINCT ?a { { <a> a 1 . ?1 !a "test"@en . FILTER ((?a = "foo") && !isIRI(?a)) ?a ?b ?c . MINUS { <x> <y> <z> . } } UNION { <a> <b> <c> . OPTIONAL { <d> <e> "1999"^^xsd:gYear . FILTER true } } } ORDER BY ASC(?a) DESC(?b) """ diffedAssertEqual( expected.trimmingCharacters(in: .whitespacesAndNewlines), result.trimmingCharacters(in: .whitespacesAndNewlines) ) } func testNestedProject() throws { let query = Query(op: .project( ["a"], .join( .project( ["b"], .bgp([ Triple( subject: .variable("b"), predicate: .node(.iri("foo")), object: .literal(.withLanguage("test", "en")) ) ]) ), .bgp([ Triple( subject: .variable("a"), predicate: .node(.iri("bar")), object: .literal(.withDatatype("1", .integer)) ) ]) ) ) ) let context = Context(prefixMapping: [ "rdf": RDF.base, "xsd": XSD.base, ]) let result = try query.serializeToSPARQL(depth: 0, context: context) let expected = """ SELECT ?a { { SELECT ?b { ?b <foo> "test"@en . } } ?a <bar> 1 . } """ diffedAssertEqual( expected.trimmingCharacters(in: .whitespacesAndNewlines), result.trimmingCharacters(in: .whitespacesAndNewlines) ) } func testNestedDistinct() throws { let query = Query(op: .project( ["a"], .join( .distinct( .project( ["b"], .bgp([ Triple( subject: .variable("b"), predicate: .node(.iri("foo")), object: .literal(.withLanguage("test", "en")) ) ]) ) ), .bgp([ Triple( subject: .variable("a"), predicate: .node(.iri("bar")), object: .literal(.withDatatype("1", .integer)) ) ]) ) ) ) let context = Context(prefixMapping: [ "rdf": RDF.base, "xsd": XSD.base, ]) let result = try query.serializeToSPARQL(depth: 0, context: context) let expected = """ SELECT ?a { { SELECT DISTINCT ?b { ?b <foo> "test"@en . } } ?a <bar> 1 . } """ diffedAssertEqual( expected.trimmingCharacters(in: .whitespacesAndNewlines), result.trimmingCharacters(in: .whitespacesAndNewlines) ) } func testNestedDirectProject() throws { let query = Query(op: .project( ["a"], .project( ["b"], .bgp([ Triple( subject: .variable("b"), predicate: .node(.iri("foo")), object: .literal(.withLanguage("test", "en")) ) ]) ) ) ) let context = Context(prefixMapping: [ "rdf": RDF.base, "xsd": XSD.base, ]) let result = try query.serializeToSPARQL(depth: 0, context: context) let expected = """ SELECT ?a { { SELECT ?b { ?b <foo> "test"@en . } } } """ diffedAssertEqual( expected.trimmingCharacters(in: .whitespacesAndNewlines), result.trimmingCharacters(in: .whitespacesAndNewlines) ) } func testGroup() throws { let query = Query(op: .project( ["a"], .group( .bgp([ Triple( subject: .variable("b"), predicate: .node(.iri("foo")), object: .literal(.withLanguage("test", "en")) ) ]), ["b", "f"], [ "c": .count(.node(.variable("d")), distinct: true), "d": .count(nil, distinct: true), "e": .groupConcat(.node(.variable("x")), distinct: false, separator: "|") ] ) ) ) let context = Context(prefixMapping: [ "rdf": RDF.base, "xsd": XSD.base, ]) let result = try query.serializeToSPARQL(depth: 0, context: context) let expected = """ SELECT ?a (COUNT(DISTINCT ?d) AS ?c) (COUNT(DISTINCT *) AS ?d) (GROUP_CONCAT(?x; SEPARATOR="|") AS ?e) { ?b <foo> "test"@en . } GROUP BY ?b ?f """ diffedAssertEqual( expected.trimmingCharacters(in: .whitespacesAndNewlines), result.trimmingCharacters(in: .whitespacesAndNewlines) ) } func testFilterGroup() throws { let query = Query(op: .project( ["a"], .filter( .equals(.node(.variable("a")), .node(.literal(.plain("foo")))), .group( .bgp([ Triple( subject: .variable("b"), predicate: .node(.iri("foo")), object: .literal(.withLanguage("test", "en")) ) ]), ["b", "f"], [ "c": .count(.node(.variable("d")), distinct: true), "d": .count(nil, distinct: true), "e": .groupConcat(.node(.variable("x")), distinct: false, separator: "|") ] ) ) ) ) let context = Context(prefixMapping: [ "rdf": RDF.base, "xsd": XSD.base, ]) let result = try query.serializeToSPARQL(depth: 0, context: context) let expected = """ SELECT ?a (COUNT(DISTINCT ?d) AS ?c) (COUNT(DISTINCT *) AS ?d) (GROUP_CONCAT(?x; SEPARATOR="|") AS ?e) { ?b <foo> "test"@en . } GROUP BY ?b ?f HAVING (?a = "foo") """ diffedAssertEqual( expected.trimmingCharacters(in: .whitespacesAndNewlines), result.trimmingCharacters(in: .whitespacesAndNewlines) ) } } <file_sep>import XCTest import SPARQLTests var tests = [XCTestCaseEntry]() tests += SPARQLTests.__allTests() XCTMain(tests) <file_sep> public protocol SPARQLSerializable { func serializeToSPARQL(depth: Int, context: Context) throws -> String } <file_sep>public enum Predicate: Equatable { case node(Node) case path(Path) } extension Predicate: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) -> String { switch self { case let .node(node): return node.serializeToSPARQL(depth: depth, context: context) case let .path(path): return path.serializeToSPARQL(depth: depth, context: context) } } } <file_sep> public enum NegatedIRI: Equatable { case forward(String) case reverse(String) public var iri: String { switch self { case let .forward(iri): return iri case let .reverse(iri): return iri } } } extension NegatedIRI: CustomStringConvertible { public var description: String { let serialized = "<\(iri)>" switch self { case .forward: return serialized case .reverse: return "^\(serialized)" } } } extension NegatedIRI: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) -> String { let iri = self.iri let serialized: String if iri == RDF.type { serialized = "a" } else if let (prefix, suffix) = context.findPrefixMapping(iri: iri) { serialized = "\(prefix):\(suffix)" } else { serialized = "<\(iri)>" } switch self { case .forward: return serialized case .reverse: return "^\(serialized)" } } } <file_sep> public struct RDF { public static let base = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" public static let type = base + "type" } <file_sep> public struct OrderComparator: Equatable { public var order: Order public var expression: Expression public init(order: Order, expression: Expression) { self.order = order self.expression = expression } } extension OrderComparator: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) throws -> String { let serializedOrder = try order.serializeToSPARQL(depth: 0, context: context) let serializedExpression = try expression.serializeToSPARQL(depth: 0, context: context) return "\(serializedOrder)(\(serializedExpression))" } } <file_sep> public enum Node: Hashable { case variable(String) case blank(String) case iri(String) case literal(Literal) public static var `true`: Node { return .literal(.withDatatype("true", Datatype.boolean)) } public static var `false`: Node { return .literal(.withDatatype("false", Datatype.boolean)) } } extension Node: CustomStringConvertible { public var description: String { switch self { case let .variable(name): return "?\(name)" case let .blank(id): return "_:\(id)" case .iri(RDF.type): return "a" case let .iri(iri): return "<\(iri)>" case let .literal(literal): return literal.description } } } extension Node: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) -> String { if self == .iri(RDF.type) { return "a" } if case let .iri(iri) = self, let (prefix, suffix) = context.findPrefixMapping(iri: iri) { return "\(prefix):\(suffix)" } if case let .literal(literal) = self { return literal.serializeToSPARQL(depth: depth, context: context) } return description } } <file_sep> public enum Datatype: Hashable { case string case boolean case integer case float case double case decimal case date case dateTime case custom(String) public var iri: String { switch self { case .string: return XSD.string case .boolean: return XSD.boolean case .integer: return XSD.integer case .float: return XSD.float case .double: return XSD.double case .decimal: return XSD.decimal case .date: return XSD.date case .dateTime: return XSD.dateTime case .custom(let iri): return iri } } public init(iri: String) { switch iri { case XSD.string: self = .string case XSD.boolean: self = .boolean case XSD.integer: self = .integer case XSD.float: self = .float case XSD.double: self = .double case XSD.decimal: self = .decimal case XSD.date: self = .date case XSD.dateTime: self = .dateTime default: self = .custom(iri) } } } extension Datatype: CustomStringConvertible{ public var description: String { return "<\(iri)>" } } extension Datatype: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) -> String { if let (prefix, suffix) = context.findPrefixMapping(iri: iri) { return "\(prefix):\(suffix)" } return description } } <file_sep> public struct XSD { public static let base = "http://www.w3.org/2001/XMLSchema#" public static let string = base + "string" public static let boolean = base + "boolean" public static let integer = base + "integer" public static let float = base + "float" public static let double = base + "double" public static let decimal = base + "decimal" public static let date = base + "date" public static let dateTime = base + "dateTime" public static let gYear = base + "gYear" public static let gMonth = base + "gMonth" public static let gDay = base + "gDay" public static let gYearMonth = base + "gYearMonth" public static let gMonthDay = base + "gMonthDay" } <file_sep>[![Build Status](https://travis-ci.org/turbolent/SPARQL.svg?branch=master)](https://travis-ci.org/turbolent/SPARQL) # SPARQL SPARQL algebra and SPARQL syntax serialization <file_sep>public struct Query: Equatable { public var op: Op public init(op: Op) { self.op = op } } extension Query: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) throws -> String { let indentation = indent(depth: depth) var result = indentation result += "SELECT " switch op { case .orderBy, .project, .distinct: result += try op.serializeToSPARQL(depth: depth, context: context) default: result += "* {\n" result += try op.serializeToSPARQL(depth: depth + 1, context: context) result += indentation result += "}\n" } return result } } <file_sep> // possible nesting: distinct? project orderBy? filter? group? public indirect enum Op: Equatable { case identity case distinct(Op) case project([String], Op) case orderBy(Op, [OrderComparator]) case filter(Expression, Op) case group(Op, [String], [String: Aggregation]) case bgp([Triple]) case union(Op, Op) case minus(Op, Op) case leftJoin(Op, Op, Expression?) case join(Op, Op) } extension Op: SPARQLSerializable { public enum SPARQLSerializationError: Error { case unimplemented case unsupportedChildOp } public func serializeToSPARQL(depth: Int, context: Context) throws -> String { let indentation = indent(depth: depth) func nest(_ nested: SPARQLSerializable, depth: Int) throws -> String { var depth = depth var result = "" let nestedOp = nested as? Op let isSubquery = nestedOp .map { self.isSubquery(nested: $0) } ?? false let indentation = indent(depth: depth) if isSubquery { result += indentation result += "{\n" result += indentation result += " SELECT " depth += 1 } if nestedOp?.isHaving(parent: self) ?? false, case let .filter(expression, op)? = nestedOp { // if child op is group it will add the block switch op { case .group: result += try nest(op, depth: depth) default: result += " {\n" result += try nest(op, depth: depth + 1) result += indentation result += "}\n" } result += indentation result += "HAVING " result += try nest(expression, depth: 0) result += "\n" } else { result += try nested.serializeToSPARQL(depth: depth, context: context) } if isSubquery { result += indentation result += "}\n" } return result } switch self { case .identity: return "" case let .bgp(triples): var result = "" for triple in triples { result += indentation result += try nest(triple, depth: depth) result += "\n" } return result case let .union(left, .identity): return try nest(left, depth: depth) case let .union(.identity, right): return try nest(right, depth: depth) case let .union(left, right): var result = indentation result += "{\n" result += try nest(left, depth: depth + 1) result += indentation result += "} UNION {\n" result += try nest(right, depth: depth + 1) result += indentation result += "}\n" return result case let .minus(left, .identity): return try nest(left, depth: depth) case let .minus(.identity, right): return try nest(right, depth: depth) case let .minus(left, right): var result = try nest(left, depth: depth) result += indentation result += "MINUS {\n" result += try nest(right, depth: depth + 1) result += indentation result += "}\n" return result case .filter(_, .identity): return "" case let .filter(expression, op): var result = try nest(op, depth: depth) result += indentation result += "FILTER " result += try nest(expression, depth: 0) result += "\n" return result case let .leftJoin(left, right, expression): var result = try nest(left, depth: depth) result += indentation result += "OPTIONAL {\n" result += try nest(right, depth: depth + 1) if let expression = expression { result += indentation result += " FILTER " result += try nest(expression, depth: 0) result += "\n" } result += indentation result += "}\n" return result case let .join(left, right): var result = try nest(left, depth: depth) result += try nest(right, depth: depth) return result case let .project(variables, op): var result = "" if variables.isEmpty { result += "*" } else { result += variables .map { name in "?\(name)" } .joined(separator: " ") } // if child op is a filter which will result in a HAVING clause, a group, or an order by, // it will add the block switch op { case .filter where op.isHaving(parent: self), .group, .orderBy: result += try nest(op, depth: depth) default: result += " {\n" result += try nest(op, depth: depth + 1) result += indentation result += "}\n" } return result case let .distinct(op) where op.isValidDistinctChild: var result = "DISTINCT " result += try nest(op, depth: depth) return result case .distinct: // fall-through for distinct child ops which are invalid throw SPARQLSerializationError.unsupportedChildOp case let .orderBy(op, orderComparators): var result = "" // if child op is filter which will result in a HAVING clause, or a group, it will add the block switch op { case .filter where op.isHaving(parent: self), .group: result += try nest(op, depth: depth) default: result += " {\n" result += try nest(op, depth: depth + 1) result += indentation result += "}\n" } if orderComparators.isEmpty { return result } result += indentation result += "ORDER BY " result += try orderComparators .map { try nest($0, depth: 0) } .joined(separator: " ") result += "\n" return result case let .group(op, groupVars, aggregations): var result = try aggregations .sorted { $0.key < $1.key } .map { let (name, aggregation) = $0 let serialized = try nest(aggregation, depth: 0) return " (\(serialized) AS ?\(name))" } .joined() // if child op is filter which will result in a HAVING clause, or an order by, // it will add the block switch op { case .filter where op.isHaving(parent: self), .orderBy: result += try nest(op, depth: depth) default: result += " {\n" result += try nest(op, depth: depth + 1) result += indentation result += "}\n" } if !groupVars.isEmpty { result += indentation result += "GROUP BY " result += groupVars .map { name in "?\(name)" } .joined(separator: " ") } result += "\n" return result } } public var isValidDistinctChild: Bool { guard case .project = self else { return false } return true } public var isQuery: Bool { switch self { case .distinct, .project: return true default: return false } } public func isSubquery(nested: Op) -> Bool { switch self { case .distinct: return false default: return nested.isQuery } } public func isHaving(parent: Op) -> Bool { guard case let .filter(_, child) = self else { return false } switch parent { case .orderBy, .project: guard case .group = child else { return false } return true default: return false } } } <file_sep> public final class Context { public var prefixMapping: [String: String] public init(prefixMapping: [String: String]) { self.prefixMapping = prefixMapping } func findPrefixMapping(iri: String) -> (prefix: String, suffix: String)? { let entry = prefixMapping.first { let (_, base) = $0 return iri.hasPrefix(base) } guard case let (prefix, base)? = entry else { return nil } let index = iri.index(iri.startIndex, offsetBy: base.count) return (prefix, String(iri[index...])) } } <file_sep> public indirect enum Expression: Hashable { case node(Node) case not(Expression) case and(Expression, Expression) case or(Expression, Expression) case equals(Expression, Expression) case notEquals(Expression, Expression) case lessThan(Expression, Expression) case lessThanOrEquals(Expression, Expression) case greaterThan(Expression, Expression) case greaterThanOrEquals(Expression, Expression) case functionCall(String, [Expression]) } extension Expression: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) throws -> String { switch self { case let .node(node): return node.serializeToSPARQL(depth: depth, context: context) case let .not(expression): return "!" + (try expression.serializeToSPARQL(depth: depth, context: context)) case let .and(left, right): let values = try [left, right].map { try $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(values, separator: " && ") case let .or(left, right): let values = try [left, right].map { try $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(values, separator: " || ") case let .equals(left, right): let values = try [left, right].map { try $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(values, separator: " = ") case let .notEquals(left, right): let values = try [left, right].map { try $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(values, separator: " != ") case let .lessThan(left, right): let values = try [left, right].map { try $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(values, separator: " < ") case let .lessThanOrEquals(left, right): let values = try [left, right].map { try $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(values, separator: " <= ") case let .greaterThan(left, right): let values = try [left, right].map { try $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(values, separator: " > ") case let .greaterThanOrEquals(left, right): let values = try [left, right].map { try $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(values, separator: " >= ") case let .functionCall(name, arguments): let serializedArguments = try arguments .map { try $0.serializeToSPARQL(depth: 0, context: context) } .joined(separator: ", ") return "\(name)(\(serializedArguments))" } } } <file_sep> public struct Triple: Equatable { public var subject: Node public var predicate: Predicate public var object: Node public init(subject: Node, predicate: Predicate, object: Node) { self.subject = subject self.predicate = predicate self.object = object } } extension Triple: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) -> String { let subject = self.subject.serializeToSPARQL(depth: depth, context: context) let predicate = self.predicate.serializeToSPARQL(depth: depth, context: context) let object = self.object.serializeToSPARQL(depth: depth, context: context) return [subject, predicate, object].joined(separator: " ") + " ." } } <file_sep> public indirect enum Path: Equatable { case predicate(String) case inverse(Path) case sequence([Path]) case alternative([Path]) case zeroOrMore(Path) case oneOrMore(Path) case zeroOrOne(Path) case negated([NegatedIRI]) } extension Path: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) -> String { switch self { case .predicate(RDF.type): return "a" case let .predicate(iri): if let (prefix, suffix) = context.findPrefixMapping(iri: iri) { return "\(prefix):\(suffix)" } return "<\(iri)>" case let .inverse(path): let serialized = path.serializeToSPARQL(depth: depth, context: context) return "^\(serialized)" case let .sequence(paths): let serialized = paths.map { $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(serialized, separator: " / ") case let .alternative(paths): let serialized = paths.map { $0.serializeToSPARQL(depth: depth, context: context) } return joinAndGroup(serialized, separator: " | ") case let .zeroOrMore(path): let serialized = path.serializeToSPARQL(depth: depth, context: context) return "\(serialized)*" case let .oneOrMore(path): let serialized = path.serializeToSPARQL(depth: depth, context: context) return "\(serialized)+" case let .zeroOrOne(path): let serialized = path.serializeToSPARQL(depth: depth, context: context) return "\(serialized)?" case let .negated(negatedIRIs): let serialized = negatedIRIs.map { $0.serializeToSPARQL(depth: depth, context: context) } let joined = joinAndGroup(serialized, separator: " | ") return "!\(joined)" } } } <file_sep> import Foundation public enum Literal: Hashable { case plain(String) case withLanguage(String, String) case withDatatype(String, Datatype) public var value: String { switch self { case let .plain(value): return value case .withLanguage(let value, _): return value case .withDatatype(let value, _): return value } } } extension Literal: CustomStringConvertible { public var description: String { switch self { case .plain, .withDatatype(_, .string): return valueDescription case .withLanguage(_, let language): return [valueDescription, language] .joined(separator: "@") case .withDatatype(_, let datatype): return [valueDescription, datatype.description] .joined(separator: "^^") } } private var valueDescription: String { let escaped = value .replacingOccurrences(of:"\"", with: "\\\"") return "\"\(escaped)\"" } } extension Literal: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) -> String { switch self { case .withDatatype(let literal, .integer), .withDatatype(let literal, .double), .withDatatype(let literal, .boolean): return literal case .withDatatype(_, let datatype): let serializedDatatype = datatype.serializeToSPARQL(depth: depth, context: context) return [valueDescription, serializedDatatype] .joined(separator: "^^") default: return description } } } <file_sep> public enum Order: Equatable { case ascending case descending } extension Order: SPARQLSerializable { public func serializeToSPARQL(depth: Int, context: Context) throws -> String { switch self { case .ascending: return "ASC" case .descending: return "DESC" } } } <file_sep> internal func joinAndGroup(_ values: [String], separator: String) -> String { if values.count < 2 { return values.first ?? "" } let joined = values .joined(separator: separator) return "(\(joined))" } internal func indent(depth: Int) -> String { return String(repeating: " ", count: depth * 2) }
52c30f30d46591a613efcaa70894450e9df8b267
[ "Swift", "Markdown" ]
21
Swift
turbolent/SPARQL
f63668d1360054c5f7c49a241522e4dfc9b289b7
59677e3a82d62cae0a0e71a2914698de2b3dd31d
refs/heads/master
<file_sep>def packer(name=None, **kwargs): print(kwargs) def unpacker(first_name=None, last_name=None): if first_name and last_name: print("Hi {} {}!".format(first_name, last_name)) else: print("hi no name!") packer(name="Kenneth", num=42, spanish_inquisition=None) unpacker(**{"last_name": "Love", "first_name": "Kenneth"}) course_minutes = {"Python Basics": 232, "Django Basics": 237, "Flask Basics": 189, "Java Basics": 133} for course, minutes in course_minutes.items(): print("{} is {} minutes long".format(course, minutes))<file_sep>def word_count(string): string = string.lower() word_dictionary = dict() list_of_words = string.split() for word in list_of_words: word_dictionary[word] = list_of_words.count(word) return word_dictionary <file_sep>def covers(args): result = [] for key, value in COURSES.items(): if args.intersection(value): result.append(key) return result def covers_all(args): new_list = [] for key, value in COURSES.items(): if args & COURSES[key] == args: new_list.append(key) return new_list COURSES = { "Python Basics": {"Python", "functions", "variables", "booleans", "integers", "floats", "arrays", "strings", "exceptions", "conditions", "input", "loops"}, "Java Basics": {"Java", "strings", "variables", "input", "exceptions", "integers", "booleans", "loops"}, "PHP Basics": {"PHP", "variables", "conditions", "integers", "floats", "strings", "booleans", "HTML"}, "Ruby Basics": {"Ruby", "strings", "floats", "integers", "conditions", "functions", "input"} } <file_sep># The dictionary will look something like: # {'<NAME>': ['jQuery Basics', 'Node.js Basics'], # '<NAME>': ['Python Basics', 'Python Collections']} # # Each key will be a Teacher and the value will be a list of courses. # # Your code goes below here. def num_teachers(teachers): count = 0 for d in teachers.keys(): count = count+1 return(count) def num_courses(teachers): courses = 0 for key, value in teachers.items(): courses += len(list(value)) return(courses) def courses(teachers): list_courses = [] for value in teachers.values(): for val in value: list_courses.append(val) return(list_courses) def most_courses(teachers): maxcourse = 0 maxname = '' for name in teachers.keys(): if maxcourse < len(teachers[name]): maxcourse = len(teachers[name]) maxname = name else: continue return maxname def stats(teachers): lista = [] for key in teachers: course = [key, len(teachers[key])] lista.append(course) return lista <file_sep>def yell(text): text = text.upper() number_of_characters = len(text) result = text + "!" * (number_of_characters // 2) print(result) yell("You are doing great") yell("Don't forget to ask for help") yell("Don't repeat yourself, Keep things DRY")<file_sep>SERVICE_CHARGE = 2 TICKET_PRICE = 10 tickets_remaining = 100 def calculate_price(number_of_tickets): return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE while tickets_remaining >= 1: print("There are {} tickets remaining".format(tickets_remaining)) name = input("What is your name? ") num_tickets = input("{}, How many tickets would you like? ".format(name)) try: num_tickets = int(num_tickets) if num_tickets > tickets_remaining: raise ValueError("There are only {} ticket's remaining.".format(tickets_remaining)) except ValueError as err: print("Oh no, we ran into an issue. {}. Please try again.".format(err)) else: amount_due = calculate_price(num_tickets) print("Total due is {}".format(amount_due)) should_proceed = input("Do you want to proceed? Y/N ") if should_proceed.lower() == "y": print("Sold") tickets_remaining -= num_tickets else: print("Thank you anyways, {}.".format(name)) print("Sorry, we are sold out")
76caaedd3b65a7fc463328e468b0c969702ec3e5
[ "Python" ]
6
Python
haptikfeedback/python_basics
ad7ba3184036a40c461901641bb3055ed375bf77
bd29d35912d9d95722e028a11d0354743363547c
refs/heads/master
<file_sep>plugins { id 'java' id 'idea' id 'org.springframework.boot' id 'io.spring.dependency-management' } dependencies { testImplementation group: 'org.springframework.security', name: 'spring-security-test' /** TODO Spring Boot */ implementation group: 'org.springframework.boot', name: 'spring-boot-starter-hateoas' // HATEOAS(Hypermedia as the engine of application state)是 REST 架构风格中最复杂的约束 /** TODO Session: 使用 Token 更好 */ implementation group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.1' /** TODO Security */ implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security' /** TODO H2 */ implementation group: 'com.h2database', name: 'h2' } <file_sep>/** todo 官方配置文档地址: https://docs.gradle.org/current/dsl/org.gradle.api.initialization.Settings.html */ rootProject.name = 'SpringBoot' include 'Web' include 'Mybatis' include 'Redis' include 'Mongo' include 'Neo4j' <file_sep>plugins { id 'java' id 'idea' id 'org.springframework.boot' id 'io.spring.dependency-management' } dependencies { /** TODO Mongo */ implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-mongodb' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-mongodb-reactive' implementation group: 'org.mongodb', name: 'mongo-java-driver' } <file_sep>package kasei.boot.web; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class WebBootAppTest { @Autowired ApplicationContext applicationContext; @Test public void test(){ Map<String, Object> beansOfType = applicationContext.getBeansOfType(Object.class); beansOfType.forEach((k, v) -> System.out.println(k)); } } <file_sep>plugins { id 'java' id 'idea' id 'org.springframework.boot' id 'io.spring.dependency-management' } dependencies { /** TODO Neo4j */ implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-neo4j' implementation group: 'org.neo4j', name: 'neo4j-ogm-embedded-driver', version: '3.2.3' // 该依赖存在时 spring boot 自动创建一个 neo4j 实例保存到 IOC 容器中 implementation group: 'org.neo4j', name: 'neo4j', version: '3.5.13' // neo4j 嵌入式数据库 implementation group: 'org.neo4j.driver', name: 'neo4j-java-driver-spring-boot-starter', version: '4.0.0' } <file_sep>package kasei.springboot; import com.zaxxer.hikari.HikariDataSource; import kasei.springboot.repository.slaver.dao.mapper.PersonMapper; import kasei.springboot.repository.slaver.entity.Person; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.jupiter.api.Test; import org.neo4j.graphdb.factory.GraphDatabaseBuilder; import org.neo4j.graphdb.factory.GraphDatabaseFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient; import org.springframework.boot.test.context.SpringBootTest; import javax.sql.DataSource; import javax.xml.crypto.Data; import java.io.File; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class SpringBootAppTest { // @Autowired PersonMapper personMapper; @Autowired @Qualifier("slaverSqlSessionFactory") SqlSessionFactory factory; @Test public void mainTest() throws SQLException { GraphDatabaseBuilder graphDatabaseBuilder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(new File("/opt/Git/LocalRepository/SpringBoot/src/main/resources/neo4j")); } } <file_sep>package kasei.boot.web.controller; import kasei.boot.web.utility.UniversalResponse; import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collection; @RestController @RequestMapping( path = "/Security", produces = {MediaType.APPLICATION_JSON_VALUE}) public class SecurityController { /** TODO spring security authenticate procedure * 构造一个 Authentication 实例 * 将 Authentication 实例传递给 AuthenticationManager 实例进行认证 * org.springframework.security.authentication.AuthenticationManager 返回一个补充过权限等信息的 Authentication 实例 * 调用 SecurityContextHolder.getContext().setAuthentication(…​) 将认证过的 Authentication 实例放入到 SecurityContext 中 * */ // @PostMapping("/authenticate/pwd") // public UniversalResponse authenticateByPwd(@RequestBody User user){ // // Authentication 接口表示:一切能表明用户身份的信息的东西,以下简称 -- 身份证 // Authentication authRequest = new UsernamePasswordAuthenticationToken(user.getAccount(), user.getPassword()); // // // AuthenticationManager 用于验证 身份证 的真实性 // AuthenticationManager am = new UserPwdAuthenticationManager(); // Authentication authResult = null; // try { // authResult = am.authenticate(authRequest); // 返回一个验证过的 身份证,包含认证过的 证书,和 权限 // } catch (AuthenticationException e) { // System.out.println("Authentication failed: " + e.getMessage()); // } // // // 将验证过的 身份证 放入到 安全认证上下文中,SecurityContextHolder 是用于操作 SecurityContext (安全认证上下文)的操作类 // SecurityContextHolder.getContext().setAuthentication(authResult); // // return null; // } @PostMapping("/authenticate/jwt") public UniversalResponse authenticateByJwt(){ return null; } @GetMapping public String getSecurityFundamentalClass(){ // 获取保存在 ThreadLocal 中的 SecurityContext 实例 SecurityContext securityContext = SecurityContextHolder.getContext(); // 获取认证方式 Authentication authentication = securityContext.getAuthentication(); // 获取当前认证方式的主角 Object principal = authentication.getPrincipal(); // 获取权限 Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); return null; } } <file_sep>package kasei.boot.mybatis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * spring boot 应用进入 debug * -Xdebug -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 * */ @SpringBootApplication public class MybatisBootApp { public static void main(String[] args) { SpringApplication.run(MybatisBootApp.class, args); } } <file_sep>package kasei.boot.web.controller; import kasei.boot.web.repository.h2.dao.UserDao; import kasei.boot.web.repository.h2.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; import java.util.Optional; @RestController @RequestMapping("/User") public class UserController { @Autowired private UserDao userDao; @Autowired private ApplicationContext applicationContext; @GetMapping("/beans") public User getAllUser(){ Map<String, Object> beansOfType = applicationContext.getBeansOfType(Object.class); beansOfType.forEach((k,v)-> System.out.println(k)); return null; } @GetMapping("/gg") public List<User> gg(){ return userDao.gg(); } @GetMapping("/id") public User getById(){ Optional<User> byId = userDao.findById(1); return byId.get(); } } <file_sep>plugins { id 'java' id 'idea' id 'org.springframework.boot' id 'io.spring.dependency-management' } dependencies { /** TODO Local Dependency */ implementation fileTree(dir:'lib', excludes:['**/ignore/**', '**/data/**']) /** TODO Spring Boot */ implementation group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc' /** TODO ORM */ implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '2.1.1' implementation group: 'org.mybatis', name: 'mybatis', version: '3.5.3' implementation group: 'org.mybatis.dynamic-sql', name: 'mybatis-dynamic-sql', version: '1.1.4' implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.18' /** TODO Convenient Develop */ runtimeOnly group: 'org.mybatis.generator', name: 'mybatis-generator-core', version: '1.4.0' // mybatis 自动根据数据库表生成代码 } <file_sep>package kasei.boot.mongo.repository.mongo.dao; import kasei.boot.mongo.repository.mongo.entity.Org; import java.util.List; public interface OrgDaoCustomRepository { public List<String> updateByName(String name, Integer year); } <file_sep>/** TODO 将所有插件定义到 root project, * apply false: 表示将插件添加到所有项目中,除了 root project * */ plugins { id 'java' id 'idea' // 作用: 引入 gradle 构建 spring boot 项目所需要的 task,且引入的 task 会根据 gradle 中引入的插件动态变化 id 'org.springframework.boot' version '2.2.2.RELEASE' // 作用: 让 srping boot 来管理各个依赖的版本,而不是手工指定, // 好处: spring boot 管理的各个版本的依赖,都是经过测试的 id 'io.spring.dependency-management' version "1.0.8.RELEASE" } allprojects { apply plugin: 'java' apply plugin: 'io.spring.dependency-management' sourceCompatibility = JavaVersion.VERSION_11 // 项目中代码使用的 JDK 版本 targetCompatibility = JavaVersion.VERSION_11 // 编译后的 .class 文件的 JDK 版本 version = '0.0.1' configurations { compile.exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging' // 排除掉 spring 默认的日志框架(logback) testCompile.exclude group: 'org.junit.vintage' // 排除掉 Junit5 兼容 Junit4 的 jar 包 } repositories { maven { url "http://maven.aliyun.com/nexus/content/groups/public" } mavenCentral() jcenter() } dependencies { /** todo Gradle 支持的依赖方式 * compileOnly — for dependencies that are necessary to compile your production code but shouldn’t be part of the runtime classpath * implementation (supersedes compile) — used for compilation and runtime * runtimeOnly (supersedes runtime) — only used at runtime, not for compilation * testCompileOnly — same as compileOnly except it’s for the tests * testImplementation — test equivalent of implementation * testRuntimeOnly — test equivalent of runtimeOnly * */ /** TODO Convenient Develop */ // 自动生成 getter setter,而不用写在代码里,需要 IDEA 安装 lombok 插件,并修改 "Settings > Build > Compiler > Annotation Processors" 为 Enable annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.10' implementation group: 'org.springframework.boot', name: 'spring-boot-devtools' // 开发工具,实现 spring boot 项目热部署 /** TODO 测试 */ testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-test' testImplementation group: 'org.junit.platform', name: 'junit-platform-launcher' /** TODO Config */ // spring boot 默认只能注入 yml 里面的配置,引入这个可以注入 .xml 或 .properties 文件的配置,例如:@PropertySource("classpath:your.properties") implementation group: 'org.springframework.boot', name: 'spring-boot-configuration-processor' /** TODO Logging */ implementation group: 'org.springframework.boot', name: 'spring-boot-starter-log4j2' testImplementation group: 'org.slf4j', name: 'slf4j-log4j12' /** TODO Web */ implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-webflux' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-json' /** TODO Persistence */ implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa' } } <file_sep>package kasei.boot.mongo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class}) public class MongoBootApp { public static void main(String[] args) { SpringApplication.run(MongoBootApp.class, args); } } <file_sep>package kasei.springboot.utility; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class MessageDigestUtil { public static String generateMD(String content) throws NoSuchAlgorithmException { return generateMD(content.getBytes(Charset.forName("utf8"))); } public static String generateMD(byte[] bytes) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(bytes); byte[] digest = messageDigest.digest(); String base64Digest = Base64.getUrlEncoder().encodeToString(digest); return base64Digest; } } <file_sep>package kasei.boot.neo4j; public class Neo4jBootApp { } <file_sep>plugins { id 'java' id 'idea' id 'org.springframework.boot' id 'io.spring.dependency-management' } dependencies { /** TODO Redis */ implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis-reactive' implementation group: 'org.apache.commons', name: 'commons-pool2', version: '2.7.0' } <file_sep>package kasei.boot.web.config.security; import kasei.boot.web.repository.h2.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.Set; @Component // 当有一个自定义的 UserDetailsService 类型的 bean 存在于 IOC 容器中时,会关闭 UserDetailsServiceAutoConfiguration 的自动配置 public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserDao userDao; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { kasei.boot.web.repository.h2.entity.User byAccount = userDao.findByAccount(username); if (byAccount == null) { return null; } // 为当前用户配置权限 GrantedAuthority authority1 = new SimpleGrantedAuthority("ROLE_USER"); Collection<? extends GrantedAuthority> authorities = Set.of(authority1); // 注意这里的 User 是 org.springframework.security.core.userdetails.User 不是自定义的 User UserDetails userDetails = new User(username, byAccount.getPassword(), authorities); return userDetails; } } <file_sep> insert into user(id, account, password) values (0, 'root', '<PASSWORD>'), (1, 'kasei', '<PASSWORD>');
e498f8bae61d6f74de5dd03d3478bf3ad3354225
[ "Java", "SQL", "Gradle" ]
18
Gradle
lzlFLT1/SpringBoot
c9aabf6d272700e2f6fd93ebf9ff70538f19b83a
6e11f9031550147cea4276d46db9f44ba2959f26
refs/heads/master
<file_sep>package pp; import java.util.LinkedList; import java.util.Random; public class Experiment<E extends Comparable<E>> { private final LinkedList<E> list; public Experiment(LinkedList<E> list) { this.list = list; } @SuppressWarnings("unchecked") public void carryOut() { // Sequentially System.out.println("Sequentially"); LinkedList<E> try1 = (LinkedList<E>) this.list.clone(); MergeSortSequenziell<E> ms1 = new MergeSortSequenziell<>(); long timeStart = System.currentTimeMillis(); ms1.mergeSort(try1); long timeEnd = System.currentTimeMillis(); System.out.println("Execution time: " + (timeEnd - timeStart) + " milliseconds."); // Runnable System.out.println("Runnable"); LinkedList<E> try2 = (LinkedList<E>) this.list.clone(); MergeSortRunnable<E> ms2 = new MergeSortRunnable<>(); timeStart = System.currentTimeMillis(); ms2.mergeSort(try2); timeEnd = System.currentTimeMillis(); System.out.println("Execution time: " + (timeEnd - timeStart) + " milliseconds."); // ThreadPool System.out.println("Threadpool"); LinkedList<E> try3 = (LinkedList<E>) this.list.clone(); MergeSortThreadPool<E> ms3 = new MergeSortThreadPool<>(); timeStart = System.currentTimeMillis(); ms3.mergeSort(try3); timeEnd = System.currentTimeMillis(); System.out.println("Execution time: " + (timeEnd - timeStart) + " milliseconds."); // ForkJoin System.out.println("ForkJoin"); LinkedList<E> try4 = (LinkedList<E>) this.list.clone(); MergeSortForkJoin<E> ms4 = new MergeSortForkJoin<>(); timeStart = System.currentTimeMillis(); ms4.mergeSort(try4); timeEnd = System.currentTimeMillis(); System.out.println("Execution time: " + (timeEnd - timeStart) + " milliseconds."); } public static void main(String[] args) { Random r = new Random(); LinkedList<Integer> list = new LinkedList<Integer>(); // Measure points 1-4 System.out.println("An Experiment with 10 items:"); for (int i = 0; i < 10; i++) list.add(1 + r.nextInt(50000)); new Experiment<Integer>(list).carryOut(); // Measure points 5-8 System.out.println("\nAAn Experiment with 100 items:"); for (int i = 0; i < 100; i++) list.add(1 + r.nextInt(50000)); new Experiment<Integer>(list).carryOut(); // Measure points 9-12 System.out.println("\nAAn Experiment with 1000 items:"); for (int i = 0; i < 1000; i++) list.add(1 + r.nextInt(50000)); new Experiment<Integer>(list).carryOut(); // Measure points 13-16 list = new LinkedList<Integer>(); System.out.println("\nAn Experiment with 5000 items:"); for (int i = 0; i < 5000; i++) list.add(1 + r.nextInt(50000)); new Experiment<Integer>(list).carryOut(); // Measure points 17-20 list = new LinkedList<Integer>(); System.out.println("\nAn Experiment with 10000 items:"); for (int i = 0; i < 10000; i++) list.add(1 + r.nextInt(50000)); new Experiment<Integer>(list).carryOut(); // Measure points 21-24 list = new LinkedList<Integer>(); System.out.println("\nAn Experiment with 50000 items:"); for (int i = 0; i < 50000; i++) list.add(1 + r.nextInt(50000)); new Experiment<Integer>(list).carryOut(); } } <file_sep>package pp; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Collections; import java.util.LinkedList; import java.util.Random; import org.junit.jupiter.api.Test; class JUnitTestMergeSortThreadPool { MergeSortThreadPool<String> ms1 = new MergeSortThreadPool<>(); MergeSortThreadPool<Integer> ms2 = new MergeSortThreadPool<>(); @Test void freeTypeTest() { ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); LinkedList<Integer> list = new LinkedList<>(); ms2.mergeSort(list); ms2.printListForTest(list); String expectedOutput = ""; assertEquals(expectedOutput, outContent.toString()); } @Test void StringsDescending() { LinkedList<String> list = new LinkedList<>(); list.add("Zaan"); list.add("Xenon"); list.add("Walter"); list.add("Vadim"); list.add("Ullrich"); list.add("Ted"); list.add("Sam"); list.add("Rob"); list.add("Pedro"); list.add("Otis"); list.add("Niklas"); list.add("Matt"); list.add("Lion"); list.add("Kai"); list.add("Jessy"); list.add("Ivan"); list.add("Hendrik"); list.add("Hanno"); list.add("Georg"); list.add("Frodo"); list.add("Egon"); list.add("Diego"); list.add("Derek"); list.add("Damir"); list.add("Carlo"); list.add("Bryson"); list.add("Bo"); list.add("Baal"); list.add("August"); list.add("Andrea"); list.add("Adam"); list.add("Aaron"); ms1.mergeSort(list); ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); ms1.printListForTest(list); String expectedOutput = "AaronAdamAndreaAugustBaalBoBrysonCarloDamirDerekDiegoEgonFrodoGeorgHannoHendrikIvanJessyKaiLionMattNiklasOtisPedroRobSamTedUllrichVadimWalterXenonZaan"; assertEquals(expectedOutput, outContent.toString()); } @Test void randomNumbers() { LinkedList<Integer> mylist = new LinkedList<>(); LinkedList<Integer> expectedlist = new LinkedList<>(); Random r = new Random(); for (int i = 0; i < 132; i++) { int randomNumber = 1 + r.nextInt(1000); mylist.add(randomNumber); expectedlist.add(randomNumber); } ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); ms2.mergeSort(mylist); ms2.printList(mylist); ByteArrayOutputStream expectedOutput = new ByteArrayOutputStream(); System.setOut(new PrintStream(expectedOutput)); Collections.sort(expectedlist); ms2.printList(expectedlist); assertEquals(expectedOutput.toString(), outContent.toString()); } } <file_sep>package io.dama.ffi.hoh; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> { private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock readLock = lock.readLock(); private final Lock writeLock = lock.writeLock(); private Node<T> first; private class Node<U> { private U element; private final Node<U> prev; private Node<U> next; private Node(final U element, final Node<U> prev, final Node<U> next) { super(); this.element = element; this.prev = prev; this.next = next; } } public ThreadsafeSimplifiedList() { super(); this.first = null; } @Override public T get(final int i) { try { readLock.lock(); var ptr = this.first; for (var j = 0; j < i; j++) { ptr = ptr.next; } return delay(ptr.element); } finally { readLock.unlock(); } } @Override public boolean add(final T e) { try { writeLock.lock(); if (this.first != null) { var ptr = this.first; while (ptr.next != null) { ptr = ptr.next; } ptr.next = new Node<>(e, ptr, null); } else { this.first = new Node<>(e, null, null); } return true; } finally { writeLock.unlock(); } } @Override public T set(final int i, final T e) { try { writeLock.lock(); var ptr = this.first; for (var j = 0; j < i; j++) { ptr = ptr.next; } ptr.element = e; return e; } finally { writeLock.unlock(); } } @Override public boolean isEmpty() { try { readLock.lock(); return this.first == null; } finally { readLock.unlock(); } } } <file_sep>package pp; import java.util.LinkedList; import java.util.concurrent.atomic.AtomicInteger; public class MergeSortRunnable<E extends Comparable<E>> extends MergeSortSequenziell<E> { private final int PROCESSORS = Runtime.getRuntime().availableProcessors() - 1; private AtomicInteger counter = new AtomicInteger(0); // count the processors used /** * a method to sort a list of values in ascending order. the data * to be sorted must be of the type that implements the Comparable * interface. * @param data LinkedList to be sorted * @return void - */ public void mergeSort(LinkedList<E> data) { if (data == null) throw new IllegalArgumentException("null is not allowed"); mergeSortHelper(data, 0, data.size() - 1); } protected void mergeSortHelper(LinkedList<E> data, int min, int max) { // if the resources are exhausted continue with sequential sorting... if (counter.get() >= PROCESSORS) { super.mergeSortHelper(data, min, max); } else { // ..otherwise divide the problem int len = max - min + 1; if (len > 1) { int middle = min + (max - min) / 2; // find the middle of the list Thread t1 = new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); mergeSortHelper(data, min, middle); // sort the left part of the list counter.decrementAndGet(); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); mergeSortHelper(data, middle + 1, max); // sort the right part of the list counter.decrementAndGet(); } }); t1.start(); // start sorting of the left part t2.start(); // start sorting of the right part try { t1.join(); // wait until the left part is sorted t2.join(); // wait until the right is sorted } catch (InterruptedException e) { e.printStackTrace(); } merge(data, min, middle, middle + 1, max); // merge the both of parts } else return; } } } <file_sep>package pp; import java.util.Arrays; import java.util.LinkedList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; public class MergeSortThreadPool<E extends Comparable<E>> extends MergeSortSequenziell<E> { private final int PROCESSORS = Runtime.getRuntime().availableProcessors()-1; private ExecutorService es = Executors.newCachedThreadPool(); private AtomicInteger counter = new AtomicInteger(0); // count the processors used /** * a method to sort a list of values in ascending order. the data * to be sorted must be of the type that implements the Comparable * interface. * @param data LinkedList to be sorted * @return void - */ public void mergeSort(LinkedList<E> data) { if (data == null) throw new IllegalArgumentException("null is not allowed"); mergeSortHelper(data, 0, data.size() - 1); es.shutdown(); } protected void mergeSortHelper(LinkedList<E> data, int min, int max) { // if the resources are exhausted continue with sequential sorting... if (counter.get() >= PROCESSORS) { super.mergeSortHelper(data, min, max); } else { // ..otherwise divide the problem int len = max - min + 1; if (len > 1) { int middle = min + (max - min) / 2; Callable<Void> c1 = () -> { counter.incrementAndGet(); mergeSortHelper(data, min, middle); // sort the left part of the list counter.decrementAndGet(); return null; }; Callable<Void> c2 = () -> { counter.incrementAndGet(); mergeSortHelper(data, middle + 1, max); // sort the right part of the list counter.decrementAndGet(); return null; }; // sort the right and the left parts of the list // and wait until the both of part are sorted try { es.invokeAll(Arrays.asList(c1,c2)); } catch (InterruptedException e) { e.printStackTrace(); } merge(data, min, middle, middle + 1, max); // merge the both of parts } else return; } } } <file_sep>package io.dama.ffi.parcoord.dining.cond; import java.util.concurrent.locks.Lock; public interface IPhilosopher { void run(); void setLeft(IPhilosopher left); void setRight(IPhilosopher right); void setSeat(int seat); void setTable(Lock table); void start(); void stopPhilosopher(); }
820e03abbad2af8e22f978eb249112d621ed0d8d
[ "Java" ]
6
Java
SergejHerwald/Sergej_Herwald
c3cf25edbd23ae340fc15836e4ac4490a8412b9c
4363170f131855a72d0d9b962742dcc5c4fb44f2
refs/heads/master
<file_sep>package com.ppc.ui; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import com.ppc.data.PassportData; public class GameWindow { public static void initialize() { Frame frame = new Frame("\"Papers, Please\" Clone"); frame.add(new GamePanel()); frame.setExtendedState(Frame.MAXIMIZED_BOTH); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); ObjectManager.instance().addObject(new Passport(PassportData.randomPassportData())); } } <file_sep>package com.ppc.data; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class Date { private int day; private int month; private int year; public Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getDaysInMonth() { return getDaysInMonth(month, year); } public void addDays(int days) { if (days <= 0) { throw new IndexOutOfBoundsException("Invalid amount of days to add: " + days); } day += days; if (day > getDaysInMonth()) { month++; day %= getDaysInMonth(); if (month > 12) { year++; month = 1; } } } @Override public String toString() { return month + "/" + day + "/" + year; } @Override public boolean equals(Object obj) { if (obj instanceof Date) { Date date = (Date) obj; return date.day == day && date.month == month && date.year == year; } return false; } @Override public int hashCode() { int hash = 17; hash = hash * 31 + day; hash = hash * 31 + month; hash = hash * 31 + year; return hash; } public static Date randomDate(int yearMin, int yearMax) { Random random = ThreadLocalRandom.current(); int day; int month; int year; year = random.nextInt(yearMax - yearMin) + yearMin; month = random.nextInt(12) + 1; day = random.nextInt(getDaysInMonth(month, year)) + 1; return new Date(day, month, year); } public static int getDaysInMonth(int month, int year) { switch (month) { case 2: return year % 4 == 0 ? 29 : 28; case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; default: return 30; } } } <file_sep>package com.ppc.ui; import java.awt.Graphics2D; import java.util.ArrayList; public class ObjectManager { private static ObjectManager instance = new ObjectManager(); public static ObjectManager instance() { return instance; } private ArrayList<GameObject> objects = new ArrayList<>(); public void addObject(GameObject object) { objects.add(object); } public void update(Graphics2D graphics) { for (GameObject object : objects) { object.draw(graphics); } } public GameObject getObjectAt(int x, int y) { for (GameObject object : objects) { int x0 = object.getX(); int y0 = object.getY(); if (x >= x0 && y >= y0 && x < x0 + object.getWidth() && y < y0 + object.getHeight()) { return object; } } return null; } } <file_sep>package com.ppc; import com.ppc.ui.GameWindow; public class GameMain { public static void main(String[] args) { Game.initialize(); GameWindow.initialize(); } }
13461e2052e93e2c6178d8bb49d94fae2b788248
[ "Java" ]
4
Java
TitaniumSapphire/Papers-Please-Clone
10944c770cd0d518d8b9f3e9cae3fbd458cc1a58
e5eee8d739df955e876468acd75a4fb93c8d4151
refs/heads/main
<file_sep> function myclock(){ var mytime = new Date(); var myHour = mytime.getHours(); var myMinute = mytime.getMinutes(); var mySeconds = mytime.getSeconds(); var ampm = 'AM'; if(myHour > 12){ myHour =myHour - 12; ampm = 'PM'; }else{ myHour = myHour; } if(myMinute < 10){ myMinute = '0' + myMinute; }else{ myMinute = myMinute; } if(myHour < 10){ myHour = '0' + myHour; }else{ myHour = myHour; } if(mySeconds < 10){ mySeconds = '0' + mySeconds; }else{ mySeconds = mySeconds; } var display = document.getElementById('display'); var ampmArea = document.getElementById('ampm'); var finalTime = myHour + ':' + myMinute + ':' + mySeconds; console.log(finalTime); display.innerText = finalTime; ampmArea.innerText = ampm; } setInterval(myclock,100);
1a6b2776d02e4ddc54644ef23251e1eef2e3f972
[ "JavaScript" ]
1
JavaScript
Ranagithubrr/clock
b137f208c4f58443e5d67e3d3d2725a9917cad30
caff27ab2ea1ad842f26c03a57294c06e26d3ac0
refs/heads/master
<file_sep>import math import random hex_numbers = ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F') program = "PM:\n00: 0900\n01: 0001\n02: 0500\n03: 00E0\n04: 14C0\n05: 0CC0\n06: 9D00\n07: 00FF\n08: 7011\n09: 2D00\n0a: 0001\n0b: 1CC0\n0c: 02C0\n0d: 9D00\n0e: 00E0\n0f: 7008\n10: 3D00\n11: 0001\n12: 9300\n13: 8002\n14: AB00\n15: 60F7\n16: 2D00\n17: 0001\n18: 1300\n19: 60EB\n1a: F000" microcode = "MyM:\n00: 00f8000\n01: 008a000\n02: 0000100\n03: 0078080\n04: 00FA080\n05: 0078000\n06: 00B8080\n07: 0000000\n08: 0384000\n09: 1040000\n0a: 0138080\n0b: 00B0180\n0c: 0190180\n0d: 0280000\n0e: 0980000\n0f: 0130180\n10: 0380000\n11: 0A80000\n12: 0130180\n13: 0380000\n14: 0c80000\n15: 0130180\n16: 0041000\n17: 0380000\n18: 000061A\n19: 1A00A98\n1a: 0130180\n1b: 0000400\n1c: 02C0000\n1d: 1040000\n1e: 0118180\n1f: 0000780\n20: 0380000\n21: 0A80000\n22: 000041C\n23: 0000180\n24: 000041C\n25: 00004A8\n26: 000071C\n27: 0000180\n28: 0000700\n29: 000029C\n2a: 0000180\n2b: 00A8000\n2c: 0384000\n2d: 0980000\n2e: 0138000\n2f: 0150180" k_one = "K1:\n00: 0B\n01: 0C\n02: 0D\n03: 10\n04: 13\n05: 16\n06: 1C\n07: 22\n08: 24\n09: 20\n0a: 2B\n0b: 00\n0c: 00\n0d: 00\n0e: 00\n0f: 1F" k_two = "K2:\n00: 03\n01: 04\n02: 05\n03: 08" the_rest = "PC:\n00\n\nASR:\n00\n\nAR:\n0000\n\nHR:\n0000\n\nGR0:\n0000\n\nGR1:\n0000\n\nGR2:\n0000\n\nGR3:\n0000\n\nIR:\n0000\n\nMyPC:\n00\n\nSMyPC:\n00\n\nLC:\n00\n\nO_flag:\n\nC_flag:\n\nN_flag:\n\nZ_flag:\n\nL_flag:\nEnd_of_dump_file" # amount of files to generate for filenumber in range(1): #open file to write to with open('testcase'+str(filenumber)+".mia", 'w') as this_file: ###START OF PM### #write program lines this_file.write(program) this_file.write("\n") #write zeros after the program and before the numbers to sort #hex 0x1b to 0xdf for hex_int_pm in range(27,224): this_file.write(hex(hex_int_pm).split("x")[1]+": 0000\n") #write the unsorted list of numbers #hex 0xe0 to 0xff for numbers_amnt in range(224,256): hex_digit = ""; #generate a 4 digit hex number for digit_index in range(4): randomint = random.randint(0,len(hex_numbers)-1) hex_digit+=hex_numbers[randomint] this_file.write(hex(numbers_amnt).split("x")[1]+": "+hex_digit+"\n") this_file.write("\n") ###END OF PM## ###START OF MyM### #write microcode lines this_file.write(microcode) this_file.write("\n") #write zeros to rest #hex 0x30 to 7f for hex_int_myp in range(48,128): this_file.write(hex(hex_int_myp).split("x")[1]+": 0000000\n") this_file.write("\n") ###END OF MyP### #write k1 this_file.write(k_one) this_file.write("\n\n") #write k2 this_file.write(k_two) this_file.write("\n\n") #write the rest this_file.write(the_rest)
77618758fa5b360c953f7b43c3892962b7100650
[ "Python" ]
1
Python
RorroS/tsea83-labs
b6a50204d81e2e4eef074335dc3bf6b556d3b3c9
e8fff3724550ccdbdc23bf74af2395868067c012
refs/heads/master
<file_sep>#pragma once #include <string> typedef unsigned char byte; using namespace std; class ByteArray { private: byte* bytes; int length; public: ByteArray(int length); explicit ByteArray(string text); ByteArray(const ByteArray &byteArray); ~ByteArray(); byte & operator[] (int i); const byte operator[] (int i) const; ByteArray& operator = (const ByteArray& byteArray); //ByteArray& operator = (ByteArray&& byteArray); int getLength() const; string toString() const; friend std::ostream& operator << (std::ostream& out, const ByteArray& byteArray); }; <file_sep>#include "FileHelper.h" #include <stdexcept> #include <fstream> #include <sstream> namespace files { FileHelper::FileHelper(int labNum) { if (labNum < 0 || labNum > 4) throw new invalid_argument("This lab is not listed"); path = PROJECT_PATH + "\\lab" + to_string(labNum) +"\\files\\"; } FileHelper::~FileHelper() { } string FileHelper::readSampleText() { return readText(path + SAMPLE_TEXT); } void FileHelper::writeEncryptionKey(ByteArray key) { writeBytes(path + ENCRYPTION_KEY, key); } ByteArray FileHelper::readEncryptionKey() { return readBytes(path + ENCRYPTION_KEY); } void FileHelper::writeCipherText(ByteArray text) { writeBytes(path + CIPHER_TEXT, text); } ByteArray FileHelper::readCipherText() { return readBytes(path + CIPHER_TEXT); } void FileHelper::writeDecryptedText(string text) { writeText(path + DECRYPTED_TEXT, text); } string FileHelper::readDecryptedText() { return readText(path + DECRYPTED_TEXT); } string FileHelper::readText(const string path) { string tempText; stringstream fullText; ifstream in(path); if (in.is_open()) { while (getline(in, tempText)) { fullText << tempText; if (!in.eof()) fullText << endl; } } in.close(); return fullText.str(); } void FileHelper::writeText(const string path, const string text) { ofstream out(path, ios::out); if (out.is_open()) { out << text; } out.close(); } const ByteArray FileHelper::readBytes(const string path) { string tempText; stringstream fullText; ifstream in(path, ios_base::binary); if (in.is_open()) { while (getline(in, tempText)) { fullText << tempText; if (!in.eof()) fullText << endl; } } in.close(); return ByteArray(fullText.str()); } void FileHelper::writeBytes(string path, const ByteArray text) { ofstream out(path, ios_base::binary); if (out.is_open()) { for (int i = 0; i < text.getLength(); i++) { out << text[i]; } } out.close(); } }<file_sep>#include "VernamCipher.h" #include <ctime> ByteArray algorithm::VernamCipher::generateKey(const int length) { ByteArray bytes = length; srand(time(0)); for (int i = 0; i < length; i++) { bytes[i] = ((rand() % (255 + 1 - 0)) + 0); } return bytes; } const ByteArray algorithm::VernamCipher::encrypt(const string text, const ByteArray key) { ByteArray bytes = key.getLength(); ByteArray text_ = ByteArray((string)text); for (int i = 0; i < key.getLength(); i++) { bytes[i] = key[i] ^ text_[i]; } return bytes; } string algorithm::VernamCipher::decrypt(const ByteArray text, const ByteArray key) { ByteArray bytes = key.getLength(); for (int i = 0; i < key.getLength(); i++) { bytes[i] = key[i] ^ text[i]; } return bytes.toString(); } <file_sep>#pragma once #include <string> #include "../common/ByteArray.h" using namespace std; namespace files { class FileHelper { private: const string PROJECT_PATH = "C:\\MY DATA\\Учёба\\4 курс\\8 семестр\\Защита информации\\Лабы\\ZI"; const string LAB_PATH = PROJECT_PATH + "\\lab%d\\files\\"; const string SAMPLE_TEXT = "sample_text.txt"; const string ENCRYPTION_KEY = "encryption_key.txt"; const string CIPHER_TEXT = "cipher_text.txt"; const string DECRYPTED_TEXT = "decrypted_text.txt"; string path; string readText(const string path); void writeText(const string path, const string text); const ByteArray readBytes(const string path); void writeBytes(string path, const ByteArray text); public: FileHelper(int labNum); ~FileHelper(); string readSampleText(); void writeEncryptionKey(ByteArray key); ByteArray readEncryptionKey(); void writeCipherText(ByteArray text); ByteArray readCipherText(); void writeDecryptedText(string text); string readDecryptedText(); }; }<file_sep>// ZI.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> #include <clocale> #include <Windows.h> #include "common/FileHelper.h" #include "lab1/algorithm/VernamCipher.h" using namespace std; using namespace files; using namespace algorithm; void lab1(); int main() { setlocale(LC_ALL, "Rus"); lab1(); cin.get(); return 0; } void lab1() { FileHelper helper = 1; string sampleText = helper.readSampleText(); ByteArray key = VernamCipher::generateKey(sampleText.length()); helper.writeEncryptionKey(key); key = helper.readEncryptionKey(); ByteArray en = VernamCipher::encrypt(sampleText, key); helper.writeCipherText(en); en = helper.readCipherText(); string de = VernamCipher::decrypt(en, key); cout << "Изначальный текст:\n" << sampleText << endl << endl; cout << "Ключ шифрования:\n" << key << endl << endl; cout << "Зашифрованный текст:\n" << en << endl << endl; cout << "Расшифрованный текст:\n" << de; }<file_sep>#pragma once #include <string> #include "../../common/ByteArray.h" typedef unsigned char byte; using namespace std; namespace algorithm { class VernamCipher { private: VernamCipher() { } public: static ByteArray generateKey(const int length); static const ByteArray encrypt(const string text, const ByteArray key); static string decrypt(const ByteArray text, const ByteArray key); }; }<file_sep>#include "ByteArray.h" #include <stdexcept> #include <iostream> ByteArray::ByteArray(int _length) { if (_length < 1) throw new invalid_argument("Длина должна быть больше 0"); length = _length; bytes = new byte[length]; } ByteArray::ByteArray(const string text) { if (text.length() < 1) throw new invalid_argument("Длина строки должна быть больше 0"); length = text.length(); bytes = new byte[length]; const char* temp = text.c_str(); for (int i = 0; i < length; i++) { bytes[i] = temp[i]; } } ByteArray::ByteArray(const ByteArray& byteArray) { length = byteArray.length; bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = byteArray.bytes[i]; } } ByteArray::~ByteArray() { delete[] bytes; } byte & ByteArray::operator[](int i) { if (i < 0 || i > length) throw new out_of_range("Выход за пределы массива. Размер массива:" + to_string(length) + ". Индекс:" + to_string(i) + "."); return bytes[i]; } const byte ByteArray::operator[](int i) const { if (i < 0 || i > length) throw new out_of_range("Выход за пределы массива. Размер массива:" + to_string(length) + ". Индекс:" + to_string(i) + "."); return bytes[i]; } ByteArray& ByteArray::operator=(const ByteArray& byteArray) { if (length != byteArray.length) { delete[] bytes; bytes = new byte[byteArray.length]; } length = byteArray.length; for (int i = 0; i < length; i++) { bytes[i] = byteArray.bytes[i]; } return *this; } //ByteArray& ByteArray::operator=(ByteArray&& byteArray) { // swap(length, byteArray.length); // swap(bytes, byteArray.bytes); // // return *this; //} int ByteArray::getLength() const { return length; } string ByteArray::toString() const { return string((char*)bytes, length); } std::ostream& operator<<(std::ostream& _out, const ByteArray& _a) { _out << _a.toString(); return _out; }
0fceca8df10d158d0a90cc660b738782a95e31c2
[ "C++" ]
7
C++
battisq/ZI
8dfcbf33b97c7296cd9001cf24bc139daede3079
d1717ff3cae9d380562f18d158a6dab74f6b9e1b
refs/heads/master
<repo_name>Lneedy/elementui<file_sep>/components/card.js import { BootstrapElement } from "./element"; /** * See documentation at: https://getbootstrap.com/docs/5.0/components/buttons/ */ export class Cards extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super() // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <div class="card" style="width: 18rem;"> <slot name="image"></slot> <div class="card-body"> <h5 class="card-title"><slot name="title"></slot></h5> <p class="card-text"><slot name="text"></slot></p> <a href="#"><slot name="button"></slot></a> </div> </div> ` this.element = this.shadowRoot.querySelector("div") } // The connection callback. connectedCallback() { super.connectedCallback() // The class... } } customElements.define('bootstrap-cards', Cards)<file_sep>/components/collapse.js import { BootstrapElement } from "./element"; import * as bootstrap from 'bootstrap/dist/js/bootstrap.js'; export class Collapse extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super() // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <div class="collapse"> <div class="card card-body"> <slot></slot> </div> </div> ` this.element = this.shadowRoot.querySelector(".collapse") this.onshow = null this.element.addEventListener("show.bs.collapse", ()=>{ if(this.onshow != undefined){ this.onshow() } }) this.onshown = null this.element.addEventListener("shown.bs.collapse", ()=>{ if(this.onshown != undefined){ this.onshown() } }) this.onhide = null this.element.addEventListener("hide.bs.collapse", ()=>{ if(this.onhide != undefined){ this.onhide() } }) this.onhidden = null this.element.addEventListener("hidden.bs.collapse", ()=>{ if(this.onhidden != undefined){ this.onhidden() } }) this.bsCollapse = new bootstrap.Collapse(this.element, { toggle: false }) } // The connection callback. connectedCallback() { super.connectedCallback() } // Toggle the panel. toggle() { this.bsCollapse.toggle() } // show the panel show(){ this.bsCollapse.show() } hide(){ this.bsCollapse.hide() } dispose() { this.bsCollapse.dispose() } } customElements.define('bootstrap-collapse', Collapse)<file_sep>/components/buttons.js import { BootstrapElement } from "./element"; /** * See documentation at: https://getbootstrap.com/docs/5.0/components/buttons/ */ export class Button extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super() // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <button type="button" class="btn"> <slot> </slot> </button> ` this.element = this.shadowRoot.querySelector("button") } // The connection callback. connectedCallback() { super.connectedCallback() // The class... } } customElements.define('bootstrap-button', Button) export class ButtonGroup extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super() // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <div class="btn-group" role="group"> <slot></slot> </div> ` this.element = this.shadowRoot.querySelector(".btn-group") } // The connection callback. connectedCallback() { super.connectedCallback() } } customElements.define('bootstrap-button-group', ButtonGroup)<file_sep>/components/listGroup.js import { BootstrapElement } from "./element"; /** * See documentation at: https://getbootstrap.com/docs/5.0/components/buttons/ */ export class ListGroup extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super(); // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <style> </style> <ul class="list-group"> <slot></slot> </ul> `; this.element = this.shadowRoot.querySelector("ul"); } // The connection callback. connectedCallback() { super.connectedCallback(); // The class... } setElementAttributes() { super.setElementAttributes(); console.log("if I can change anyone can change!"); for(var i=0; i < this.children.length; i++){ if(this.hasAttribute("list-group-flush")){ this.children[i].setListGroupFlush() }else{ this.children[i].resetListGroupFlush() } if(this.hasAttribute("list-group-numbered")){ this.children[i].displayBeforeSpan() }else{ this.children[i].hideBeforeSpan() } } } } customElements.define("bootstrap-list-group", ListGroup); /** * See documentation at: https://getbootstrap.com/docs/5.0/components/buttons/ */ export class ListGroupItem extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super(); // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <style> .rounded-top-border { backgroud-color: pink; border-top-right-radius: .25em; border-top-left-radius: .25em; } .list-group-flush { border-width: 0 0 1px; } .last{ border: none; } span{ padding-right: 5px; display: none; } </style> <li class="list-group-item"><span></span><slot></slot></li> `; this.element = this.shadowRoot.querySelector("li"); this.before = this.shadowRoot.querySelector("span"); this.parentNode.children[0].element.classList.add("rounded-top-border"); // in case the parent has attribute list-group-flush if (this.parentNode.hasAttribute("list-group-flush")) { this.setListGroupFlush() } let index = Array.from(this.parentNode.children).indexOf(this) this.before.innerHTML = ++index +"." if(this.parentNode.hasAttribute("list-group-numbered")){ this.displayBeforeSpan() } } displayBeforeSpan(){ this.before.style.display = "inline" } hideBeforeSpan(){ this.before.style.display = "none" } setListGroupFlush(){ this.element.classList.add("list-group-flush"); if ( this.parentNode.children[this.parentNode.children.length - 1].element != undefined ) { this.parentNode.children[ this.parentNode.children.length - 1 ].element.classList.add("last"); } } resetListGroupFlush(){ this.element.classList.remove("list-group-flush"); this.element.classList.remove("last"); } // The connection callback. connectedCallback() { super.connectedCallback(); // The class... } } customElements.define("bootstrap-list-group-item", ListGroupItem); <file_sep>/index.js import {Button} from "./components/buttons" import {ButtonGroup} from "./components/buttons" import {ButtonTest} from "./components/buttonsTest" import {Accordion, AccordionItem} from "./components/accordion" import {Collapse} from "./components/collapse" import {Alerts} from "./components/alerts" import {Badges} from "./components/badges" import {card} from "./components/card" import {img} from "./components/img" import {ListGroup} from "./components/listGroup" import {ListGroupItem} from "./components/listGroup" import {Link} from "./components/link" import {Modal} from "./components/modal" function main(){ /** That function will be call when the windows is loaded. */ let test = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <style> body { margin: 0; font-family: var(--bs-font-sans-serif); font-size: 1rem; font-weight: 400; line-height: 1.5; color: #212529; background-color: #fff; -webkit-text-size-adjust: 100%; -webkit-tap-highlight-color: transparent; } .grid{ display: flex; flex-direction: column; padding: 4px; } .grid div{ padding: 4px; } </style> <div class="grid"> <div> <bootstrap-button btn-outline-primary disabled>Disabled</bootstrap-button> <bootstrap-button btn-outline-primary>Enabled</bootstrap-button> </div> <div> <bootstrap-button-group> <bootstrap-button btn-primary>Left</bootstrap-button> <bootstrap-button btn-primary>Middle</bootstrap-button> <bootstrap-button btn-primary>Right</bootstrap-button> </bootstrap-button-group> </div> <div> <bootstrap-accordion always-open> <bootstrap-accordion-item show> <div slot="title">Accordion Item #1</div> <strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow. </bootstrap-accordion-item> <bootstrap-accordion-item> <div slot="title"> Accordion Item #2</div> <strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow. </bootstrap-accordion-item> <bootstrap-accordion-item> <div slot="title"> Accordion Item #3</div> <strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow. </bootstrap-accordion-item> </bootstrap-accordion> </div> <div> <div> <div> <bootstrap-button id="bootstrap-collapse-btn" btn-primary>Collapse</bootstrap-button> </div> <bootstrap-collapse> Some placeholder content for the collapse component. This panel is hidden by default but revealed when the user activates the relevant trigger. </bootstrap-collapse> </div> </div> <bootstrap-alerts alert-secondary>A simple primary alert—check it out!</bootstrap-alerts> <div> <bootstrap-badges badge bg-primary>Primary<bootstrap-badges> </div> <div> <bootstrap-button btn-primary position-relative> Profile <bootstrap-badges position-absolute top-0 start-100 translate-middle p-2 bg-danger border border-light rounded-circle> <bootstrap-badges visually-hidden>New alerts<bootstrap-badges> <bootstrap-badges> </bootstrap-button> </div> <div> <h1>Example heading<bootstrap-badges badge bg-primary>New<bootstrap-badges></h1> </div> <div> <h6>Example heading<bootstrap-badges badge bg-primary>New<bootstrap-badges></h6> </div> <bootstrap-cards> <bootstrap-images slot="image" src="https://www.w3schools.com/tags/img_girl.jpg"></bootstrap-images> <div slot="title">Card title</div> <div slot="text">Some quick example text to build on the card title and make up the bulk of the card's content.</div> <bootstrap-button slot="button" btn-primary>Go somewhere</bootstrap-button> </bootstrap-cards> <div style="width: 300px;"> <bootstrap-list-group list-group-flush> <bootstrap-list-group-item>An active item</bootstrap-list-group-item> <bootstrap-list-group-item>A second item</bootstrap-list-group-item> <bootstrap-list-group-item>A third item</bootstrap-list-group-item> <bootstrap-list-group-item>A fourth item</bootstrap-list-group-item> <bootstrap-list-group-item>And a fifth one</bootstrap-list-group-item> </bootstrap-list-group> </div> <div style="width: 300px;padding-top: 80px;" > <bootstrap-list-group> <bootstrap-link href="#" list-group-item-action active>The current link item</bootstrap-link> <bootstrap-link href="#" list-group-item-action>A second link item</bootstrap-link> <bootstrap-link href="#" list-group-item-action>A third link item</bootstrap-link> <bootstrap-link href="#" list-group-item-action>A fourth link item</bootstrap-link> <bootstrap-link href="#" list-group-item-action disabled>A disabled link item</bootstrap-link> </bootstrap-list-group> </div> <div style="width: 300px;padding-top: 80px;" > <bootstrap-button id="my-modal-btn" btn-primary>Modal</bootstrap-button> <bootstrap-modal-dialog> <div slot="modal-footer"> <bootstrap-button btn-secondary data-bs-dismiss="modal">Close</bootstrap-button> <bootstrap-button btn-primary>Save changes</bootstrap-button> </div> ... </bootstrap-modal-dialog> </div> ` document.body.appendChild(document.createRange().createContextualFragment(test)) let modalBtn = document.body.querySelector("#my-modal-btn") let modal = document.body.querySelector("bootstrap-modal") modalBtn.onclick = ()=>{ modal.show() } let collapse = document.body.querySelector("bootstrap-collapse") let collapse_btn = document.body.querySelector("#bootstrap-collapse-btn") collapse_btn.onclick = ()=>{ collapse.toggle() } collapse.onshown = ()=>{ console.log("---> collapse was shown!") } collapse.onhidden = ()=>{ console.log("---> collapse was hidden!") } } window.onload = ()=>{ main(); }<file_sep>/README.md # elementui ## Bootstrap 5 + webcomponents = elementui Why reinventing the wheel again and again. Boostrap is the perfect css framework for creating nice looking web application and webcompnents are perfect for encapsulate all html/css code into reusable html element. <file_sep>/components/plain.js /** * Sample empty component, can be use to start a new component. */ export class Empty extends HTMLElement { // attributes. // Create the applicaiton view. constructor() { super() // Set the shadow dom. this.attachShadow({ mode: 'open' }); // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <style> ${theme} #container{ } </style> <div id="container"> </div> ` // give the focus to the input. let container = this.shadowRoot.querySelector("#container") } // The connection callback. connectedCallback() { } // Call search event. hello() { } } customElements.define('boostrap-5-empty', Empty)<file_sep>/components/modal.js import { BootstrapElement } from "./element"; import * as bootstrap from 'bootstrap/dist/js/bootstrap.js'; /** * See documentation at: https://getbootstrap.com/docs/5.0/components/buttons/ */ export class Modal extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super() // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <slot></slot> </div> ` this.element = this.shadowRoot.querySelector("#myModal") // this.myInput = this.shadowRoot.querySelector("#myInput") this.Modal = new bootstrap.Modal(this.element, { keyboard: false }) } // The connection callback. connectedCallback() { super.connectedCallback() // The class... } show(){ this.Modal.toggle() } hide(){ this.Modal.dismiss() } } customElements.define('bootstrap-modal', Modal) /** * See documentation at: https://getbootstrap.com/docs/5.0/components/buttons/ */ export class ModalDialog extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super() // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Modal --> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <slot></slot> </div> <div class="modal-footer"> <slot name="modal-footer"> </slot> </div> </div> </div> ` this.element = this.shadowRoot.querySelector(".modal-dialog") } // The connection callback. connectedCallback() { super.connectedCallback() // The class... } } customElements.define('bootstrap-modal-dialog', ModalDialog)<file_sep>/components/element.js /** * Sample empty component, can be use to start a new component. */ export class BootstrapElement extends HTMLElement { // attributes. // Create the applicaiton view. constructor() { super() // Set the shadow dom. this.attachShadow({ mode: 'open' }); // The boostrap element. this.element = null; // Innitialisation of the layout. this.shadowRoot.innerHTML = `` const observer = new MutationObserver(records => { this.setElementAttributes() }) // Notify me of style changes observer.observe(this, { attributes: true }); } // Make the sub-element keep same attribute as it web-component. setElementAttributes() { if(this.className_ == undefined){ this.className_ = this.element.className } this.element.className = this.className_ for (var i = 0; i < this.attributes.length; i++) { var attrib = this.attributes[i]; if(attrib.name == "tabindex" || attrib.name == "src" || attrib.name == "href" ){ this.element.setAttribute(attrib.name, attrib.value) }else{ this.element.classList.add(attrib.name) } } } // The connection callback. connectedCallback() { this.setElementAttributes() } } customElements.define('boostrap-element', BootstrapElement)<file_sep>/components/accordion.js import { BootstrapElement } from "./element"; import * as bootstrap from 'bootstrap/dist/js/bootstrap.js'; export class Accordion extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super() // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <div class="accordion"></div> <slot></slot> ` this.element = this.shadowRoot.querySelector(".accordion") } // The connection callback. connectedCallback() { super.connectedCallback() // The class... for (var i = 0; i < this.children.length; i++) { let item = this.children[i] if (this.getAttribute("always-open") != undefined) { item.onshow = () => { for (var i = 0; i < this.children.length; i++) { this.children[i].hide() } } } } } } customElements.define('bootstrap-accordion', Accordion) export class AccordionItem extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super() // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <div class="accordion-item"> <h2 class="accordion-header" id="headingOne"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> <slot id="accordion-item-title" name="title"></slot> </button> </h2> <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="accordion-body"> <slot></slot> </div> </div> </div> ` this.element = this.shadowRoot.querySelector(".accordion-item") // get the collapse element this.bsCollapse = new bootstrap.Collapse(this.shadowRoot.querySelector("#collapseOne"), { toggle: false }) this.button = this.shadowRoot.querySelector(".accordion-button") this.button.onclick = () => { this.bsCollapse.toggle() } this.shadowRoot.querySelector("#collapseOne").addEventListener("hide.bs.collapse", () => { this.button.classList.add("collapsed") if (this.onhide != undefined) { this.onhide(this) } }) this.shadowRoot.querySelector("#collapseOne").addEventListener("show.bs.collapse", () => { this.button.classList.remove("collapsed") if (this.onshow != undefined) { this.onshow(this) } }) this.body = this.shadowRoot.querySelector(".accordion-body") this.onshow = null this.onshown = null this.shadowRoot.querySelector("#collapseOne").addEventListener("shown.bs.collapse", () => { if (this.onshown != undefined) { this.onshown(this) } }) this.onhide = null this.shadowRoot.querySelector("#collapseOne").addEventListener("hide.bs.collapse", () => { }) this.onhidden = null this.shadowRoot.querySelector("#collapseOne").addEventListener("hidden.bs.collapse", () => { if (this.onhidden != undefined) { this.onhidden(this) } }) } // show the panel show() { this.bsCollapse.show() } hide() { this.bsCollapse.hide() } // The connection callback. connectedCallback() { super.connectedCallback() } } customElements.define('bootstrap-accordion-item', AccordionItem)<file_sep>/components/link.js import { BootstrapElement } from "./element"; /** * See documentation at: https://getbootstrap.com/docs/5.0/components/buttons/ */ export class Link extends BootstrapElement { // attributes. // Create the applicaiton view. constructor() { super(); // Innitialisation of the layout. this.shadowRoot.innerHTML = ` <link href="css/bootstrap.min.css" rel="stylesheet"> <style> .rounded-top-border { backgroud-color: pink; border-top-right-radius: .25em; border-top-left-radius: .25em; } .list-group-flush { border-width: 0 0 1px; } .last{ border: none; } span{ padding-right: 5px; display: none; } </style> <a href="" class="list-group-item list-group-item-action"><span></span><slot></slot></a> `; this.element = this.shadowRoot.querySelector("a"); this.before = this.shadowRoot.querySelector("span"); this.parentNode.children[0].element.classList.add("rounded-top-border"); // in case the parent has attribute list-group-flush if (this.parentNode.hasAttribute("list-group-flush")) { this.setListGroupFlush(); } } // The connection callback. connectedCallback() { super.connectedCallback(); // The class... } setListGroupFlush() { this.element.classList.add("list-group-flush"); if ( this.parentNode.children[this.parentNode.children.length - 1].element != undefined ) { this.parentNode.children[ this.parentNode.children.length - 1 ].element.classList.add("last"); } } resetListGroupFlush() { this.element.classList.remove("list-group-flush"); this.element.classList.remove("last"); } displayBeforeSpan(){ this.before.style.display = "inline" } hideBeforeSpan(){ this.before.style.display = "none" } } customElements.define("bootstrap-link", Link);
fa81d012fe0d3efe1d9ad19e017609c6962da98d
[ "JavaScript", "Markdown" ]
11
JavaScript
Lneedy/elementui
a6cbcefa4274fa2ac376443451342063f94183f8
8cc8e2bef8d62666ad2f08a43e2461f95c4e7ab5
refs/heads/master
<repo_name>akirobudo/web<file_sep>/file.php <?php if(isset($_SERVER['HTTP_REFERER']) && isset($_GET["ur"])) { $link = base64_decode($_GET["ur"]); $fichero = 'file/'.$link; if (file_exists($fichero)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($fichero).'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($fichero)); readfile($fichero); exit; } if (preg_match("/akirobuu.herokuapp.com/", $_SERVER["HTTP_REFERER"])){ readfile($fichero); }else{ header('Location: '.'https://sites.google.com/view/httpserver/h'); } }else{ header('Location: '.'https://sites.google.com/view/httpserver/h'); } ?> <file_sep>/wo.php <?php if(isset($_GET["ur"])){ $link = base64_decode($_GET["ur"]); if (preg_match("/ehi/i", $link)){ $img = 'HTTP_INJECTOR.svg'; $imgt = 'HTTP_INJECTOR.png'; } if (preg_match("/zxc/i", $link)){ $img = 'HTTP_CUSTOM.svg'; $imgt = 'HTTP_CUSTOM.png'; } $sis = true; }else { $link = 'NO SE ENCONTRO NINGUN SERVER.'; $sis = 'false'; $img = 'not.svg'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>URL AKIROBUU</title> <meta name="robots" content="noindex, nofollow"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta property="og:url" content="https://cut-urls.com/st?api=96699ad00f4656753d472c19f94f673983a445bb&url=https://akirobuu.herokuapp.com/wo.php?ur=<?php echo $link; ?>" /> <meta property="og:type" content="Website" /> <meta property="og:title" content="<?php echo $link; ?>" /> <meta property="og:image" content="https://akirobudo.github.io/web/<?php echo $imgt; ?>" /> <link rel="stylesheet" href="https://unpkg.com/picnic"> </head> <style type="text/css"> body{ background-color: #fcfcfc; } article{ text-align: center; } .centered{ text-align:center; } .tu{ margin: 5px 20% 0px 20%; text-align: center; } #myProgress { width: 100%; background-color: #ffffff; text-align: center; } #myBar { width: 10%; height: 30px; background-color: #4CAF50; text-align: center; line-height: 30px; color: white; text-align: center; } a{ color: white; } .aa{ color: black; } .footer { left: 0; bottom: 0; width: 100%; text-align: center; } </style> <body> <article class="card ma"> <header> <h2><a href="https://sites.google.com/view/httpserver/h" class="aa">SERVER AKIRUBUU</a><span class="label success">Exito</span></h2> </header> </article> <div class="centered"> <div class="flex"> <div class="third tu"> <article class="card"> <header> <h3><?php echo $link; ?></h3> </header> <footer> <img class="stack" src="<?php echo $img; ?>"> <div id="myProgress"> <span>DESCARGANDO..</span> <div id="myBar">0%</div> <hr/> <span id="note" style="display: none;">¿No funciona? <a style="color: #0366d6;" href="<?php echo 'https://akirobuu.herokuapp.com/file.php?ur='. base64_encode($link); ?>">Link directo</a></span> </div> </footer> </article> </div> </div> </div> <div class="footer"> <div> <iframe data-aa="1189078" src="//acceptable.a-ads.com/1189078" scrolling="no" style="border:0px; padding:0; overflow:hidden" allowtransparency="true"></iframe> </div> <article class="card"> <header> <span>Entra a nuestra web para mas Servers.</span> <button class='success'><a href="https://sites.google.com/view/httpserver/h">Entrar</a></button> </header> </article> </div> <script> if(<?php echo $sis ?>){ var elem = document.getElementById("myBar"); var width = 10; var id = setInterval(frame, 50); } function frame(){ if (width >= 100){ window.location.href = '<?php echo 'https://akirobuu.herokuapp.com/file.php?ur='. base64_encode($link); ?>'; setTimeout(function(){ document.getElementById('note').style.display = 'block'; }, 2000); clearInterval(id); }else{ width++; elem.style.width = width + '%'; elem.innerHTML = width * 1 + '%'; } } </script> </body> </html> <file_sep>/link.php <?php if(isset($_GET["ur"])) { $link = base64_decode($_GET["ur"]); if (preg_match("/ehi/i", $link)){ $img = 'HTTP_INJECTOR.png'; } if (preg_match("/zxc/i", $link)){ $img = 'HTTP_CUSTOM.png'; } if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), "google")){ $roob = false; }else{ $roob = true; header('Location: '.'https://cut-urls.com/st?api=96699ad00f4656753d472c19f94f673983a445bb&url=https://akirobuu.herokuapp.com/wo.php?ur='. $_GET["ur"]); } }else{ header('Location: '.'https://sites.google.com/view/httpserver/h'); } ?> <!DOCTYPE html> <html prefix="og: http://ogp.me/ns#"> <head> <meta name="googlebot" content="noindex" /> <meta property="og:image" content="https://akirobudo.github.io/web/<?php echo $img; ?>" /> <meta property="og:image:width" content="190" /> <meta property="og:image:height" content="240" /> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta property="og:url" content="https://cut-urls.com/st?api=96699ad00f4656753d472c19f94f673983a445bb&url=https://akirobuu.herokuapp.com/wo.php?ur=<?php echo base64_encode($link); ?>" /> <meta property="og:type" content="Website" /> <meta property="og:title" content="<?php echo $link; ?>" /> </head> <body> </body> </html>
3ab744d40623d1807a0d3743bc6013391922bea1
[ "PHP" ]
3
PHP
akirobudo/web
fdda4266f45395f4d3a2c1e72e9dd637806671fe
d6f499d82222135ab8ccfd430860a1148b076285
refs/heads/master
<file_sep>// Scroll-spy $('body').scrollspy({ target: '#nav-header', // スクロールスパイ対象ナビゲーション offset: 60 //切り替えポイントオフセット(ヘッダーの高さ) }); // .active クラスの取得 // スクロールが hero 領域の場合はヘッダーを初期化する var navToggler = function(){ // リンクの href の値(ページ内リンクID)を取得 var _hash = $('#nav-header a.active').attr('href'); // class付け替え作業 $('.site-header').toggleClass('is-scrolled', ( _hash != '#sect-hero')); }; // 初期位置取得 navToggler(); // スクロールイベント // issue: 現状 window でスクロールスパイのイベントが発生する... // https://github.com/twbs/bootstrap/issues/20086 $(window).on('activate.bs.scrollspy', function(){ navToggler(); }); <file_sep># Bootstrap4 - ペットクリニック【簡易版】 <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> - [Bootstrapの準備](#bootstrap%E3%81%AE%E6%BA%96%E5%82%99) - [Boostrap 4 のQuick Start を使用する場合](#boostrap-4-%E3%81%AEquick-start-%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B%E5%A0%B4%E5%90%88) - [Starter Templateを使用する場合](#starter-template%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B%E5%A0%B4%E5%90%88) - [gulpによるSass構築環境設定](#gulp%E3%81%AB%E3%82%88%E3%82%8Bsass%E6%A7%8B%E7%AF%89%E7%92%B0%E5%A2%83%E8%A8%AD%E5%AE%9A) - [Browser-sync(ブラウザ自動更新)の準備(オプショナル)](#browser-sync%E3%83%96%E3%83%A9%E3%82%A6%E3%82%B6%E8%87%AA%E5%8B%95%E6%9B%B4%E6%96%B0%E3%81%AE%E6%BA%96%E5%82%99%E3%82%AA%E3%83%97%E3%82%B7%E3%83%A7%E3%83%8A%E3%83%AB) - [Sass環境](#sass%E7%92%B0%E5%A2%83) - [Bootstrapの基本レイアウト - グリッドレイアウト](#bootstrap%E3%81%AE%E5%9F%BA%E6%9C%AC%E3%83%AC%E3%82%A4%E3%82%A2%E3%82%A6%E3%83%88---%E3%82%B0%E3%83%AA%E3%83%83%E3%83%89%E3%83%AC%E3%82%A4%E3%82%A2%E3%82%A6%E3%83%88) - [Bootstrapのカラムとブレークポイントを理解する](#bootstrap%E3%81%AE%E3%82%AB%E3%83%A9%E3%83%A0%E3%81%A8%E3%83%96%E3%83%AC%E3%83%BC%E3%82%AF%E3%83%9D%E3%82%A4%E3%83%B3%E3%83%88%E3%82%92%E7%90%86%E8%A7%A3%E3%81%99%E3%82%8B) - [ヘッダーの作成](#%E3%83%98%E3%83%83%E3%83%80%E3%83%BC%E3%81%AE%E4%BD%9C%E6%88%90) - [メインスライダーの作成 - bxslider](#%E3%83%A1%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%A9%E3%82%A4%E3%83%80%E3%83%BC%E3%81%AE%E4%BD%9C%E6%88%90---bxslider) - [セクションの作成「私たちのミッション」](#%E3%82%BB%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AE%E4%BD%9C%E6%88%90%E7%A7%81%E3%81%9F%E3%81%A1%E3%81%AE%E3%83%9F%E3%83%83%E3%82%B7%E3%83%A7%E3%83%B3) - [Bootstrap 4 のブレークポイントに合わせたメディアクエリ例](#bootstrap-4-%E3%81%AE%E3%83%96%E3%83%AC%E3%83%BC%E3%82%AF%E3%83%9D%E3%82%A4%E3%83%B3%E3%83%88%E3%81%AB%E5%90%88%E3%82%8F%E3%81%9B%E3%81%9F%E3%83%A1%E3%83%87%E3%82%A3%E3%82%A2%E3%82%AF%E3%82%A8%E3%83%AA%E4%BE%8B) - [セクションの作成「サービス」](#%E3%82%BB%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AE%E4%BD%9C%E6%88%90%E3%82%B5%E3%83%BC%E3%83%93%E3%82%B9) - [セクションの作成「スタッフ紹介」](#%E3%82%BB%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AE%E4%BD%9C%E6%88%90%E3%82%B9%E3%82%BF%E3%83%83%E3%83%95%E7%B4%B9%E4%BB%8B) - [セクションの作成「飼い主様の声」](#%E3%82%BB%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AE%E4%BD%9C%E6%88%90%E9%A3%BC%E3%81%84%E4%B8%BB%E6%A7%98%E3%81%AE%E5%A3%B0) - [お客様の声ブロックのレイアウト・装飾](#%E3%81%8A%E5%AE%A2%E6%A7%98%E3%81%AE%E5%A3%B0%E3%83%96%E3%83%AD%E3%83%83%E3%82%AF%E3%81%AE%E3%83%AC%E3%82%A4%E3%82%A2%E3%82%A6%E3%83%88%E3%83%BB%E8%A3%85%E9%A3%BE) - [引用部分レイアウト・装飾](#%E5%BC%95%E7%94%A8%E9%83%A8%E5%88%86%E3%83%AC%E3%82%A4%E3%82%A2%E3%82%A6%E3%83%88%E3%83%BB%E8%A3%85%E9%A3%BE) - [引用下部にフェード効果をつける](#%E5%BC%95%E7%94%A8%E4%B8%8B%E9%83%A8%E3%81%AB%E3%83%95%E3%82%A7%E3%83%BC%E3%83%89%E5%8A%B9%E6%9E%9C%E3%82%92%E3%81%A4%E3%81%91%E3%82%8B) - [背景画像指定](#%E8%83%8C%E6%99%AF%E7%94%BB%E5%83%8F%E6%8C%87%E5%AE%9A) - [フッターの作成](#%E3%83%95%E3%83%83%E3%82%BF%E3%83%BC%E3%81%AE%E4%BD%9C%E6%88%90) - [基本構造](#%E5%9F%BA%E6%9C%AC%E6%A7%8B%E9%80%A0) - [スタイル](#%E3%82%B9%E3%82%BF%E3%82%A4%E3%83%AB) - [ナビゲーションとスクロール位置の連動 - Scrollspy](#%E3%83%8A%E3%83%93%E3%82%B2%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%A8%E3%82%B9%E3%82%AF%E3%83%AD%E3%83%BC%E3%83%AB%E4%BD%8D%E7%BD%AE%E3%81%AE%E9%80%A3%E5%8B%95---scrollspy) - [`.active` のスタイリング](#active-%E3%81%AE%E3%82%B9%E3%82%BF%E3%82%A4%E3%83%AA%E3%83%B3%E3%82%B0) - [サイトヘッダーを固定し、ナビゲーションの伸縮アニメーションを追加する](#%E3%82%B5%E3%82%A4%E3%83%88%E3%83%98%E3%83%83%E3%83%80%E3%83%BC%E3%82%92%E5%9B%BA%E5%AE%9A%E3%81%97%E3%83%8A%E3%83%93%E3%82%B2%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AE%E4%BC%B8%E7%B8%AE%E3%82%A2%E3%83%8B%E3%83%A1%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E3%82%92%E8%BF%BD%E5%8A%A0%E3%81%99%E3%82%8B) - [ロゴにも伸縮アニメーションを追加する](#%E3%83%AD%E3%82%B4%E3%81%AB%E3%82%82%E4%BC%B8%E7%B8%AE%E3%82%A2%E3%83%8B%E3%83%A1%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E3%82%92%E8%BF%BD%E5%8A%A0%E3%81%99%E3%82%8B) - [Scrollspy用のJSを設定する](#scrollspy%E7%94%A8%E3%81%AEjs%E3%82%92%E8%A8%AD%E5%AE%9A%E3%81%99%E3%82%8B) - [スムーススクロールを実装する](#%E3%82%B9%E3%83%A0%E3%83%BC%E3%82%B9%E3%82%B9%E3%82%AF%E3%83%AD%E3%83%BC%E3%83%AB%E3%82%92%E5%AE%9F%E8%A3%85%E3%81%99%E3%82%8B) <!-- END doctoc generated TOC please keep comment here to allow auto update --> テキストファイル [Bootstrap 4 - ペットクリニック用テキスト](https://github.com/ipgotanda/bs4_pet_easy/blob/master/%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88.txt) * * * ## Bootstrapの準備 ### Boostrap 4 のQuick Start を使用する場合 CDNを利用する。 http://v4-alpha.getbootstrap.com/getting-started/introduction/#quick-start メインCSS ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">` ``` スクリプト関連 ```html <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>` ``` * jQueryは最新版 Ver. 3.x ### Starter Templateを使用する場合 http://v4-alpha.getbootstrap.com/getting-started/introduction/#starter-template ```html <!DOCTYPE html> <html lang="**ja**"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> </head> <body> <h1>Hello, world!</h1> <!-- jQuery first, then Tether, then Bootstrap JS. --> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html> ``` * `lang="ja"` にしておく * * * ## gulpによるSass構築環境設定 以下のファイルをコピーしてください。 ```bash 講師用フォルダ\Bootstrap4\gulp\dev.zip ``` **ポイント** * Sassのコンパイル * エラー通知 * エラー制御 ファイルを解凍し、プロジェクトディレクトリに配置します。 * * * ## Browser-sync(ブラウザ自動更新)の準備(オプショナル) [ブラウザの自動リロードを行うBrowser-sync - グローバルインストール編](https://quip.com/dozzAwswTXNr) **ポイント** * グローバル環境にインストールするとプロジェクト毎にインストールしなくてよくなる * gulp環境とは切り分ける * * * ## Sass環境 /project /dev 開発用フォルダ /scss style.scss Sassメインファイル _variables.scss 変数用パーツファイル /assets 本番用フォルダ /css CSSフォルダ /img 画像用フォルダ /js JSフォルダ scss/_variables.scss ```scss // テーマカラーの設定 $color-primary : #8a3f20; $color-secondary: #44bf5b; $color-base : #f8f8f8; $color-text : #000; $color-link : #000; ``` * * * ## Bootstrapの基本レイアウト - グリッドレイアウト [Image: file:///-/blob/NZYAAAyBfR4/HsdzRVsyBugECgaP5u56sA]http://v4-alpha.getbootstrap.com/layout/grid/ Bootstrap でのカラムレイアウトでは**Grid system (グリッドシステム)**と呼ばれるものが用意されています。 以下の3つのコードで形成されます。 **コンテンツの幅を画面幅に応じて変化させるコンテナ** **`.container`** * `.container`: 固定幅(ブレークポイントごとに固定幅が用意されている) * `.container-fluid`: 流動幅(ウィンドウサイズに従う) * 両クラスともに左右の内側余白 15px が設定されている **カラム用のコンテナ** `.row` `.container`と共に使用した際に、`.container`の内側余白をネガティブマージンで打ち消している。 つまりカラムが`.container`の幅に収まるようになる。 **カラム** **`.col-{breakpoint}-{colspan}`** Bootstrap4 より**Flexbox**によるレイアウト方法が採用されている。 * breakpoint: ブレークポイントのキーワードを指定 カラムデザインが有効化される範囲を表すキーワードで指定します(下記表参照) * colspan: カラムサイズ指定。1~12の数値で指定。 * カラムは最大12カラムで形成されるため、{colspan} の合計値が12を超えないように注意する 使用例 ```html <div class="container"> <div class="row"> <div class="col-md-8">8カラム .rowを使うと.containerにフィットします。 </div> <div class="col-md-4">4カラム<br />高さが違いますが高さが合います<br />3行目</div> </div> </div> ``` デモ: http://codepen.io/ipgotanda/pen/KabpoL?editors=1100 上記の例では 第1カラムが8/12(約67%)の幅, 第2カラムが4/12(約33%) の幅でレイアウトされる。 カラム数は 8+4=12 となり.container にきれいに収まる。 ### Bootstrapのカラムとブレークポイントを理解する A Extra Small Small Medium Large Extra Large ブレークポイントキーワード xs sm md lg xl クラス名接頭辞 .col- .col-sm- .col-md- .col-lg- .col-xl- カラム有効ウィンドウサイズ 0px以上 576px以上 768px以上 992px以上 1200px以上 http://v4-alpha.getbootstrap.com/layout/grid/#grid-options 【参考】フレックスボックスを使ったレイアウト http://the-echoplex.net/flexyboxes/ **オフセット - カラムの外側余白** カラム同士の間隔を取ったり、マージンを取る際に使用する `**.offset-{breakpoint}-{colspan}**` {breakpoint}, {colspan} の部分は上記カラムとブレークポイントの表を参照。 CSS の margin プロパティにより間隔ができる。 ```html <div class="container container-demo"> <div class="row"> <div class="col-md-6 col-demo">6カラム</div> <div class="col-md-4** **offset-md-2 col-demo">4カラム</div> </div> </div> ``` デモ: http://codepen.io/ipgotanda/pen/GrzymR?editors=1100 * * * ## ヘッダーの作成 **ベースコード** https://v4-alpha.getbootstrap.com/components/navbar/#supported-content **コードをサイト用にアレンジする** index.html ```html <header class="site-header"> <nav class="navbar navbar-toggleable-md navbar-light bg-faded"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> </div> </nav> **</header>** ``` **ヘッダー背景色の設定** index.html ```html <nav class="navbar navbar-toggleable-md **navbar-header**"> ...略... ``` * `.navbar-header` 追加 * `.bg-faded`, `.navbar-light` 削除 独自スタイルシートの読み込み index.html `<head>` 内 ```html <link rel="stylesheet" href="./assets/css/style.css"> ``` scss/style.scss ```scss .navbar-header { background: $color-primary; } ``` **ナビゲーションの位置調整** ```html <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav **ml-auto**"> ``` 元々設定されている `.mr-auto` を削除し、`.ml-auto` を追加します。 `.ml-auto` は `margin-left: auto` が設定されます。 これはBoostrapのスペーシングユティリティと呼ばれるもので、例えば * mt-3: `margin-top: 1rem` * mx-auto: `margin-left: auto; margin-right: auto`(xはx軸方向を表す。つまり right と left) * pb-5: `padding-bottom: 3rem;` となる。 デモ: http://codepen.io/ipgotanda/pen/JEzKxr さらに詳しい説明は以下を参照 スペーシングユティリティ https://v4-alpha.getbootstrap.com/utilities/spacing/ **ロゴの配置とサイズ調整** index.html ```html <h1 class="site-logo"> <a class="navbar-brand" href="#"><img src="./assets/img/logo.svg" alt="ウィズダムペットクリニック"></a> </h1> ``` scss/style.scss ```scss .site-logo { margin: 0; img { max-height: 60px; } } ``` **ナビゲーションのリンク色調整** scss/style.scss ```scss .navbar-header{ .nav-link { color: #fff; } } ``` **ナビゲーションアイコンの設定 - ioniconsによるオリジナルアイコンの導入** .navbar-light の削除により、ナビゲーション開閉ボタンのスタイルが外れてしまったので、独自スタイルを導入する。もちろんボタンデザインの柔軟性を持たせる理由もある。 CDNからIoniconsの導入する。 index.html `<head>` 内 ```html <!-- ionicons --> <link rel="stylesheet" href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link rel="stylesheet" href="./assets/css/style.css... ``` **アイコンの追加** index.html ```html <span class="navbar-toggler-icon"><i class="ion-navicon"></i></span> ``` dev/scss/style.scss ```scss .navbar-toggler { border-color: #fff; background-color: rgba(white, .2); } .navbar-toggler-icon { color: #fff; i:before { font-size: 30px; } } ``` * アイコンサイズは font-size で調整する * `rgba()` はCSSの関数だが、`rgba(white, .2)` のような指定は Sass でしかできないことに注意しておきたい。 `rgba(255, 255, 255, .2)` がCSS本来の指定方法 ここまでの結果を確認する。 ~ 991px [Image: file:///-/blob/NZYAAAyBfR4/toHxgeFc6J41trcZt3UysA] 992px~ [Image: file:///-/blob/NZYAAAyBfR4/n7OQlJUPOE3Q4gTAMtXfdQ] * * * ## メインスライダーの作成 - bxslider jQueryのプラグインbxsliderを使用してサイトのスプラッシュイメージとスライダーを作成します。 http://bxslider.com/ **bxslider準備** index.html `<head>` 内にCSS ```html <!-- bxslider --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/bxslider/4.2.6/jquery.bxslider.css"> ``` `</body>` 前にスクリプトを読み込む * jQuery 2.x * bxsliderスクリプト * 自前スクリプト ``` <!-- jQuery legacy --> <script src="https://cdn.jsdelivr.net/jquery/2.2.4/jquery.min.js"></script> <!-- bxslider --> <script src="https://cdn.jsdelivr.net/bxslider/4.2.6/jquery.bxslider.min.js"></script> <script src="./assets/js/script.js"></script> ``` スライダーのコードを追加する index.html ```html <div class=" sect-hero" id="sect-hero"> <ul class="bxslider"> <li> <img src="./assets/img/carousel_01.jpg" alt=""> </li> <li> <img src="./assets/img/carousel_02.jpg" alt=""> </li> <li> <img src="./assets/img/carousel_03.jpg" alt=""> </li> <li> <img src="./assets/img/carousel_04.jpg" alt=""> </li> <li> <img src="./assets/img/carousel_05.jpg" alt=""> </li> <li> <img src="./assets/img/carousel_06.jpg" alt=""> </li> </ul> </div><!-- /.sect-hero --> ``` * div で `.sect-hero` , `#sect-hero` を追加 * `.sect-hero` 内に スライダーのコードを追加し、 `.bxslider` とする assets/js/script.js ```js $('.bxslider').bxSlider({ adaptiveHeight: true, mode: 'fade', auto: true }); ``` * adaptiveHeight: 画像の高さが違う場合に true に設定するとアニメーションで調整してくれる * mode: モードの設定。 slide(スライドモード) と fade (フェードモード)がある * auto: 自動スライド送りの設定 bxsliderで設定できるオプションはたくさんあります。 bxsliderのオプション http://bxslider.com/options **bxsliderのCSSを上書きしスタイル調整する** scss/style.scss ```scss .sect-hero { .bx-wrapper { margin-bottom: 0; border: none; box-shadow: none; } .bx-wrapper .bx-pager, .bx-wrapper .bx-controls-auto { bottom: 30px; } .bx-wrapper .bx-pager.bx-default-pager a { background-color: #fff; } .bx-wrapper .bx-pager.bx-default-pager a.active { background-color: $color-primary; } } ``` * 親セレクタ `.sect-hero` から設定し、スタイルの優先度を上げるのと同時に、HERO部分のbxsliderであるというニュアンスを持たせ、bxsliderのデフォルトCSSをオーバーライドする * * * ## セクションの作成「私たちのミッション」 [Image: file:///-/blob/NZYAAAyBfR4/XmBvyxklrRLDrHVdrHfZOw]メインセクションを用意し、まず「私たちのミッション」セクションを作成します。 index.html ``` </div><!-- /.sect-hero --> <main class="site-main"> </main> ``` ```html <main class="site-main"> <div class="sect-mission sect-common"> <section> <div class="container"> <h2 class="sect-head text-center">私たちのミッション</h2> <div class="row"> <p class="col-md-5 offset-md-1">このたびは、私どものホームページーズにお応えすべく...</p> <p class="col-md-5">理想を実現するために、私たちはホスピタリティの向上に日々努めています。...</p> </div> </div> </section> </div> ``` * 見出し(h2) の `.text-center` はBootstrap のタイポグラフィに関するクラス * カラムサイズは5とし、文章が間延びしたようにならないように工夫する * `.offset-md-1` は前述したとおり、カラムの間隔を取るためのBootstrapのクラス Bootstrapのタイポグラフィに関するマニュアル https://v4-alpha.getbootstrap.com/utilities/typography/ scss/style.css ``` // セクション .sect-common { padding: 3rem 0; } // セクション見出し .sect-head { margin-bottom: 1em; } //ミッション .sect-mission { background: $color-secondary; background: linear-gradient(to bottom, lighten(yellow, 20%), $color-secondary); } ``` * linear-gradient() はCSS3のグラデーション関数 * `lighten()` はSassの色の明度を上げる関数(明度を下げる場合は `darken()` ) `**linear-gradient(角度, 開始色[ 開始位置], 中間もしくは終了色[ 開始位置][, 色[ 開始位置]...])**` * 角度のオプション: to left(開始位置: 右) | to right(開始位置: 左) | to bottom(開始位置: 上) | to top(開始位置: 下) | *deg(角度指定) `linear-gradient()` デモ: http://codepen.io/ipgotanda/pen/jyJoaZ?editors=1100 `lighten()` 関数 とりあえず参考サイト https://mbdb.jp/web/sass-color-generator.html * * * ## Bootstrap 4 のブレークポイントに合わせたメディアクエリ例 ``` @media only screen and (min-width: 576px) { // smサイズ 576px~ } @media only screen and (min-width: 768px) { // mdサイズ 768px~ } @media only screen and (min-width: 992px) { // lgサイズ 992px~ } @media only screen and (min-width: 1200px) { // xlサイズ 1200px~ } ``` * 1つのセレクタに対し、メディアクエリを複数使用する際の注意点として min-width が小さいものから指定すること * 768px background-color: green 544px background-color: yellow の順で指定すると、768px~ では背景色はyellowになる * * * ## セクションの作成「サービス」 [Image: file:///-/blob/NZYAAAyBfR4/d9l537RE1fr4O0ejGGW2mg]Bootstrapのグリッドシステムを利用して各ブレークポイントごとにレイアウトを切り替える **基本レイアウト** index.html ``` <div class="sect-service sect-common" id="sect-service"> <section> <div class="container"> <h2 class="sect-head text-center">サービス</h2> <div class="row"> <div class="col-sm-6 col-md-4 service"> </div> <div class="col-sm-6 col-md-4 service"> </div> <div class="col-sm-6 col-md-4 service"> </div> <div class="col-sm-6 col-md-4 service"> </div> <div class="col-sm-6 col-md-4 service"> </div> <div class="col-sm-6 col-md-4 service"> </div> </div> </div> </section> </div><!-- /.sect-service --> ``` * カラム毎に `.service` を追加し、各カラム内のデザインを指定できるようにする **カラム内詳細** index.html ``` <div class="col-md-4 col-sm-6 service"> <img src="./assets/img/icon-exoticpets.svg" alt="外来産ペット" class="service-icon"> <h3 class="text-center">外来産ペット</h3> <p>両生類、げっ歯類、鳥類などちょっと変わった動物のスペシャルケアをご用意しております。</p> </div> ``` * アイコン画像には `.service-icon` を追加 * h3の `.text-center` は Bootstrap のタイポグラフィユーティリティクラス https://v4-alpha.getbootstrap.com/utilities/typography/ 上記のコードを参考に各サービスごとのHTMLを完成させる。 **サービスカラムのスタイル設定** アイコンを中央揃えにし、サイズ・間隔を調整する。 index.html ``` <img src="./assets/img/icon-exoticpets.svg" alt="" class="d-block mx-auto service-icon"> ``` * `.d-block` は `display: block` を指定するBootstrap のディスプレイプロパティクラス https://v4-alpha.getbootstrap.com/utilities/display-property/ * `.mx-auto` は` margin-left`, `margin-right` を `auto` に設定するBootstrapのスペーシングユティリティクラス https://v4-alpha.getbootstrap.com/utilities/spacing/ dev/scss/style.scss ```scss .service-icon { width: 80px; margin-bottom: 1rem; } .service { margin-bottom: 2rem; @media (max-width: 575px) { padding: 0 2rem; } h3 { font-size: 1.2rem; font-weight: bold; } } ``` * * * ## セクションの作成「スタッフ紹介」 [Image: file:///-/blob/NZYAAAyBfR4/TAUOze6-28w7lOwLb_nWCA] **グリッドのネストで細かいレイアウト調整を行う** index.html ```html <div class="sect-staff sect-common" id="sect-staff"> <section> <div class="container"> <h2 class="sect-head text-center">スタッフ</h2> <div class="row"> <div class="col-lg-4 staff"> <div class="row"> <div class="col-sm-4 col-lg-12"> </div> <div class="col-sm-8 col-lg-12"> </div> </div><!-- /.row --> </div><!-- /.staff --> <div class="col-lg-4 staff"> <div class="row"> <div class="col-sm-4 col-lg-12"> </div> <div class="col-sm-8 col-lg-12"> </div> </div><!-- /.row --> </div><!-- /.staff --> <div class="col-lg-4 staff"> <div class="row"> <div class="col-sm-4 col-lg-12"> </div> <div class="col-sm-8 col-lg-12"> </div> </div><!-- /.row --> </div><!-- /.staff --> </div> </div> </section> </div><!-- /.sect-staff --> ``` * 各親カラムには `.staff` を追加 **カラム内詳細** index.html ```html <div class="col-lg-4 staff"> <div class="row"> <div class="col-sm-4 col-lg-12"> <img src="./assets/img/doctor-slump.jpg" alt="Dr.スランプ" class="d-block mx-auto staff-img"> </div> <div class="col-sm-8 col-lg-12"> <h3 class="text-center text-sm-left text-lg-center staff-name mb-3">Dr.スランプ</h3> <p class="staff-intro"> 私が獣医師を目指したのは、小学生のとき飼っていた犬がきっかけです。椎間板ヘルニアから下半身不随となり、同時に腎不全も発症してしまったのです。大学病院で腹膜透析を受けて調子が良くなった彼の顔を見て『私もこんな仕事がしたい!』と思ったのです。治療には色々な選択肢があると思います。その中で、皆様に寄り添ったその子にとって最高の治療ができるように心がけていきたいと思っています。 </p> </div> </div><!-- /.row --> </div><!-- /.staff --> ``` * スタッフ画像(img) * スタッフ画像には `.d-block`, `.mx-auto` クラスを追加。いずれも前述のようにBootstrap のディスプレイプロパティクラス * `.staff-img` も追加 * スタッフの名前(h3) * レスポンシブ対応した Bootstrap のタイポグラフィクラス( `.text-sm-left` 等)を与え、細かく行揃えを調整する * `.mb-3` で `margin-bottom` 設定 * `.staff-name` 追加 * スタッフの紹介文 * `.staff-intro` 追加 他スタッフも上記のコードを参考に完成させる。 **スタッフ紹介セクション背景色の設定** index.html ```scss .sect-staff { background: linear-gradient(to bottom, #e4d29d, darken(#e4d29d, 10%)); } ``` **スタッフカラムのスタイル設定** dev/scss/style.scss ```scss .staff { margin-bottom: 2rem; @media (min-width: 991px) { margin-bottom: 0; } } .staff-img { width: 80%; border-radius: 50%; margin-bottom: 1rem; @media (min-width: 576px) and (max-width: 991px) { width: 100%; margin-bottom: 0; } } .staff-intro { @media (max-width: 575px) { padding: 0 1rem; } } ``` * * * ## セクションの作成「飼い主様の声」 ![飼い主様の声](http://i.imgur.com/6qSiiXB.png) まずはレイアウト index.html ```html <div class="sect-voice" id="sect-voice"> <section> <div class="container-fluid"> <div class="row"> <blockquote class="col-sm-6 voice voice-01"></blockquote> <blockquote class="col-sm-6 voice voice-02"></blockquote> <blockquote class="col-sm-6 voice voice-03"></blockquote> <blockquote class="col-sm-6 voice voice-04"></blockquote> </div> </div> </section> </div><!-- /.sect-voice --> ``` * お客様の声なので引用を表す `blockquote` でマークアップする 詳細 ```html <div class="voice-quote"> <p> <span class="lead">今までどこの動物病院でも「うさぎは難しいから・・・」... </span> <span class="more"> ちゃんと診察できる動物に「うさぎ」って書いてあるだけのことはあります!... </span> </p> </div> ``` * `.voice-quote` はレイアウト用。`p` 内の `span.lead` は抜粋部分 * `span.more` はマウスオーバー時に表示される部分 ### お客様の声ブロックのレイアウト・装飾 dev/scss/style.scss ```scss .voice { margin-bottom: 0; min-height: 350px; position: relative; } ``` ``` .voice-quote { color: #fff; position: absolute; bottom: 0; left: 0; background-color: rgba(black,.6); border-radius: 0 1rem 0 0; padding: 1rem; } ``` ### 引用部分レイアウト・装飾 ```scss .voice-quote { ...略... p { margin-bottom: 0; line-height: 1.5; min-height: 4.5rem; max-height: 4.5rem; max-width: 25em; // 1行の最大文字数 transition: max-height .4s; overflow: hidden; .lead { font-size: 1rem; // bootstrapオーバーライド } .more { opacity: 0; transition: opacity .4s; } } //p // マウスオーバー時 &:hover { p { max-height: 15em; .more { opacity: 1; } } } ...略... } //.voice-quote ``` * マウスOFF時 * `.lead` 部分は3行の高さまで見せる * `.more` は `opacity: 0` で隠しておく * マウスON時 * `p` を高さ最大 `15em` までとする。 * マウスオーバー時に `.more` の部分を見せる ### 引用下部にフェード効果をつける コメントが続いているニュアンスを出すためのちょっとしたデザイン要素。 dev/scss/style.scss ```scss .voice-quote { ...略... &:after { content: ''; display: block; position: absolute; left: 0; bottom: 0; width: 100%; height: 4rem; background-image: linear-gradient(to top,rgba(black,.75), transparent); } &:hover:after { background-image: none; } } //.voice-quote ``` ### 背景画像指定 dev/scss/style.scss ```scss .voice { ...略... // 背景画像サイズ background-size: cover; background-position: center center; } .voice-01 { background-image: url(../img/testimonial_01.jpg); } .voice-02 { background-image: url(../img/testimonial_02.jpg); } .voice-03 { background-image: url(../img/testimonial_03.jpg); } .voice-04 { background-image: url(../img/testimonial_04.jpg); } ``` * * * ## フッターの作成 ### 基本構造 index.html ```html <footer class="site-footer"> <div class="container-fluid"> <div class="row"> <div class="col-md-6"> <p>フリーダイヤル <span class="site-footer-phone">0120-333-906</span> </p> <p> <small>&copy; 2017 <a href="#">Wisdom Pet Clinic</a>. All rights reserved.</small> </p> </div> <div class="col-md-6"> <nav class="nav justify-content-end nav-site-sitefooter"> <a class="nav-link" href="#">利用規約</a> <a class="nav-link" href="#">プライバシーポリシー</a> </nav> </div> </div> </div> </footer> ``` * `. justify-content-end` はBootstrap のレイアウトレスポンシブユティリティクラス [https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignmen](https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment) * ナビゲーションは Bootstrap のナビゲーションコンポーネント [https://v4-alpha.getbootstrap.com/components/navs/#base-nav](https://v4-alpha.getbootstrap.com/components/navs/#base-nav) ### スタイル dev/scss/style.scss ```scss // フッター .site-footer { background-color: #586d74; color: #fff; font-size: .9rem; padding: 1.5rem 0; a { color: #e0e6ae; } } .site-footer-phone { font-size: 1.4em; font-weight: bold; color: #e0e6ae; } .nav-site-footer { .nav-link { text-decoration: underline; } } ``` ## ナビゲーションとスクロール位置の連動 - Scrollspy ScrollspyとはBootstrapの機能の1つで、ナビゲーションのページ内リンクとリンク先のセクションを連動させます。 ページをスクロールしていき、そのセクションがブラウザの表示領域内に入ると、ナビゲーションのリンク部分がアクティブ化するというもの。 Scrollspy サンプルページ http://v4-alpha.getbootstrap.com/components/scrollspy/ ナビゲーションはマストではないが、Bootstrapコンポーネントである .navbar を利用すると良い http://v4-alpha.getbootstrap.com/components/navbar/ 基本スタイルの設定 ```scss body { position: relative; } ``` HTMLの設定 index.html ```html <header class="site-header"> <nav class="navbar navbar-toggleable-md navbar-header" id="nav-header"> ...略... ``` * .navbar に #nav-header を追加 Javascriptの設定 今回はscrollspy用のスクリプトファイルを用意します。 assets/js/scrollspy.js ```js $('body').scrollspy({ target: '#nav-header', offset: 60 }); ``` * `target:` には先程HTMLで追加したIDを指定 * `offset:` にはヘッダーの高さを指定。ナビがアクティブになるタイミングがウィンドウ上部より60px手前になる。 要素の検証等でナビゲーションの `.nav-link` に `.active` が追加、削除することを確認する ![scrollspy activeクラス](http://i.imgur.com/WXeCCTA.png) ### `.active` のスタイリング ``` scss .navbar-header{ .nav-link { color: #fff; &.active { box-shadow: 0 5px 0 0 #fff; } } } ``` * .active には box-shadow で下線を付ける ### サイトヘッダーを固定し、ナビゲーションの伸縮アニメーションを追加する ![ヘッダーアニメーション](http://i.imgur.com/4QomVkJ.gif) ヘッダーの固定化 dev/scss/style.scss ```scss .site-header { position: fixed; z-index: 10000; width: 100%; } ``` * `z-index: 10000` は保険のため 伸縮アニメーション dev/scss/style.scss ```scss .navbar-header { background: rgba($color-primary, .8); @media (min-width: 992px) { max-height: 120px; //transition用 transition: max-height 1s; // HERO以外にスクロールした時 .is-scrolled & { max-height: 60px; } } } //.navbar-header ``` * メディアクエリで lg サイズ以上という条件でアニメーションを設定にする( `@media(min-width: 992px)` )。なぜなら` max-height: 120px `はアコーディオン化したナビゲーションには不必要なため。逆に `max-height` があると表示が崩れる。 * `.is-scrolled` は次のステップで `.site-header` に追加されるクラス **【ポイント】** この is-scrolled というクラスをヘッダーへ追加・削除することで、ヘッダー内各パーツのスタイルを変化させる。その変化の過程を transition プロパティを使ってアニメーション化する。 ### Scrollspyのイベントを使用し、ヘッダーの高さをアニメーションさせる ここではHEROセクション(Home)以外に画面をスクロールした際にヘッダーの高さを縮める。HEROセクションに戻った際にはまたヘッダーの高さをもとに戻すというアニメーションを完成させていく。 assets/js/scrollspy.js ```js // .active クラスの取得 var navToggler = function(){ // リンクの href の値(ページ内リンクID)を取得 var _hash = $('#nav-header a.active').attr('href'); // #sect-hero以外の場合は // .site-headerに .is-scrolled クラスを追加する $('.site-header').toggleClass('is-scrolled', ( _hash != '#sect-hero')); }; // 初期位置取得 navToggler(); // スクロールイベント(Scrollspy) $(window).on('activate.bs.scrollspy', function(){ navToggler(); }); ``` * `navToggler` 関数は現在アクティブ化しているナビゲーションリンクを検知し、サイトヘッダー(.site-header)へ `.is-scrolled` の追加・削除を行う。 * `$(window).on('activate.bs.scrollspy', function(){...` はセクションが切り替わる際にイベントが発生するので、その度に実行させたい処理を function 内に記述する。この場合は `navToggler` を実行。 ### ロゴにも伸縮アニメーションを追加する dev/scss/style.scss ```scss .site-logo { margin: 0; font-size: 1rem; img { max-height: 60px; transition: max-height 1s; } @media (max-width: 767px) { img { max-height: 40px; } } // HERO以外にスクロールした時 @media (min-width: 768px) { .is-scrolled & { img { max-height: 40px; } } } } ``` * `.site-logo` の `font-size: 1rem` はBootstrap によって `h1` に `2.5rem` というフォントサイズの設定をオーバーライドしている。余白が空くのを防止する。 * md サイズ以下ではロゴの最大高を 40px とする。 * ロゴは md サイズ以降で、HERO以外に移動した場合、最大高を 40px とする。 * * * ## スムーススクロールを実装する スクリプトは次のサイトをベースにする。 http://goo.gl/WhTHd5 同じページのページ内リンクに反応する、「#」だけのリンクは除外する等の細かい処理が施されています。 assets/js/script.js ```js var topoffset = 60; //Use smooth scrolling when clicking on navigation $('.navbar a[href*=\\#]:not([href=\\#])').click(function() { if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top-topoffset+2 }, 500); return false; } //target.length } //click function }); //smooth scrolling ``` * オリジナルのJSから少し手直しを加えてあるので上記をコピーすること * `var topoffset = 60` は ヘッダーの高さ。移動する際にヘッダーの高さを差し引く。
a8c63b772163dd95a4635558ac2b2d21863d771b
[ "JavaScript", "Markdown" ]
2
JavaScript
ipgotanda/bs4_pet_easy
54afd5e556d1be4412a53bbdf5317bc1591e5d29
df2f0def5333678cb313d265cd8b7142a714f0a4
refs/heads/main
<file_sep>package db; public class DbIntegrityException extends RuntimeException{ //Como é subclasse de RuntimeException, então é obrigado ter o serial private static final long serialVersionUID = 1L; //Forçar a passar a mensagem para a superclasse public DbIntegrityException(String msg) { super(msg); } }
56e37673a418bc8e751c704b23f92822dafb030a
[ "Java" ]
1
Java
RobsondCCarneiro/demo-dao-jdbc
13aa38c1a1e0e473af9b4f77e43848b04ce13dc2
07d65b2e67608bdfe7dd4081d825e567c3e2fbf6
refs/heads/master
<repo_name>DBarreto1996/nodeTareas<file_sep>/tareas/tareas.js const fs = require('fs'); let listadoTareas = []; const guardarDB=()=>{ let data = JSON.stringify(listadoTareas); fs.writeFile('db/data.json', data, (err)=>{ if(err) throw new Error('No se pudo guardar',err) }); } const cargarDB =()=>{ try{ listadoTareas = require('../db/data.json'); }catch(error){ listadoTareas=[]; } } const crear = (descripcion)=>{ cargarDB(); let tarea={ descripcion, completado: false }; listadoTareas.push(tarea); guardarDB(); return tarea; } const getListado = ()=>{ cargarDB(); return listadoTareas; } const actualizar = (descripcion,completado = true)=>{ cargarDB(); let index=listadoTareas.findIndex( tar=>{ return tar.descripcion === descripcion; }) if(index>=0){ listadoTareas[index].completado= completado; guardarDB(); return true; }else{ return false; } } const eliminar = (descripcion) => { cargarDB(); let nuevoListado = listadoTareas.filter( tar =>{ return tar.descripcion !== descripcion; }); if(listadoTareas.length===nuevoListado.length){ return false; }else{ listadoTareas=nuevoListado; guardarDB(); return true; } } module.exports={ crear, getListado, actualizar, eliminar }<file_sep>/app.js //const argv = require('yargs').argv; const argv = require('./config/yargs.js').argv; const tarea = require('./tareas/tareas'); const colors = require('colors'); let comando = argv._[0]; switch( comando ){ case 'crear': let tareat = tarea.crear(argv.descripcion); console.log(tareat); break; case 'listar': let listado = tarea.getListado(); for(let tar of listado){ console.log('======Por Hacer========'.green); console.log(tar.descripcion); console.log('Estado: ', tar.completado); console.log('======================='.green); } console.log('Mostrar todas las tareas por hacer'); break; case 'actualizar': let actualizado = tarea.actualizar(argv.descripcion, argv.completado); console.log(actualizado); break; case 'eliminar': let eliminado=tarea.eliminar(argv.descripcion); console.log('Eliminado'); break; default: console.log('Comando no reconocido'); }<file_sep>/README.md ## Aplicacion de comandos app de tareas ``` npm install ```
3a4ac293a741a5ebbe87732bb93f6af5c3625515
[ "JavaScript", "Markdown" ]
3
JavaScript
DBarreto1996/nodeTareas
120c85e5c37c5d7eacbb19e94ebefa1fd69a340c
02fbb268675ff09d286cbe0710adac96c699674c
refs/heads/master
<repo_name>danielkokott/oz<file_sep>/test/scope.js 'use strict'; // Load modules const Code = require('code'); const Lab = require('lab'); const Oz = require('../lib'); // Declare internals const internals = {}; // Test shortcuts const lab = exports.lab = Lab.script(); const describe = lab.experiment; const it = lab.test; const expect = Code.expect; describe('Scope', () => { describe('validate()', () => { it('should return null for valid scope', () => { const scope = ['a', 'b', 'c']; expect(() => Oz.scope.validate(scope)).to.not.throw(); }); it('should return error when scope is null', () => { expect(() => Oz.scope.validate(null)).to.throw(); }); it('should return error when scope is not an array', () => { expect(() => Oz.scope.validate({})).to.throw(); }); it('should return error when scope contains non-string values', () => { const scope = ['a', 'b', 1]; expect(() => Oz.scope.validate(scope)).to.throw(); }); it('should return error when scope contains duplicates', () => { const scope = ['a', 'b', 'b']; expect(() => Oz.scope.validate(scope)).to.throw(); }); it('should return error when scope contains empty strings', () => { const scope = ['a', 'b', '']; expect(() => Oz.scope.validate(scope)).to.throw(); }); }); describe('isSubset()', () => { it('should return true when scope is a subset', () => { const scope = ['a', 'b', 'c']; const subset = ['a', 'c']; const isSubset = Oz.scope.isSubset(scope, subset); expect(isSubset).to.equal(true); }); it('should return false when scope is not a subset', () => { const scope = ['a']; const subset = ['a', 'c']; const isSubset = Oz.scope.isSubset(scope, subset); expect(isSubset).to.equal(false); }); it('should return false when scope is not a subset but equal length', () => { const scope = ['a', 'b']; const subset = ['a', 'c']; const isSubset = Oz.scope.isSubset(scope, subset); expect(isSubset).to.equal(false); }); it('should return false when scope is not a subset due to duplicates', () => { const scope = ['a', 'c', 'c', 'd']; const subset = ['a', 'c', 'c']; const isSubset = Oz.scope.isSubset(scope, subset); expect(isSubset).to.equal(false); }); }); describe('isEqual()', () => { it('compares scopes', () => { const scope = ['a', 'b', 'c']; expect(Oz.scope.isEqual(null, null)).to.equal(true); expect(Oz.scope.isEqual(scope, scope)).to.equal(true); expect(Oz.scope.isEqual(null, scope)).to.equal(false); expect(Oz.scope.isEqual(scope, null)).to.equal(false); expect(Oz.scope.isEqual(scope, [])).to.equal(false); expect(Oz.scope.isEqual([], scope)).to.equal(false); expect(Oz.scope.isEqual(scope, ['a', 'b', 'c'])).to.equal(true); expect(Oz.scope.isEqual(scope, ['a', 'c', 'd'])).to.equal(false); expect(Oz.scope.isEqual(['a', 'b', 'c'], scope)).to.equal(true); expect(Oz.scope.isEqual(['a', 'c', 'd'], scope)).to.equal(false); }); }); });
67ecba23f5bf3c2aed02ea0fccfe8b09285a4f72
[ "JavaScript" ]
1
JavaScript
danielkokott/oz
5797e5bd8b96d187c702643e9e8d862d146b9058
b159a8b2ae86954ab0ed23de137be2c504a80d28
refs/heads/master
<repo_name>geoffreycc/cookie_stand<file_sep>/README.md # cookie_stand 201 Class Project 2 References https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random http://html5doctor.com/ https://css-tricks.com/ http://paletton.com/ http://paletton.com/#uid=33C0u0klTnXpKzQnSsHjwiThidP https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children https://developer.mozilla.org/en-US/docs/Web/API/Node/lastChild <file_sep>/SalesDataPage/JS/app.js var hoursOpen = ['10am', '11am','12pm','1pm','2pm','3pm','4pm','5pm','6pm']; var storeArr = []; function Store(storeName, minCust, maxCust, avgCookie){ this.storeName = storeName; this.minCust = minCust; this.maxCust = maxCust; this.avgCookie = avgCookie; storeArr.push(this); } Store.prototype.hourlySales = []; Store.prototype.dailyTotal = 0; Store.prototype.getSalesNums = function(minNum, maxNum){ return(Math.random() * (maxNum - minNum)) + minNum; }; Store.prototype.totals = function(rand, maxN, minN, avgC, hour, hourlyS, dayTotal) { for(var s = 0; s < hour.length; s++) { this.hourlySales[s] = Math.floor(rand(minN, maxN) * avgC); this.dailyTotal += this.hourlySales[s]; } }; Store.prototype.render = function() { this.totals(this.getSalesNums, this.maxCust, this.minCust, this.avgCookie, hoursOpen, this.hourlySales, this.dailyTotal); storeTitle(this.storeName, this.hourlySales, this.dailyTotal, hoursOpen); }; function storeTitle(nameS, hourlyS, dayTotal, hours) { var storeNameTr = document.createElement('tr'); var totalTh = document.createElement('th'); var tableB = document.getElementById('storeInfo'); storeNameTr.textContent = nameS; tableB.appendChild(storeNameTr); for (var d = 0; d < hours.length; d++) { var space = / /g; var tdElm = document.createElement('td'); var noSpace = nameS.replace(space, ''); var noSpaceName = noSpace.toLowerCase(); storeNameTr.id = noSpaceName; tdElm.textContent = hourlyS[d]; storeNameTr.appendChild(tdElm); } totalTh.textContent = dayTotal; storeNameTr.appendChild(totalTh); } var TopRowRender = (function () { var topR = document.getElementById('hoursRow'); var totalTopTh = document.createElement('th'); var storeNameTh = document.createElement('th'); storeNameTh.textContent = 'Store Name'; topR.appendChild(storeNameTh); for (var h = 0; h < hoursOpen.length; h++) { var hourTh = document.createElement('th'); hourTh.textContent = hoursOpen[h]; topR.appendChild(hourTh); } totalTopTh.textContent = 'Total'; topR.appendChild(totalTopTh); var pikePlace = new Store('Pike Place', 17, 88, 5.2); //moved into iffy var seaTac = new Store('SeaTac Airport', 6, 24, 1.2); var southCenter = new Store('Southcenter', 11, 38, 1.9); var bellSquare = new Store('Bellevue Square', 20, 48, 3.3); var alki = new Store('Alki', 3, 24, 2.6); for (store in storeArr) { storeArr[store].render(); } }()); var space = / /g; function update(obj) { var nameStore = event.target.storeN.value; var noSpace = nameStore.replace(space, ''); var noSpaceName = noSpace.toLowerCase(); var parentRow = document.getElementById(noSpaceName); obj.totals(obj.getSalesNums, obj.maxCust, obj.minCust, obj.avgCookie, hoursOpen); for (var h = 0; h < hoursOpen.length; h++) { parentRow.children[h].textContent = obj.hourlySales[h]; } parentRow.lastChild.textContent = obj.dailyTotal; } var formEl = document.getElementById('newStoreInfo'); formEl.addEventListener('submit', function(event) { event.preventDefault(); var nameStore = event.target.storeN.value; var miniC = parseInt(event.target.minC.value); var maxiC = parseInt(event.target.maxC.value); var avgCook = parseFloat(event.target.avgCook.value); var noSpace = nameStore.replace(space, ''); var noSpaceName = noSpace.toLowerCase(); var storeNew = new Store(nameStore, miniC, maxiC, avgCook); if (document.getElementById(noSpaceName) === null) { storeNew.render(); } else { var updateStore = new Store(nameStore, miniC, maxiC, avgCook); update(updateStore); } });
11fe8a8c795392f0dd13fb1626112d169e9e5fc2
[ "Markdown", "JavaScript" ]
2
Markdown
geoffreycc/cookie_stand
d6e66e74a0e78db018d3764f7d68de44e33d52b9
a31b1eddb2dc6646f23231fdf15fe8113c24f6bd
refs/heads/master
<file_sep>const express = require("express"); const { getIdeas, getIdea, addIdea, updateIdea, deleteIdea } = require("../controllers/ideas"); const Idea = require("../models/Idea"); const router = express.Router({ mergeParams: true }); //Bring the protect Middleware const advancedResults = require("../middleware/advancedResults"); const { protect, authorize } = require("../middleware/auth"); router .route("/") .get( advancedResults(Idea, { path: "project", select: "name description" }), getIdeas ) .post(protect, authorize("publisher", "admin"), addIdea); router .route("/:id") .get(getIdea) .put(protect, authorize("publisher", "admin"), updateIdea) .delete(protect, authorize("publisher", "admin"), deleteIdea); module.exports = router; <file_sep>const path = require("path"); const ErrorResponse = require("../utils/ErrorResponse"); const geocoder = require("../utils/geocoder"); const Project = require("../models/Project"); const asyncHandler = require("../middleware/asyncHandler"); // desc Get all projects // @router GET /api/v1/projects // @access Public exports.getProjects = asyncHandler(async (req, res, next) => { //Send Responses res.status(200).json(res.advancedResults); }); // @desc GEt single Project // @router GET /api/v1/projects/:id // @access Public exports.getProject = asyncHandler(async (req, res, next) => { const project = await Project.findById(req.params.id).populate("ideas"); if (!project) { // return to avoid "header already set" Error // formatted objectId but not found in db return next( new ErrorResponse(`Project not found with id of ${req.params.id}`, 404) ); } res.status(200).json({ success: true, data: project }); }); // @desc Create new Project // @router POST /api/v1/projects // @access Private exports.createProject = asyncHandler(async (req, res, next) => { // Add user to req.body req.body.user = req.user.id; //Check for published project const publishedProject = await Project.findOne({ user: req.user.id }); // If the user is not an Admin, they can only add only one project if (publishedProject && req.user.role != "admin") { return next( new ErrorResponse( `The user with ID ${req.user.id} has already submitted a project`, 400 ) ); } const project = await Project.create(req.body); res.status(201).json({ success: true, data: project }); }); // @desc Update single Project // @router PUT /api/v1/projects/:id // @access Private exports.updateProject = asyncHandler(async (req, res, next) => { let project = await Project.findById(req.params.id, req.body); if (!project) { return next( new ErrorResponse(`Project not found with id of ${req.params.id}`, 404) ); } // Make sure user is project owner if (project.user.toString() !== req.user.id && req.user.role !== "admin") { return next( new ErrorResponse( `User ${req.params.id} is not authorized to update this Project`, 401 ) ); } // then update project = await Project.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }); res.status(200).json({ success: true, data: project }); }); // @desc Delete single Project // @router DELETE /api/v1/projects/:id // @access Private exports.deleteProject = asyncHandler(async (req, res, next) => { const project = await Project.findById(req.params.id); if (!project) { return next( new ErrorResponse(`Project not found with id of ${req.params.id}`, 404) ); } //Make sure the user is the owner of a project or an Admin if (project.user.toString() !== req.user.id && req.user.role !== "admin") { return next( new ErrorResponse( `User with ID ${req.params.id} is not authorized to delete this Project`, 401 ) ); } //then delete the project project.remove(); res.status(200).json({ success: true, msg: "Document Deleted" }); }); // @desc Get projects within a radius // @router DELETE /api/v1/projects/radius/:zipcode/:distance // @access Private exports.getProjectsInRadius = asyncHandler(async (req, res, next) => { const { zipcode, distance } = req.params; //Get lat/lang from geocoder const loc = await geocoder.geocode(zipcode); const lat = loc[0].latitude; const lng = loc[0].longitude; //Calc radius using radius //Divide distance by radius of earth //Earth Radius = 3,963 mi /6,378 km const radius = distance / 6378; const projects = await Project.find({ location: { $geoWithin: { $centerSphere: [[lng, lat], radius] } } }); res.status(200).json({ success: true, count: projects.length, data: projects }); }); // @desc Upload Photo for a Project // @router DELETE /api/v1/projects/:id/photo // @access Private exports.projectPhotoUpload = asyncHandler(async (req, res, next) => { const project = await Project.findById(req.params.id); // Make sure user is project exist if (!project) { return next( new ErrorResponse(`Project not found with id of ${req.params.id}`, 404) ); } // Make sure user is project owner if (project.user.toString() !== req.user.id && req.user.role !== "admin") { return next( new ErrorResponse( `User ${req.params.id} is not authorized to update this Project`, 401 ) ); } if (!req.files) { return next(new ErrorResponse(`Please Upload a file`, 400)); } console.log(req.files); const file = req.files.file; //make sure image is a photo if (!file.mimetype.startsWith("image")) { return next(new ErrorResponse(`Please Upload an image file`, 400)); } // check file size if (file.size > process.env.MAX_FILE_UPLOAD_SIZE) { return next( new ErrorResponse( `Please Upload an image less than ${process.env.MAX_FILE_UPLOAD_SIZE / 1000000}MB`, 400 ) ); } //Custom file name file.name = `photo_${project._id}${Math.random()}_${Date.now()}${ path.parse(file.name).ext }`; file.mv(`${process.env.FILE_UPLOAD_PATH}/${file.name}`, async err => { if (err) { console.log(err); return next(new ErrorResponse(`Problem with the file upload`, 500)); } // Insert filename into the db await Project.findByIdAndUpdate(req.params.id, { photo: file.name }); res.status(200).json({ success: true, data: file.name }); }); }); <file_sep>const ErrorResponse = require("../utils/ErrorResponse"); const asyncHandler = require("../middleware/asyncHandler"); const User = require("../models/User"); /** * @desc Get all Users * @route GET /api/v1/auth/users * @access private/admin */ exports.getUsers = asyncHandler(async (req, res, next) => { res.status(200).json(res.advancedResults); }); /** * @desc Get Single User * @route GET /api/v1/auth/users/id * @access private/admin */ exports.getUser = asyncHandler(async (req, res, next) => { const user = await User.findById(req.params.id); res.status(200).json({ success: true, data: user }); }); /** * @desc Create a User * @route POST /api/v1/auth/users * @access private/admin */ exports.createUser = asyncHandler(async (req, res, next) => { const user = await User.create(req.body); res.status(201).json({ success: true, data: user }); }); /** * @desc Update a User * @route PUT /api/v1/auth/users/:id * @access private/admin */ exports.updateUser = asyncHandler(async (req, res, next) => { const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }); res.status(200).json({ success: true, data: user }); }); /** * @desc Delete a User * @route DELETE /api/v1/auth/users/:id * @access private/admin */ exports.deleteUser = asyncHandler(async (req, res, next) => { User.findByIdAndDelete(req.params.id); res.status(200).json({ success: true, data: "User deleted" }); }); <file_sep>const express = require("express"); const { getProjects, getProject, createProject, updateProject, deleteProject, getProjectsInRadius, projectPhotoUpload } = require("../controllers/projects"); const Project = require("../models/Project"); /** * Using Resources * Include other Resources Routers */ const ideaRouter = require("./ideas"); const reviewRouter = require("./reviews"); const router = express.Router(); //Bring the protect Middleware const advancedResults = require("../middleware/advancedResults"); const { protect, authorize } = require("../middleware/auth"); /** * Re-route into other resource routers * {{url}}/api/v1/projects/:projectID/-other-router */ router.use("/:projectId/ideas", ideaRouter); router.use("/:projectId/reviews", reviewRouter); // Routes router.route("/radius/:zipcode/:distance").get(getProjectsInRadius); router .route("/:id/photo") .put(protect, authorize("publisher", "admin"), projectPhotoUpload); router .route("/") .get(advancedResults(Project, "ideas"), getProjects) // using advancedResults middleware .post(protect, authorize("publisher", "admin"), createProject); router .route("/:id") .get(getProject) .put(protect, authorize("publisher", "admin"), updateProject) .delete(protect, authorize("publisher", "admin"), deleteProject); module.exports = router;
d349bd504e7fd04f07fa186dbb3c7182bbe6c2a0
[ "JavaScript" ]
4
JavaScript
reanzi/node-api
824cd2e88f100095017a21ebd03f8f65adbb0a3f
d74c32dd2693f87e3192c52ac5df956c958c2468
refs/heads/master
<file_sep>package com.prashant.strategy; import java.beans.PropertyDescriptor; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeoutException; import org.apache.log4j.Logger; import org.json.JSONException; import com.prashant.ordermgmt.InformationThroughKiteConnect; import com.prashant.ordermgmt.KiteConnectManager; import com.prashant.ordermgmt.OrderThroughKiteConnect; import com.prashant.rabbitmq.BroadCastTick; import com.prashant.util.TickerUtils; import com.prashant.util.Utils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.DeliverCallback; import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; import com.zerodhatech.kiteconnect.utils.Constants; import com.zerodhatech.models.Order; import com.zerodhatech.models.OrderParams; import com.zerodhatech.models.Position; public abstract class AbstractStrategy implements Runnable { final static Logger logger = Logger.getLogger(OrderThroughKiteConnect.class); private static final String EXCHANGE_NAME = "topic_logs"; protected StrategyData strategyData; protected List<Order> strategyOrders = new LinkedList<Order>(); public StrategyData getStrategyData() { return strategyData; } public void setStrategyData(StrategyData strategyData) { this.strategyData = strategyData; } public int getState() { return state; } public void setState(int state) { this.state = state; } public int strategyID; private int state; private long waitTimeForCreatePosition = 2000; private int currentQuantity = 0; public AbstractStrategy () { init(); } public void init () { } public void initMessageTicks () throws IOException, TimeoutException, KiteException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); channel.queueDeclare("Ticks", false, false, false, null); String queueName = "Ticks"; String tradingSymbol = strategyData.getOrderParamList().get(0).tradingsymbol; String bindingKey = "" + TickerUtils.getInstrumentTokenForTradingSymbol(tradingSymbol); channel.queueBind(queueName, EXCHANGE_NAME, bindingKey); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); updateTick(8.0,9.0); System.out.println(" [x] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { }); } public void updateTick(double price, double volume) { } public List<OrderParams> geOrderParamsfromProperties() { return null; } public double getCurrentPnL() { double pnl = InformationThroughKiteConnect.getPnL(); logger.debug("Current pnl is : " + pnl); return pnl; } /** * Creates Position and places SL orders if mentioned. * * @param orderParams * @return TODO */ public void createPosition() { List<OrderParams> orderParams = strategyData.getOrderParamList(); List<Order> orders = new LinkedList<Order>(); int incrementOrderSize = 40; if (orderParams.get(0).tradingsymbol.startsWith("N")) { incrementOrderSize = 150; } int totalQuantity = orderParams.get(0).quantity; int iterRequired = totalQuantity / incrementOrderSize; logger.debug("Total quantiity and iteration required are : " + totalQuantity + " , " + iterRequired); for (int i = 0; i < iterRequired; i++) { for (OrderParams orderParam : orderParams) { logger.debug("Iteration number : " + i + " for : " + orderParam.tradingsymbol); orderParam.quantity = incrementOrderSize; orderParam.orderType = Constants.ORDER_TYPE_LIMIT; orderParam.price = getLtp(orderParam); Order order = placeOrder(orderParam); strategyOrders.add(order); } try { Thread.sleep(waitTimeForCreatePosition); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Convert limit orders to marketS */ try { Thread.sleep(2*waitTimeForCreatePosition); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } convertLimitToMarket(orderParams); /** * Restore the oderParam quantity to original */ for (OrderParams orderParam : orderParams) { orderParam.quantity = totalQuantity; } } public void partialBook(List<OrderParams> orderParams, int factor, int mode) { int incrementOrderSize = 20; if (orderParams.get(0).tradingsymbol.startsWith("N")) { incrementOrderSize = 150; } int totalQuantity = orderParams.get(0).quantity / factor; int iterRequired = totalQuantity / incrementOrderSize; /** * mode = 0 implies order to be executed immediately */ if (mode == 0) { totalQuantity = orderParams.get(0).quantity; iterRequired = 1; } logger.debug("Partial quantiity and iteration required are : " + totalQuantity + " , " + iterRequired); for (OrderParams orderParam : orderParams) { Utils.printOrderparams(orderParam); if(mode!=0) { orderParam.quantity = incrementOrderSize; } if (orderParam.transactionType == "BUY") { orderParam.transactionType = "SELL"; } else { orderParam.transactionType = "BUY"; } } for (int i = 0; i < iterRequired; i++) { for (OrderParams orderParam : orderParams) { logger.debug("Iteration number : " + i + " for : " + orderParam.tradingsymbol); orderParam.orderType = Constants.ORDER_TYPE_MARKET; if (mode != 0) { orderParam.orderType = Constants.ORDER_TYPE_LIMIT; orderParam.price = 190.0; orderParam.price = getLtp(orderParam); } Utils.printOrderparams(orderParam); Order order = placeOrder(orderParam); strategyOrders.add(order); } try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Convert limit orders to marketS */ convertLimitToMarket(orderParams); for (OrderParams orderParam : orderParams) { Utils.printOrderparams(orderParam); if (orderParam.transactionType == "BUY") { orderParam.transactionType = "SELL"; } else { orderParam.transactionType = "BUY"; } } /** * Restore the oderParam quantity to original */ for (OrderParams orderParam : orderParams) { orderParam.quantity = totalQuantity * factor; } } public Order placeOrder(OrderParams orderParams) { return OrderThroughKiteConnect.placeOrder(orderParams); } public Order placeBracketOrder(OrderParams orderParams) { return OrderThroughKiteConnect.placeBracketOrder(orderParams); } public double getLtp(OrderParams orderParams) { logger.debug("Getting ltp for"+ orderParams.exchange + ":" +orderParams.tradingsymbol); // double ltp = InformationThroughKiteConnect.getLTP(orderParams.exchange + ":" +orderParams.tradingsymbol); double ltp = InformationThroughKiteConnect.getLTP(orderParams.tradingsymbol); logger.debug("LTP for " + orderParams.tradingsymbol + " : " + ltp); return ltp; } private void convertLimitToMarket(List<OrderParams> orderParamList) { OrderThroughKiteConnect.convertLimitToMarket(orderParamList); } public void monitorForLossProfit() { while (currentQuantity > 0) { if (getPnlForPositions() < -5000) { closePositions(); } if (getPnlForPositions() > 5000) { // move SL and trail } } try { Thread.sleep(waitTimeForCreatePosition); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private List<Position> getPositionsCreated() { /* * get Positions created for Strategy */ return null; } public long getPnlForPositions() { return 0; } public void monitor(List<OrderParams> orderParams) { int profitBookFactor = 4; double bookLossAt = -8000; while (true) { double pnl = getCurrentPnL(); // if (pnl > 15000 && profitBookFactor>3) { // partialBook(orderParams, 4, 1); // profitBookFactor--; // bookLossAt = 4000; // } // if (pnl > 19000 && profitBookFactor>2) { // partialBook(orderParams, 2, 1); // profitBookFactor--; // bookLossAt = 9000; // } // if (pnl < bookLossAt) { // partialBook(orderParams, 1, 1); // break; // } if (pnl > 8000 ) { partialBook(orderParams, 2, 1); profitBookFactor--; bookLossAt = 1000; break; } if (pnl < bookLossAt) { partialBook(orderParams, 1, 1); break; } try { Thread.sleep(60000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // if(pnl<strategyData.getInitialStopLoss()) { // System.out.println("BNWStrangleStrategy.monitor()"); // } // // Thread.sleep(strategyData.getWaitTimeForCreatePosition()); } } public void closePositions() { List<OrderParams> orderParamList = strategyData.getOrderParamList(); for (OrderParams orderParams : orderParamList) { if (orderParams.orderType.equals("SL")) { int totalquant = orderParams.quantity; } } } /** * Cancel SL orders Initiate Close Orders. */ protected void cancelOpenOrdedsForStrategy (List<Order> orders) throws JSONException, IOException, KiteException { for ( Order order : orders) { logger.debug("Cancelling order :" + order.orderId); OrderThroughKiteConnect.cancelOrder(order); } } } <file_sep>package com.prashant.feedHandlers; import com.neovisionaries.ws.client.WebSocketException; import com.prashant.database.DBUtil; import com.prashant.ordermgmt.KiteConnectManager; import com.prashant.ordermgmt.OrderThroughKiteConnect; import com.prashant.rabbitmq.BroadCastTick; import com.prashant.util.TickerUtils; import com.zerodhatech.kiteconnect.KiteConnect; import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; import com.zerodhatech.models.*; import com.zerodhatech.ticker.*; import org.apache.log4j.Logger; import org.json.JSONObject; import java.io.IOException; import java.time.LocalTime; import java.util.*; /** * Created by PD on 15/10/16. */ public class TickerHandler { public String TABLENAME = "tickdataoct"; private static KiteTicker tickerProvider ; private BroadCastTick broadCastTick ; final static Logger logger = Logger.getLogger(TickerHandler.class); private static KiteConnect kiteConnect = KiteConnectManager.getKiteConnect(); int skipCount = 0; int downSampleValue = 5; public TickerHandler () throws Exception { broadCastTick= new BroadCastTick(); } public static void subscribe(ArrayList<Long> tokens) { logger.info("Subscribing tokens"); tickerProvider.subscribe(tokens); } /** Logout user. */ public void logout(KiteConnect kiteConnect) throws KiteException, IOException { /** Logout user and kill session. */ JSONObject jsonObject10 = kiteConnect.logout(); System.out.println(jsonObject10); } /** * Demonstrates com.zerodhatech.ticker connection, subcribing for instruments, * unsubscribing for instruments, set mode of tick data, com.zerodhatech.ticker * disconnection */ public void tickerUsage(ArrayList<Long> tokens) throws IOException, WebSocketException, KiteException { /** * To get live price use websocket connection. It is recommended to use only one * websocket connection at any point of time and make sure you stop connection, * once user goes out of app. custom url points to new endpoint which can be * used till complete Kite Connect 3 migration is done. */ tickerProvider = new KiteTicker(kiteConnect.getAccessToken(), kiteConnect.getApiKey()); DBUtil dbUtil = new DBUtil(); dbUtil.initializeJDBCConn(); dbUtil.createDaysStreamingTickTable(TABLENAME); tickerProvider.setOnConnectedListener(new OnConnect() { @Override public void onConnected() { /** * Subscribe ticks for token. By default, all tokens are subscribed for * modeQuote. */ tickerProvider.subscribe(tokens); logger.info("subscribing to tokens: " + tokens.size()); tickerProvider.setMode(tokens, KiteTicker.modeFull); // tickerProvider.setMode(tokens, KiteTicker.modeLTP); } }); tickerProvider.setOnDisconnectedListener(new OnDisconnect() { @Override public void onDisconnected() { logger.info("On Disconnect"); // your code goes here } }); /** Set listener to get order updates. */ tickerProvider.setOnOrderUpdateListener(new OnOrderUpdate() { @Override public void onOrderUpdate(Order order) { logger.info("order update " + order.orderId); } }); /** Set error listener to listen to errors. */ tickerProvider.setOnErrorListener(new OnError() { @Override public void onError(Exception exception) { // handle here. } @Override public void onError(KiteException kiteException) { // handle here. } }); tickerProvider.setOnTickerArrivalListener(new OnTicks() { @Override public void onTicks(ArrayList<Tick> ticks) { //skipCount++; logger.debug("ticks size " + ticks.size()); int local= 0; if (ticks.size() > 0 && local==0) { dbUtil.storeTickData(ticks); // try { // broadCastTick.publishTicks(ticks); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } //skipCount = 0; } } }); // Make sure this is called before calling connect. tickerProvider.setTryReconnection(true); // maximum retries and should be greater than 0 tickerProvider.setMaximumRetries(10); // set maximum retry interval in seconds tickerProvider.setMaximumRetryInterval(30); /** * connects to com.zerodhatech.com.zerodhatech.ticker server for getting live * quotes */ tickerProvider.connect(); /** * You can check, if websocket connection is open or not using the following * method. */ boolean isConnected = tickerProvider.isConnectionOpen(); logger.info(isConnected); /** * set mode is used to set mode in which you need tick for list of tokens. * Ticker allows three modes, modeFull, modeQuote, modeLTP. For getting only * last traded price, use modeLTP For getting last traded price, last traded * quantity, average price, volume traded today, total sell quantity and total * buy quantity, open, high, low, close, change, use modeQuote For getting all * data with depth, use modeFull */ tickerProvider.setMode(tokens, KiteTicker.modeLTP); try { Thread.sleep(30000000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Unsubscribe for a token. tickerProvider.unsubscribe(tokens); dbUtil.closeJDBCConn(); // After using com.zerodhatech.com.zerodhatech.ticker, close websocket // connection. tickerProvider.disconnect(); } public void callTickerHandler(String tickerToRun) throws IOException, WebSocketException, KiteException { logger.info("Running ticker"); ArrayList<Long> tokens = TickerUtils.getInstrumentTokens(0); // tokens.addAll(TickerUtils.getInstrumentTokens(1)); this.tickerUsage( tokens); } } <file_sep>package com.prashant.util; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Properties; import com.prashant.ordermgmt.OrderThroughKiteConnect; import com.zerodhatech.kiteconnect.utils.Constants; import com.zerodhatech.models.OrderParams; public class Utils { public static Properties readProperties (String propertyFileName) throws IOException { FileReader reader; reader = new FileReader(".\\src\\main\\resources\\" + propertyFileName); Properties properties=new Properties(); properties.load(reader); return properties; } public static void writeProperties (Properties properties, String propertyFileName) throws IOException { properties.store(new FileWriter(".\\src\\main\\resources\\" + propertyFileName),""); } private static String formatTimeStampForHistoricalDate (String histTimestamp) { //histTimestamp = "2019-08-16T12:59:00+0530"; String formatted = histTimestamp.substring(0,10) + " " + histTimestamp.substring(11, 19); System.out.println("HistoricalDataHandler.formatTimeStampFOrHistoricalDate()" + formatted); return formatted; } public static Date simpleDateFormatForHistoricalData (String timeStamp) { timeStamp = formatTimeStampForHistoricalDate(timeStamp); Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { date = formatter.parse(timeStamp); }catch (ParseException e) { e.printStackTrace(); } return date; } public static void printOrderparams(OrderParams orderparams) { OrderThroughKiteConnect.logger.debug("printOrderparams()" + " exc " + orderparams.exchange +" type "+ orderparams.orderType + " price " + orderparams.price + " \ntradingsymbol " + orderparams.tradingsymbol + " transactiontype " + orderparams.transactionType + "\n validity " + orderparams.validity + " quantity " + orderparams.quantity + " stoplloss " + orderparams.stoploss); } public static List<OrderParams> getOrderParamsList () { OrderParams orderParams = new OrderParams(); orderParams.quantity = 300; orderParams.orderType = Constants.ORDER_TYPE_LIMIT; orderParams.tradingsymbol = "BANKNIFTY19O2430000CE"; //orderParams.tradingsymbol = "NIFTY19OCT11800CE"; orderParams.product = Constants.PRODUCT_NRML ; orderParams.exchange = Constants.EXCHANGE_NFO; orderParams.transactionType = Constants.TRANSACTION_TYPE_SELL; orderParams.validity = Constants.VALIDITY_DAY; orderParams.price = 100.0; orderParams.triggerPrice = 0.0; //orderParams.tag = "myTag"; OrderParams orderParams2 = new OrderParams(); orderParams2.quantity = 300; orderParams2.orderType = Constants.ORDER_TYPE_LIMIT; orderParams2.tradingsymbol = "BANKNIFTY19O2428200PE"; //orderParams.tradingsymbol = "NIFTY19OCT11500PE"; orderParams2.product = Constants.PRODUCT_NRML; orderParams2.exchange = Constants.EXCHANGE_NFO; orderParams2.transactionType = Constants.TRANSACTION_TYPE_SELL; orderParams2.validity = Constants.VALIDITY_DAY; orderParams2.price = 100.00; orderParams2.triggerPrice = 0.0; //orderParams2.tag = "myTag"; // OrderParams orderParams3 = new OrderParams(); // orderParams.quantity = 480; // orderParams.orderType = Constants.ORDER_TYPE_LIMIT; // orderParams.tradingsymbol = "BANKNIFTY19OCT28500CE";; // orderParams.product = Constants.PRODUCT_MIS; // orderParams.exchange = Constants.EXCHANGE_NFO; // orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; // orderParams.validity = Constants.VALIDITY_DAY; // orderParams.price = 400.0; // orderParams.triggerPrice = 0.0; // //orderParams.tag = "myTag"; // // OrderParams orderParams4 = new OrderParams(); // orderParams2.quantity = 480; // orderParams2.orderType = Constants.ORDER_TYPE_LIMIT; // orderParams2.tradingsymbol = "BANKNIFTY19OCT27500PE"; // orderParams2.product = Constants.PRODUCT_MIS; // orderParams2.exchange = Constants.EXCHANGE_NFO; // orderParams2.transactionType = Constants.TRANSACTION_TYPE_BUY; // orderParams2.validity = Constants.VALIDITY_DAY; // orderParams2.price = 400.00; // orderParams2.triggerPrice = 0.0; //orderParams2.tag = "myTag"; List<OrderParams> orderParamsList = new LinkedList<OrderParams>(); orderParamsList.add(orderParams); orderParamsList.add(orderParams2); // orderParamsList.add(orderParams3); // orderParamsList.add(orderParams4); return orderParamsList; } } <file_sep> import com.prashant.control.DaemonProcess; import com.prashant.ordermgmt.KiteConnectManager; import com.prashant.util.Utils; import com.zerodhatech.kiteconnect.KiteConnect; import com.zerodhatech.kiteconnect.kitehttp.SessionExpiryHook; import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; import com.zerodhatech.models.User; import org.json.JSONException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Properties; /** * Created by sujith on 7/10/16. This class has example of how to initialize * kiteSdk and make rest api calls to place order, get orders, modify order, * cancel order, get positions, get holdings, convert positions, get * instruments, logout user, get historical data dump, get trades */ public class Test { public static void main(String[] args) throws InterruptedException { try { // First you should get request_token, public_token using kitconnect login and // then use request_token, public_token, api_secret to make any kiteConnect api // call. // Initialize KiteSdk with your apiKey. KiteConnect kiteConnect = new KiteConnect("d5wt29ulgmpkgo8r"); // Set userId kiteConnect.setUserId("DP2095"); // Enable logs for debugging purpose. This will log request and response. kiteConnect.setEnableLogging(false); // Get login url String url = kiteConnect.getLoginURL(); // Set session expiry callback. kiteConnect.setSessionExpiryHook(new SessionExpiryHook() { @Override public void sessionExpired() { System.out.println("session expired .?"); } }); /* * The request token can to be obtained after completion of login process. Check * out https://kite.trade/docs/connect/v1/#login-flow for more information. A * request token is valid for only a couple of minutes and can be used only * once. An access token is valid for one whole day. Don't call this method for * every app run. Once an access token is received it should be stored in * preferences or database for further usage. */ User user = kiteConnect.generateSession("w0c6vFicbO8ImIvJNQoclmXOYldZMkKQ", "t79vantgxj5f303982bchikmnwlehan1"); System.out.println("Test.main()" + user.accessToken + " " + user.publicToken); kiteConnect.setAccessToken(user.accessToken); kiteConnect.setPublicToken(user.publicToken); writeTokensToPropertyFile(user.accessToken, user.publicToken); DaemonProcess.execute(null); } catch (KiteException e) { System.out.println(e.message + " " + e.code + " " + e.getClass().getName()); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); // } catch (WebSocketException e) { // e.printStackTrace(); } } public static void writeTokensToPropertyFile(String accessToken, String publicToken) throws IOException { Properties prop = new Properties(); // set the properties value prop.setProperty("Accesstoken", accessToken); prop.setProperty("Publictoken", publicToken); Utils.writeProperties(prop, KiteConnectManager.kitePropertyFileName); } } <file_sep>package com.prashant.strategy; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import com.prashant.ordermgmt.InformationThroughKiteConnect; import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; import com.zerodhatech.kiteconnect.utils.Constants; import com.zerodhatech.models.Order; import com.zerodhatech.models.OrderParams; import com.zerodhatech.models.Quote; public class FutureEntryAtPrice extends AbstractStrategy { final static Logger logger = Logger.getLogger(FutureEntryAtPrice.class); public static void main(String[] args) throws Exception, KiteException { FutureEntryAtPrice futureEntryAtPrice = new FutureEntryAtPrice(); futureEntryAtPrice.createPosition(); } public void createPosition() { waitForEntryPrice(strategyData.orderParamList.get(0)); createOrdersAfterEntryCondition(); } public FutureEntryAtPrice() { // TODO Auto-generated constructor stub init(); } public void init() { strategyData = new StrategyData(); strategyData.setOrderParamList(getOrderParamsList()); } @Override public void run() { // TODO Auto-generated method stub } public List<OrderParams> getOrderParamsList() { OrderParams orderParams = new OrderParams(); orderParams.quantity = 40; orderParams.orderType = Constants.ORDER_TYPE_LIMIT; orderParams.tradingsymbol = "BANKNIFTY19NOVFUT"; orderParams.product = Constants.PRODUCT_MIS; orderParams.exchange = Constants.EXCHANGE_NFO; orderParams.transactionType = Constants.TRANSACTION_TYPE_SELL; orderParams.validity = Constants.VALIDITY_DAY; orderParams.price = 31000.0; orderParams.triggerPrice = 0.0; List<OrderParams> orderParamsList = new LinkedList<OrderParams>(); orderParamsList.add(orderParams); return orderParamsList; } public boolean waitForEntryPrice(OrderParams orderParams) { double ltp = 0.0; while (true) { try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } ltp = InformationThroughKiteConnect.getLTP(orderParams.tradingsymbol); if (orderParams.transactionType.equals(Constants.TRANSACTION_TYPE_BUY)) { if (ltp <= orderParams.price) { logger.info("ltp is below entryprice. ltp is : " + ltp); break; } } if (orderParams.transactionType.equals(Constants.TRANSACTION_TYPE_SELL)) { if (ltp >= orderParams.price) { logger.info("ltp is above entryprice. ltp is : " + ltp); break; } } } return true; } public void createOrdersAfterEntryCondition() { OrderParams orderParams = strategyData.getOrderParamList().get(0); orderParams.trailingStoploss = 50.0; orderParams.stoploss = 50.0; orderParams.squareoff = 50.0; Order bracketOrder = placeBracketOrder(orderParams); strategyOrders.add(bracketOrder); } /* * TODO */ public void trailPosition() { } } <file_sep>package com.prashant.control; import java.io.IOException; import java.util.List; import org.apache.log4j.Logger; import org.json.JSONException; import com.prashant.database.DBUtil; import com.prashant.ordermgmt.InformationThroughKiteConnect; import com.prashant.ordermgmt.OrderThroughKiteConnect; import com.prashant.util.Utils; import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; import com.zerodhatech.kiteconnect.utils.Constants; import com.zerodhatech.models.OrderParams; import com.zerodhatech.models.Position; public class DaemonProcess { public static double MAXLOSS = -30000.0; public static void main(String args[]) throws InterruptedException, JSONException, IOException, KiteException { execute(args); } public static void execute (String args []) throws InterruptedException, JSONException, IOException, KiteException { while(true) { checkDailyLossLimit(); Thread.sleep(60000); } } private final static Logger logger = Logger.getLogger(DaemonProcess.class); public DaemonProcess() { // TODO Auto-generated constructor stub } public static void checkDailyLossLimit() throws JSONException, IOException, KiteException { double pnl = InformationThroughKiteConnect.getPnL(); if (pnl < MAXLOSS) { // 1. Cancel all open orders OrderThroughKiteConnect.cancelAllOrders(); // 2. Close all open positions List<Position> positions = InformationThroughKiteConnect.getPositions(); if(positions.size() ==0) { logger.warn("no positions"); } for (Position position : positions) { OrderParams orderParams = new OrderParams(); orderParams.exchange = position.exchange; orderParams.tradingsymbol = position.tradingSymbol; orderParams.product = position.product; orderParams.orderType = Constants.ORDER_TYPE_LIMIT; orderParams.price = position.lastPrice; if (position.tradingSymbol.contains("NIFTY")) { orderParams.orderType = Constants.ORDER_TYPE_MARKET; } if (position.netQuantity > 0) { orderParams.transactionType = Constants.TRANSACTION_TYPE_SELL; orderParams.quantity = position.netQuantity; } else { orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; orderParams.quantity = -1 * position.netQuantity; } orderParams.validity = Constants.VALIDITY_DAY; Utils.printOrderparams(orderParams); OrderThroughKiteConnect.placeOrder(orderParams); } } } } <file_sep>package com.prashant.strategy; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import com.prashant.ordermgmt.InformationThroughKiteConnect; import com.prashant.util.Utils; import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; import com.zerodhatech.kiteconnect.utils.Constants; import com.zerodhatech.models.Order; import com.zerodhatech.models.OrderParams; import com.zerodhatech.models.Quote; public class OptionEntryAtFuturePrice extends FutureEntryAtPrice { final static Logger logger = Logger.getLogger(OptionEntryAtFuturePrice.class); public static void main(String[] args) throws Exception, KiteException { OptionEntryAtFuturePrice OptionEntryAtFuturePrice = new OptionEntryAtFuturePrice(); OptionEntryAtFuturePrice.createPosition(); } @Override public void run() { // TODO Auto-generated method stub } public List<OrderParams> getOrderParamsList() { OrderParams orderParams = new OrderParams(); orderParams.quantity = 100; orderParams.orderType = Constants.ORDER_TYPE_LIMIT; orderParams.tradingsymbol = "BANKNIFTY19NOVFUT"; orderParams.product = Constants.PRODUCT_MIS; orderParams.exchange = Constants.EXCHANGE_NFO; orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; orderParams.validity = Constants.VALIDITY_DAY; orderParams.price = 30718.0; // orderParams.triggerPrice = 0.0; // orderParams.tag = "myTag"; OrderParams orderParams2 = new OrderParams(); orderParams2.quantity = orderParams.quantity ; orderParams2.orderType = Constants.ORDER_TYPE_LIMIT; orderParams2.tradingsymbol = "BANKNIFTY19N1430500PE"; orderParams2.product = orderParams.product; orderParams2.exchange = orderParams.exchange; orderParams2.transactionType = Constants.TRANSACTION_TYPE_SELL; orderParams2.validity = orderParams.validity; orderParams2.price = 100.0; orderParams2.triggerPrice = 0.0; OrderParams orderParams3 = new OrderParams(); orderParams3.quantity = orderParams.quantity ; orderParams3.orderType = Constants.ORDER_TYPE_SLM; orderParams3.tradingsymbol = "BANKNIFTY19OCTFUT"; orderParams3.product = orderParams.product; orderParams3.exchange = orderParams.exchange; orderParams3.transactionType = Constants.TRANSACTION_TYPE_BUY; orderParams3.validity = orderParams.validity; orderParams3.price = 100.0; orderParams3.triggerPrice = 0.0; List<OrderParams> orderParamsList = new LinkedList<OrderParams>(); orderParamsList.add(orderParams); orderParamsList.add(orderParams2); // orderParamsList.add(orderParams3); // orderParamsList.add(orderParams4); return orderParamsList; } public void createOrdersAfterEntryCondition() { OrderParams orderParams = strategyData.getOrderParamList().get(1); orderParams.trailingStoploss = 20.0; orderParams.stoploss = 20.0; orderParams.squareoff = 20.0; Utils.printOrderparams(orderParams); Order bracketOrder = placeBracketOrder(orderParams); strategyOrders.add(bracketOrder); } /* * TODO */ public void trailPosition() { Order targetOrder = strategyOrders.get(1); Order slOrder = strategyOrders.get(2); while(true) { if(slOrder.status== "done") { targetOrder.status="cancel"; } } } private Quote getQoute(OrderParams orderParams) throws KiteException { return InformationThroughKiteConnect.getQuote(orderParams.tradingsymbol); } } <file_sep>package com.prashant.control; public class StrategyDatabaseHandler { public StrategyDatabaseHandler() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub } public void readOrderParamsFromDB() { } public void upDateOrderStatusinDB() { } public void execute() { while(true) { readOrderParamsFromDB(); if("newOrderRequestFOund" =="true") { //callBrokerHandlerToExecute } } } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>tradeJava</groupId> <artifactId>tradeJava</artifactId> <version>0.0.1-SNAPSHOT</version> <name>tradeJava</name> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>com.prashant.control.KiteMain</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> <scope>compile</scope> </dependency> <dependency> <groupId>net.sf.supercsv</groupId> <artifactId>super-csv</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>com.neovisionaries</groupId> <artifactId>nv-websocket-client</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.2</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20171018</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.9.1</version> </dependency> <dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>1.13.0</version> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>logging-interceptor</artifactId> <version>3.9.1</version> </dependency> <dependency> <groupId>com.zerodhatech.kiteconnect</groupId> <artifactId>kiteconnect</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.9</version> </dependency> <!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client --> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.7.3</version> </dependency> </dependencies> </project><file_sep>package com.prashant.feedHandlers; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalTime; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.prashant.database.DBUtil; import com.prashant.ordermgmt.KiteConnectManager; import com.prashant.ordermgmt.OrderThroughKiteConnect; import com.prashant.util.TickerUtils; import com.zerodhatech.kiteconnect.KiteConnect; import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; import com.zerodhatech.models.HistoricalData; import com.zerodhatech.models.Instrument; import com.zerodhatech.models.Quote; public class HistoricalDataHandler { final static Logger logger = Logger.getLogger(HistoricalDataHandler.class); DBUtil dbUtil = new DBUtil(); private static KiteConnect kiteConnect; public static KiteConnect getKiteConnect() { return kiteConnect; } public static void setKiteConnect() throws Exception { if (kiteConnect == null) HistoricalDataHandler.kiteConnect = KiteConnectManager.getKiteConnect(); } public HistoricalDataHandler() { try { dbUtil.initializeJDBCConn(); setKiteConnect(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated constructor stub } public static void main(String[] args) { // CREATE TABLE Historical (TradingSymbol VARCHAR(40) NOT NULL, Open FLOAT NOT // NULL, High FLOAT NOT NULL,Low FLOAT NOT NULL, Close FLOAT NOT NULL, Volume // BIGINT NOT NULL, Timestamp DATETIME NOT NULL, PRIMARY KEY (TradingSymbol, // Timestamp)) ENGINE=InnoDB DEFAULT CHARSET=utf8; // TODO Auto-generated method stub HistoricalDataHandler historicalDataHandler = new HistoricalDataHandler(); // historicalDataHandler.formatTimeStampFOrHistoricalDate(""); historicalDataHandler.getHistoricalDataForAllInstruments(); } public HistoricalData getHistoricalDataForSingleInstrument(KiteConnect kiteConnect, Date from, Date to, long instrumentToken, String interval) throws KiteException, IOException { /** * Get historical data dump, requires from and to date, intrument token, * interval, continuous (for expired F&O contracts) returns historical data * object which will have list of historical data inside the object. */ HistoricalData historicalData = kiteConnect.getHistoricalData(from, to, "" + instrumentToken, "minute", false); List<HistoricalData> historyList = historicalData.dataArrayList; logger.info("getHistoricalData()" + historyList.size()); dbUtil.storeHistoricalData(TickerUtils.tokenMap.get(instrumentToken).substring(4), historyList); return historicalData; } public void getHistoricalDataForAllInstruments () { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date from = new Date(); Date to = new Date(); try { from = formatter.parse("2019-09-12 15:18:00"); to = formatter.parse("2019-09-12 15:30:00"); }catch (ParseException e) { e.printStackTrace(); } try { ArrayList<Long> instrumentTokens = TickerUtils.getInstrumentTokensForHistoricalData(); for(int i =0; i<instrumentTokens.size(); i ++) { getHistoricalDataForSingleInstrument(kiteConnect, from, to, instrumentTokens.get(i), "minute"); Thread.sleep(401); } } catch (KiteException | IOException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package com.prashant.trade.beans; import java.util.HashMap; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "strategy") @XmlAccessorType(XmlAccessType.FIELD) public class StrategyData { private String id; private String strategyName = "BNWCEPESELL"; private int version = 0; private double stopLoss = 20000.0; private double partialProfit = 6000.0; private double profitTarget = 50000.0; private double availableMargin = 300000.0; private int incrementOrderSize = 40; private long waitTimeForCreatePosition = 10000; private HashMap<String, Condition> conditions; public List<SOrderParams> orderParamList; public String getId() { return id; } public HashMap<String, Condition> getConditions() { return conditions; } public void setConditions(HashMap<String, Condition> conditions) { this.conditions = conditions; } public void setAvailableMargin(double availableMargin) { this.availableMargin = availableMargin; } public void setId(String id) { this.id = id; } public String getStrategyName() { return strategyName; } public void setStrategyName(String strategyName) { this.strategyName = strategyName; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public double setStopLoss() { return stopLoss; } public void setStopLoss(double stopLoss) { this.stopLoss = stopLoss; } public double getPartialProfit() { return partialProfit; } public void setPartialProfit(long partialProfit) { this.partialProfit = partialProfit; } public double getAvailableMargin() { return availableMargin; } public void setAvailableMargin(long availableMargin) { this.availableMargin = availableMargin; } public int getIncrementOrderSize() { return incrementOrderSize; } public void setIncrementOrderSize(int incrementOrderSize) { this.incrementOrderSize = incrementOrderSize; } public long getWaitTimeForCreatePosition() { return waitTimeForCreatePosition; } public void setWaitTimeForCreatePosition(long waitTimeForCreatePosition) { this.waitTimeForCreatePosition = waitTimeForCreatePosition; } public void setOrderParamList(List<SOrderParams> orderParamList) { this.orderParamList = orderParamList; } @Override public String toString() { return "StrategyData [id=" + id + ", strategyName=" + strategyName + ", version=" + version + ", stopLoss=" + stopLoss + ", partialProfit=" + partialProfit + ", profitTarget=" + profitTarget + ", availableMargin=" + availableMargin + ", incrementOrderSize=" + incrementOrderSize + ", waitTimeForCreatePosition=" + waitTimeForCreatePosition + ", orderParamList=" + orderParamList + "]"; } public double getProfitTarget() { return profitTarget; } public void setProfitTarget(double profitTarget) { this.profitTarget = profitTarget; } public double getStopLoss() { return stopLoss; } public void setPartialProfit(double partialProfit) { this.partialProfit = partialProfit; } public List<SOrderParams> getOrderParamList() { return orderParamList; } }
f96d7c164d94c07e3695b736e4ce2d9afed2f0dd
[ "Java", "Maven POM" ]
11
Java
Pdhanke/tradeapp
699b60cfb8a0fa6d8a669685c3423048e8a6b7a5
40884ef54516f0477f819adb92b8ff3226aa37e9
refs/heads/master
<file_sep><?php require "conn.php"; $user_name = $_POST["username"]; $user_pass = $_POST["<PASSWORD>"]; $mysql_qry = "select * from employee_data where username like '$user_name'and password = '$<PASSWORD>' " ; $result = mysqli_query($conn, $mysql_qry); if (mysqli_num_rows($result) > 0) { # code... echo "login successful"; } else{ echo "login not successful"; } ?> <file_sep><?php require "conn.php"; $name = $_POST["name"]; $surname = $_POST["surname"]; $age = $_POST["age"]; $username = $_POST["password"]; $password = $_POST["username"]; $mysql_qry = "insert into employee_data(name, surname, age, username, password) values ('$name', '$surname','$age', '$username','$password')" ; if ($conn -> query($mysql_qry) === TRUE) { # code... echo " Insert successful"; } else{ echo " Error: " .$mysql_qry."<br>". $conn->error; } $conn->close(); ?><file_sep>include ':app' rootProject.name='MySqlDemo'
e80657ba680b57895ccedd5883428f5094feebb0
[ "PHP", "Gradle" ]
3
PHP
Samsonjoe/MySqlDemo
70ba5748128b655384a532b453b81de2b172c793
ed1c53f23816aed4d5f6d774f463e767d9770040
refs/heads/main
<repo_name>pavan-areti/exam-form-next.js<file_sep>/README.md # exam-form-next.js
b1c9e2ae04da254012d19f5f0ee1a5577a06764f
[ "Markdown" ]
1
Markdown
pavan-areti/exam-form-next.js
898aae14a0e70ea09804733e40a8e45a826118bb
1897094052995d234da80dcd8f1edd4f65e9f745
refs/heads/master
<file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0 ) from sklearn.ensemble import RandomForestRegressor regressor = RandomForestRegressor(n_estimators=10, random_state=0) regressor.fit(X_train, y_train) y_pred = regressor.predict(X_test) from sklearn.metrics import r2_score print(r2_score(y_test, y_pred)) #0.9615908334363876<file_sep>#Import statements import numpy as np import pandas as pd import matplotlib.pyplot as plt #Import the data and split into dependent and independent variables dataset = pd.read_csv('Social_Network_Ads.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values #Test and training data split from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state = 0) #Feature scaling : not necessary but if performed helps prediction better from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) #Training the logistic regression model from sklearn.linear_model import LogisticRegression classifier = LogisticRegression(random_state=0) classifier.fit(X_train, y_train) #Predicting the new result print(classifier.predict(sc_X.transform([[30,87000]]))) #Predicting the test set results y_pred = classifier.predict(X_test) np.set_printoptions(precision=2) #print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1)) #Making the confusion matix from sklearn.metrics import confusion_matrix, accuracy_score cm = confusion_matrix(y_test, y_pred) print(cm) print(accuracy_score(y_test, y_pred)) #Visualizing the training set reults from matplotlib.colors import ListedColormap x_set, y_set = sc_X.inverse_transform(X_train), y_train X1, X2 = np.meshgrid( np.arange(start=x_set[:, 0].min()-10, stop=x_set[:, 0].max()+10, step=0.25), np.arange(start=x_set[:, 1].min()-1000, stop=x_set[:, 1].max()+1000, step=0.25) ) plt.contour(X1, X2, classifier.predict(sc_X.transform( np.array([X1.ravel(), X2.ravel()]).T )).reshape(X1.shape), alpha=0.75, cmap=ListedColormap(('red','green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(x_set[y_set == j, 0], x_set[y_set == j, 1], c= ListedColormap(('red','green'))(i), label=j) plt.title('Logistic Regression (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() #Visualize the test set results from matplotlib.colors import ListedColormap X_set, y_set = sc_X.inverse_transform(X_test), y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 10, stop = X_set[:, 0].max() + 10, step = 0.25), np.arange(start = X_set[:, 1].min() - 1000, stop = X_set[:, 1].max() + 1000, step = 0.25)) plt.contourf(X1, X2, classifier.predict(sc_X.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Logistic Regression (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()<file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter='\t', quoting=3) ''' Cleaning the text ''' import re import nltk nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer corpus = [] for i in range(0, 1000): review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i]) review = review.lower() review = review.split() #stemming ps = PorterStemmer() all_stopwords = stopwords.words('english') all_stopwords.remove('not') review = [ps.stem(word) for word in review if not word in set(all_stopwords)] review = ' '.join(review) corpus.append(review) #Create bag of words model from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features=1500) X = cv.fit_transform(corpus).toarray() y = dataset.iloc[:, -1].values from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) #Training the naive bayes model on the training set from sklearn.naive_bayes import GaussianNB classifier = GaussianNB() classifier.fit(X_train, y_train) y_pred = classifier.predict(X_test) print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)))) from sklearn.metrics import confusion_matrix, accuracy_score cm = confusion_matrix(y_test, y_pred) print(cm) acs = accuracy_score(y_test, y_pred) print(acs) #Predicting if a single review #Positive review new_review = 'I love this restaurant so much' new_review = re.sub('[^a-zA-Z]', ' ', new_review) new_review = new_review.lower() new_review = new_review.split() ps = PorterStemmer() all_stopwords = stopwords.words('english') all_stopwords.remove('not') new_review = [ps.stem(word) for word in new_review if not word in set(all_stopwords)] new_review = ' '.join(new_review) new_corpus = [new_review] new_X_test = cv.transform(new_corpus).toarray() new_y_pred = classifier.predict(new_X_test) print(new_y_pred) #### Negative review new_review = 'I hate this restaurant so much' new_review = re.sub('[^a-zA-Z]', ' ', new_review) new_review = new_review.lower() new_review = new_review.split() ps = PorterStemmer() all_stopwords = stopwords.words('english') all_stopwords.remove('not') new_review = [ps.stem(word) for word in new_review if not word in set(all_stopwords)] new_review = ' '.join(new_review) new_corpus = [new_review] new_X_test = cv.transform(new_corpus).toarray() new_y_pred = classifier.predict(new_X_test) print(new_y_pred) <file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) y_pred = regressor.predict(X_test) np.set_printoptions(precision=2) print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1)) from sklearn.metrics import r2_score print(r2_score(y_test, y_pred)) #0.9325315554761303 <file_sep>#Importing the libraries import numpy as np import pandas as pd import tensorflow as tf #print(tf.__version__) #Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:,3:-1].values y = dataset.iloc[:,-1].values #Encoding the categorical data from sklearn.preprocessing import LabelEncoder le = LabelEncoder() X[:,2] = le.fit_transform(X[:,2]) from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder # 1 is the index of the column. ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [1])], remainder='passthrough') X = np.array(ct.fit_transform(X)) #splitting the data into test and training set. from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) #Feature Scaling is mandatory for deep learning. from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) #Building ANN #Initialize ann = tf.keras.models.Sequential() #Adding input layer ann.add(tf.keras.layers.Dense(units=6, activation='relu')) #Adding second hidden layer ann.add(tf.keras.layers.Dense(units=6, activation='relu')) #Adding ouput layer ann.add(tf.keras.layers.Dense(units=1, activation='sigmoid')) #Training the ANN ann.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) ann.fit(X_train, y_train, batch_size=32, epochs=100) #Making the prediction and evaluating the model pred = ann.predict(sc.transform([[1, 0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]])) > 0.5 print(pred) y_pred = ann.predict(X_test) y_pred = (y_pred > 0.5) print(y_pred) #print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1)) from sklearn.metrics import confusion_matrix, accuracy_score cm = confusion_matrix(y_test, y_pred) print(cm) ac = accuracy_score(y_test, y_pred) print(ac) ''' [[1504 91] [ 183 222]] 0.863 '''<file_sep>k-means clustering step 1 : choose the number of K clusters step 2 : select at random K points, the centroids ( not necessarily from your dataset). step 3 : Assign each data point to the closest centroid --> that forms K clusters. step 4 : compute and place the new centroid of each other step 5 : reassign each data point to the new closest centroid. if any reassignment took place then go to step 4 otherwise go to FIN. Random Initialization Trap : the selection of centroid at the beginning of algorithm dictates the output. To correct this we need to use K-Means++ algorithm. There is no need to implement k-means ++ because its taken care of by library. Choosing right number of clusters : WCSS (Within Cluster Sum of Squares) Square of Distance between taken point to centroid. selecting more clusters will result in less value of WCSS. the upper limit to select the number of clusters is number of data points which would lead us to see WCSS as zero. To get optimal number of clusters we need to use Elbow method. its the value change in WCSS while increasing the number of clusters. Hierarchical clustering : two types are Agglomerative and Divisive. below steps are for Agglomerative. step 1 : make each data point a single point cluster that forms N clusters. step 2 : Take two closest data points and make them one cluster, that forms N-1 clusters. step 3 : take two closest clusters and make them one cluster, that forms N-2 clusters. step 4 : repeat step 3 until there is only one cluster. Euclidean distance is used for calculating the distance between data points/clusters. Distance between clusters can be calculated in multiple ways. 1. Closest points 2. Furthest points 3. Average distance 4. distance between centroid. Dendograms : Memory of hierarchical model. The distance between two data point/clusters is proportional to the height of dendograms plot. by setting the height level threshold we can decide how many clusters we need. if the threshold level is disected by two lines then the total number of clusters will be two. Association Rule learning (Apriori): People who bought also bought. Apriori Support : People who watched movie 1 also watched movie 2 Apriori Confidence : percentage of people who watched movie 2 Apriori lift : percentage of possible suggestion of movie 2 to the people who watched movie 1 already. Step 1 : set a minimum support and confidence Step 2 : take all the subsets in transactions having higher support than minimum support. Step 3 : take all the rules of these subsets having higher confidence than minimun confidence. Step 4 : sort the rules by decreasing lift. Association Rule learning (Eclat) : Eclat Support : users watchlist containing M / users watchlist Step 1 : set a minimum support Step 2 : Take all the subsets in transactions having higher support than minimun support. Step 3 : sort these subsets by decreasing support. Reinforcement Learning: Reinforcement Learning is a powerful branch of Machine Learning. It is used to solve interacting problems where the data observed up to time t is considered to decide which action to take at time t + 1. It is also used for Artificial Intelligence when training machines to perform tasks such as walking. Desired outcomes provide the AI with reward, undesired with punishment. Machines learn through trial and error. In this part, you will understand and learn how to implement the following Reinforcement Learning models: 1. Upper Confidence Bound (UCB) Initial round we will start with default confidence level. as the go through more rounds this level is adjusted based on reward. confidence bound is also adjusted based on reward. we start the next round with highest confidence bound. when the bound decrease to a minimum level then we will select that option. 2. Thompson Sampling : probablistic models we are not trying to guess the distributions behind the machines/data set. every round there will be a feedback using which something new learnt. meaning the distribution is adjusted. The Multi-Armed Bandit Problem : used to train robot dogs to walk using reinforcement learning. finding the best outcome out of many options available. 1. We have d arms. for example, arms are ads that we display to users each time they connect to a web page. 2. each time a user connects to this web page, that makes a round. 3. At each round n, we choose one ad to display to the user. 4. At each round n, ad i gives reward. 1 if the user clicks on the ad i, 0 if the user didn't. 5. our goal is to maximize the total reward we get over many rounds. UCB vs Thompson sampling : 1. UCB is deterministic model. but thompson is more of probabilistic. 2. UCB requires update at every round. Thompson can accommodate delayed feedback. 3. Thompson has better empricial evidence. Natural Language Processing Natural Language Processing (or NLP) is applying Machine Learning models to text and language. Teaching machines to understand what is said in spoken and written word is the focus of Natural Language Processing. Whenever you dictate something into your iPhone / Android device that is then converted to text, that’s an NLP algorithm in action.You can also use NLP on a text review to predict if the review is a good one or a bad one. You can use NLP on an article to predict some categories of the articles you are trying to segment. You can use NLP on a book to predict the genre of the book. And it can go further, you can use NLP to build a machine translator or a speech recognition system, and in that last example you use classification algorithms to classify language. Speaking of classification algorithms, most of NLP algorithms are classification models, and they include Logistic Regression, Naive Bayes, CART which is a model based on decision trees, Maximum Entropy again related to Decision Trees, Hidden Markov Models which are models based on Markov processes.A very well-known model in NLP is the Bag of Words model. It is a model used to preprocess the texts to classify before fitting the classification algorithms on the observations containing the texts. Exampels 1. if / else rules for chatbots 2. Audio frequency components and analysis for speech recognition 3. Bag-of-words model (classification) 4. CNN for text recognition (classification) Deep Learning is the most exciting and powerful branch of Machine Learning. Deep Learning models can be used for a variety of complex tasks: Artificial Neural Networks for Regression and Classification Convolutional Neural Networks for Computer Vision Recurrent Neural Networks for Time Series Analysis Self Organizing Maps for Feature Extraction Deep Boltzmann Machines for Recommendation Systems Auto Encoders for Recommendation Systems Training the ANN with stochastic gradient descent: step 1: randomly initialize the weights to small numbersclose to 0 but not 0. step 2: input the first observation of your dataset in the input layer, each feature in one input node. step 3: forward propagation from left to right the neurons are activated in a way that the impact of each neuron's activation is limited by the weights. propagate the activations until getting the predicted result y. step 4 : compare the predicted result to the actual result. Measure the generated error. step 5 : back-propagation from right to left the error is back propagated. update the weights according to how much they are responsible for the error. the learning rate decides by how much we update the weights. step 6 : repeat steps 1 to 5 and update the weights after each observation (Reinforcement learning). or repeat steps 1 to 5 and update the weights only after a batch of observations (Batch learning) step 7 : when the whole training set passed through the ANN, that makes an epoch. Redo more epochs. Convolutional Neural Networks : used in image recognition. Step 1 : Convolution - find feature in image using feature detector and produce feature map. ReLu Layer - apply rectifier function on convolution layer to reduce the linearity of the images. Because images have lot of non linearity data. Step 2 : Max pooling - Spacial invariance. taking the max/sum value after grouping pixels data. this will result in reducing the number of features going into network. This will help in reducing the over fitting. If mean value is considered then its called sub-sampling. Step 3 : Flattening - put data from matrix to one column (long vector) which inturn becomes one feature to feed into ANN. Step 4 : Full Connection - ANN Softmax and cross-entropy : its another way to calculate last function. if there are multiple output neuron then probability adding up to 1 between their output is less. hence we use softmax equation to normalize the probability so that the sum will be 1. if there are two NN and one of them is out performing another at every instance. Comparing these two NN there can be 1. classification error which is either true or false kind of output. These is not a great way to compare the two NN. 2. Mean Squared Error is taking the sum of squared errors and then just take the average across observations. This is more accurate in comparing two NN. 3. Cross-Entropy is a great way to compare beacuse its based on logarithm. Hence the tiny variation will be captured. This is where mean squared error will fail to capture the small adjustments.Mean squared is good for regression, and cross-entropy is good for classification. Dimensionality Reduction : There are two types of Dimensionality Reduction techniques 1. Feature Selection : Feature Selection techniques are Backward Elimination, Forward Selection, Bidirectional Elimination, Score Comparison and more. We covered these techniques in Part 2 - Regression. 2. Feature Extraction : In this part we will cover the following Feature Extraction techniques: 1. Principal Component Analysis (PCA) 2. Linear Discriminant Analysis (LDA) 3. Kernel PCA 4. Quadratic Discriminant Analysis (QDA) Principal component analysis (PCA): unsupervised learning and used in below areas. 1. Noise filtering 2. Visualization 3. Feature Extraction 4. Stock market analysis 5. Gene data analysis Goal of PCA is to identify patterns in data and detect the correlation between variables. Reduce the dimensions of a d-dimensional dataset by projecting it onto a k-dimension subspace where k < d <file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values y = y.reshape(len(y),1) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0 ) from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() sc_y = StandardScaler() X_train = sc_X.fit_transform(X_train) y_train = sc_y.fit_transform(y_train) from sklearn.svm import SVR regressor = SVR(kernel='rbf') regressor.fit(X_train, y_train) y_pred = sc_y.inverse_transform(regressor.predict(sc_X.transform(X_test))) from sklearn.metrics import r2_score print(r2_score(y_test, y_pred)) #0.9458193347147953<file_sep>#importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #importing the dataset dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:,[3,4]].values #Using the Elbow method to find the optimal number of clusters from sklearn.cluster import KMeans wcss = [] for i in range(1,11): kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42) kmeans.fit(X) wcss.append(kmeans.inertia_) ''' plt.plot(range(1,11), wcss) plt.title('The Elbow Method') plt.xlabel('Number of Clusters') plt.ylabel('WCSS') plt.savefig('The Elbow Method.png') ''' #Train the K-Means model kmeans = KMeans(n_clusters = 5, init = 'k-means++', random_state = 42) y_kmeans = kmeans.fit_predict(X) print(y_kmeans) # Visualising the cluster plt.scatter(x = X[y_kmeans == 0, 0], y = X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1') plt.scatter(x = X[y_kmeans == 1, 0], y = X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2') plt.scatter(x = X[y_kmeans == 2, 0], y = X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3') plt.scatter(x = X[y_kmeans == 3, 0], y = X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4') plt.scatter(x = X[y_kmeans == 4, 0], y = X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5') plt.scatter(x = kmeans.cluster_centers_[:,0], y = kmeans.cluster_centers_[:,1], s = 300, c = 'black', label = 'Centroid') plt.title('Clusters of Customers') plt.xlabel('Annual Income') plt.ylabel('Spending Score (1-100)') plt.legend() plt.savefig('K-Means Cluster.png') <file_sep>import tensorflow as tf from keras.preprocessing.image import ImageDataGenerator #mandatory for image processing #Data preprocessing #Change the basic attributes of images by applying transformations and its called image augmentation train_datagen = ImageDataGenerator( rescale=1/.255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) training_set = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) test_datagen = ImageDataGenerator(rescale=1/.255) test_set = test_datagen.flow_from_directory( 'dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) #Building the CNN cnn = tf.keras.models.Sequential() #Convolutional layer cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu',input_shape=[64,64,3])) #Max Pooling cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2)) #second set of layers cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu')) cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2)) #Flattening cnn.add(tf.keras.layers.Flatten()) #Full connection cnn.add(tf.keras.layers.Dense(units=128,activation='relu')) #output layer cnn.add(tf.keras.layers.Dense(units=1,activation='sigmoid')) #Training the CNN cnn.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy']) cnn.fit(x = training_set, validation_data=test_set, epochs=25) import numpy as np from keras.preprocessing import image test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size=(64,64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis=0) result = cnn.predict(test_image) print(training_set.class_indices) if result[0][0] == 1: prediction = 'Dog' else : prediction = 'Cat' print(prediction)<file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0 ) from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression poly_reg = PolynomialFeatures(degree=4) print(X_train) x_poly = poly_reg.fit_transform(X_train) print(x_poly) regressor = LinearRegression() regressor.fit(x_poly, y_train) y_pred = regressor.predict(poly_reg.transform(X_test)) np.set_printoptions(precision=2) #print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1)) from sklearn.metrics import r2_score print(r2_score(y_test, y_pred)) #0.9458193347147953<file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Market_Basket_Optimisation.csv', header=None) transaction = [] for i in range(0,7501): transaction.append([str(dataset.values[i,j]) for j in range(0, 20)]) from apyori import apriori rules = apriori(transactions = transaction,min_support = 0.003, min_confidence = 0.20, min_lift = 3, min_length = 2, max_length = 2) results = list(rules) def inspect(results): lhs = [tuple(result [2][0][0])[0] for result in results] rhs = [tuple(result [2][0][1])[0] for result in results] supports = [result[1] for result in results] confidences = [result[2][0][2] for result in results] lift = [result[2][0][3] for result in results] return list(zip(lhs, rhs, supports, confidences, lift)) resultinDataframe = pd.DataFrame(inspect(results), columns = ['Left Hand side','Right Hand side','Support','Confidence','Lift']) print(resultinDataframe.nlargest(n = 10, columns='Lift')) print('done')
151a4d7c08db11cda42296e330326be76d4d32c8
[ "Markdown", "Python" ]
11
Python
srinidhim3/ML_practice
d909075d19475663c3961b3da6c7e36e23a71dbc
450afdbeeb3719a13f27fc339a92c2b1aba8f8f6
HEAD
<file_sep>Ext JS versus Sencha Touch (super incomplete) ============================================= [Ext JS](http://www.sencha.com/products/extjs/) and [Sencha Touch](http://www.sencha.com/products/touch) are similar frameworks, but they aren't identical. Compare their differences. [Check it out here.](http://evanhahn.github.io/ExtJS-vs.-Sencha-Touch/the.html) <file_sep>var data = { /* * * * * * * * * * * * Ext globals * * * * * * * * * * * */ "Ext": [ { "name": "Ext._startTime", "ext": true }, { "name": "$previous", "ext": true }, { "name": "Function.prototype.$extIsFunction", "ext": true, "notes": "Used in Ext.isFunction." }, { "name": "Ext.enumerables", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-property-enumerables", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-property-enumerables" }, { "name": "Ext.apply", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-apply", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-apply" }, { "name": "Ext.buildSettings", "ext": true, "touch": true, "different": true }, { "name": "Ext.name", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-property-name" }, { "name": "Ext.emptyFn", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-property-emptyFn", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-property-emptyFn" }, { "name": "Ext.identityFn", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-identityFn" }, { "name": "Ext.emptyString", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-property-emptyString" }, { "name": "Ext.baseCSSPrefix", "ext": true, "touch": true }, { "name": "Ext.applyIf", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-applyIf", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-applyIf" }, { "name": "Ext.iterate", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-iterate", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-iterate" }, { "name": "Ext.extend", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-extend", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-extend" }, { "name": "Ext.override", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-override", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-override", "different": true, "notes": "ExtJS's overrides methods (messing with prototypes/Ext.define'd things). Touch's is deprecated (\"please use Ext.define instead\") and is a \"proxy to Ext.Base.override\"." }, { "name": "Ext.valueFrom", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-valueFrom", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-valueFrom" }, { "name": "Ext.typeOf", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-typeOf", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-typeOf" }, { "name": "Ext.coerce", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-coerce" }, { "name": "Ext.isEmpty", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isEmpty", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isEmpty" }, { "name": "Ext.isArray", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isArray", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isArray" }, { "name": "Ext.isDate", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isDate", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isDate" }, { "name": "Ext.isMSDate", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isMSDate" }, { "name": "Ext.isObject", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isObject", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isObject" }, { "name": "Ext.isSimpleObject", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isSimpleObject", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isSimpleObject" }, { "name": "Ext.isPrimitive", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isPrimitive", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isPrimitive" }, { "name": "Ext.isFunction", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isFunction", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isFunction", "different": true, "notes": "Implementations vary. Ext checks for a custom internal property called $extIsFunction. Touch works out some Safari inconsistencies." }, { "name": "Ext.isNumber", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isNumber", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isNumber" }, { "name": "Ext.isNumeric", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isNumeric", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isNumeric" }, { "name": "Ext.isString", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isString", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isString" }, { "name": "Ext.isBoolean", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isBoolean", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isBoolean" }, { "name": "Ext.isElement", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isElement", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isElement" }, { "name": "Ext.isTextNode", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isTextNode", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isTextNode" }, { "name": "Ext.isDefined", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isDefined", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isDefined" }, { "name": "Ext.isIterable", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-isIterable", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-isIterable", "different": true, "notes": "Implementations vary. Ext's seems more reliable." }, { "name": "Ext.clone", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-clone", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-clone" }, { "name": "Ext.getUniqueGlobalNamespace", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-getUniqueGlobalNamespace", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-getUniqueGlobalNamespace" }, { "name": "Ext.functionFactoryCache", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-property-functionFactoryCache" }, { "name": "Ext.cacheableFunctionFactory", "ext": true }, { "name": "Ext.functionFactory", "ext": true, "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-functionFactory", "different": true, "notes": "Implementations vary. Private." }, { "name": "Ext.globalEval", "ext": true, "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-property-globalEval", "different": true, "notes": "Ext has \"var Ext = this.ext\" before calling the eval. Touch does not." }, { "name": "Ext.Logger", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-property-Logger", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-property-Logger", "different": true }, { "name": "Ext.type", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-type", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-type" }, { "name": "Ext.collectNamespaces", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-collectNamespaces" }, { "name": "Ext.addNamespaces", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-addNamespaces" }, { "name": "Ext.clearNamespaces", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-clearNamespaces" }, { "name": "Ext.getNamespace", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-getNamespace" }, { "name": "Ext.versions", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-property-versions", "touch": true }, { "name": "Ext.lastRegisteredVersion", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-property-lastRegisteredVersion", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-property-lastRegisteredVersion" }, { "name": "Ext.setVersion", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-setVersion", "touch": true }, { "name": "Ext.getVersion", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-getVersion", "touch": true }, { "name": "Ext.deprecate", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-deprecate", "touch": true }, { "name": "Ext.htmlEncode", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-htmlEncode", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-htmlEncode", "different": true, "notes": "Deprecated." }, { "name": "Ext.htmlDecode", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-htmlDecode", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-htmlDecode", "different": true, "notes": "Deprecated." }, { "name": "Ext.urlAppend", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-urlAppend", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-urlAppend", "notes": "Deprecated." }, { "name": "Ext.num", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext-method-num", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext-method-num", "notes": "Deprecated." } ], "Ext.Array": [ { "name": "Ext.Array.replace", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Array-method-replace", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Array-method-replace", "notes": "Implementations vary slightly." }, { "name": "Ext.Array.each", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Array-method-each", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Array-method-each" }, { "name": "Ext.Array.erase", "ext": "", "touch": "" }, { "name": "Ext.Array.splice", "ext": "", "touch": "" }, { "name": "Ext.Array.forEach", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Array-method-forEach", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Array-method-forEach", "notes": "If using native forEach, Touch will return what the native forEach returns, but that doesn't matter because it's undefined." }, { "name": "Ext.Array.indexOf", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Array-method-indexOf", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Array-method-indexOf", "notes": "Implementations vary slightly." }, { "name": "Ext.Array.contains", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Array-method-contains", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Array-method-contains", "notes": "Implementations vary slightly." }, { "name": "Ext.Array.toArray", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Array-method-toArray", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Array-method-toArray" }, { "name": "Ext.Array.pluck", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Array-method-pluck", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Array-method-pluck" }, { "name": "Ext.Array.map", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Array-method-map", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Array-method-map", "notes": "Ext has some debug stuff." }, ], /* * * * * * * * * * * * Ext.Number * * * * * * * * * * * */ "Ext.Number": [ { "name": "Ext.Number.constrain", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Number-method-constrain", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Number-method-constrain", "different": true, "notes": "Most notably, implementations deal with NaN differently." }, { "name": "Ext.Number.snap", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Number-method-snap", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Number-method-snap", "notes": "Implementations vary slightly." }, { "name": "Ext.Number.snapInRange", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Number-method-snapInRange" }, { "name": "Ext.Number.toFixed", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Number-method-toFixed", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Number-method-toFixed", "notes": "Implementations vary slightly." }, { "name": "Ext.Number.from", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Number-method-from", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Number-method-from" }, { "name": "Ext.Number.randomInt", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Number-method-randomInt" }, { "name": "Ext.Number.correctFloat", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Number-method-correctFloat" } ], /* * * * * * * * * * * * Ext.String * * * * * * * * * * * */ "Ext.String": [ { "name": "Ext.String.trimRegex", "touch": true, "notes": "Private in Ext and public in Touch." }, { "name": "Ext.String.escapeRe", "touch": true, "notes": "Private in Ext and public in Touch." }, { "name": "Ext.String.formatRe", "touch": true, "notes": "Private in Ext and public in Touch." }, { "name": "Ext.String.escapeRegexRe", "touch": true, "notes": "Private in Ext and public in Touch." }, { "name": "Ext.String.htmlEncode", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-htmlEncode", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-htmlEncode", "different": true }, { "name": "Ext.String.htmlDecode", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-htmlDecode", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-htmlDecode", "different": true }, { "name": "Ext.String.insert", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-insert" }, { "name": "Ext.String.startsWith", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-startsWith" }, { "name": "Ext.String.endsWith", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-endsWith" }, { "name": "Ext.String.addCharacterEntities", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-addCharacterEntities" }, { "name": "Ext.String.resetCharacterEntities", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-resetCharacterEntities" }, { "name": "Ext.String.urlAppend", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-urlAppend", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-urlAppend" }, { "name": "Ext.String.trim", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-trim", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-trim" }, { "name": "Ext.String.capitalize", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-capitalize", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-capitalize" }, { "name": "Ext.String.uncapitalize", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-uncapitalize" }, { "name": "Ext.String.ellipsis", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-ellipsis", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-ellipsis" }, { "name": "Ext.String.escapeRegex", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-escapeRegex", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-escapeRegex" }, { "name": "Ext.String.escape", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-escape", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-escape" }, { "name": "Ext.String.toggle", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-toggle", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-toggle" }, { "name": "Ext.String.leftPad", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-leftPad", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-leftPad" }, { "name": "Ext.String.format", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-format", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-format" }, { "name": "Ext.String.repeat", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-repeat", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.String-method-repeat", "different": true, "notes": "Ext checks for a negative count." }, { "name": "Ext.String.createVarName", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-createVarName" }, { "name": "Ext.String.splitWords", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.String-method-splitWords" } ], /* * * * * * * * * * * * Ext.Version * * * * * * * * * * * */ "Ext.Version": [ { "name": "Ext.Version", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version" }, { "name": "Ext.Version#toString", "ext": true, "touch": true }, { "name": "Ext.Version#valueOf", "ext": true, "touch": true }, { "name": "Ext.Version#deprecate", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-deprecate" }, { "name": "Ext.Version#equals", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-equals", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-equals" }, { "name": "Ext.Version#getBuild", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-getBuild", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-getBuild" }, { "name": "Ext.Version#getMajor", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-getMajor", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-getMajor" }, { "name": "Ext.Version#getMinor", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-getMinor", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-getMinor" }, { "name": "Ext.Version#getPatch", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-getPatch", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-getPatch" }, { "name": "Ext.Version#getRelease", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-getRelease", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-getRelease" }, { "name": "Ext.Version#getShortVersion", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-getShortVersion", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-getShortVersion" }, { "name": "Ext.Version#getVersion", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-getVersion" }, { "name": "Ext.Version#gt", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-gt", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-gt" }, { "name": "Ext.Version#gtEq", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-gtEq", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-gtEq" }, { "name": "Ext.Version#isGreaterThan", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-isGreaterThan", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-isGreaterThan" }, { "name": "Ext.Version#isGreaterThanOrEqual", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-isGreaterThanOrEqual", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-isGreaterThanOrEqual" }, { "name": "Ext.Version#isLessThan", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-isLessThan", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-isLessThan" }, { "name": "Ext.Version#isLessThanOrEqual", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-isLessThanOrEqual", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-isLessThanOrEqual" }, { "name": "Ext.Version#lt", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-lt", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-lt" }, { "name": "Ext.Version#ltEq", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-ltEq", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-ltEq" }, { "name": "Ext.Version#match", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-match", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-match" }, { "name": "Ext.Version#setVersion", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-setVersion" }, { "name": "Ext.Version#toArray", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-method-toArray", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-toArray" }, { "name": "Ext.Version#toNumber", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-method-toNumber" }, { "name": "Ext.Version.releaseValueMap", "ext": true, "touch": true }, { "name": "Ext.Version.compare", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-static-method-compare", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-static-method-compare" }, { "name": "Ext.Version.getComponentValue", "ext": "http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.Version-static-method-getComponentValue", "touch": "http://docs.sencha.com/touch/2.2.0/#!/api/Ext.Version-static-method-getComponentValue" } ] };
1b80488c3fde613e1f4a3cd231e8a757cb8d7ef9
[ "Markdown", "JavaScript" ]
2
Markdown
EvanHahn/ExtJS-vs.-Sencha-Touch
6d41ba3710bd9c3720f05feeb230a7a22da96f18
972ba8255269ddd573f528b3d9045da5923f2a1a
refs/heads/master
<repo_name>bmj-hackathon/gardenstate<file_sep>/README.md # gardenstate Tracking the state of 100 ERC 721 NFT flower tokens, generating statistics and market information so you can become the next Flower Baron. ## The story so far ... A simple python script to scrape the hashbase.io json files, convert to Pandas dataframe (yes it's overkill) and save to `.csv`. You can also use the `npm dat` package at the command line. ## Roadmap - [x] Get the flower json data - [ ] Integrate with on-chain market transactions - [ ] Get the images - [ ] Train a CNN on the data <file_sep>/src/get_images.py import requests import logging import json #from datPython import Dat #import datpy import pandas as pd import glob, os #import datetime #import re import yaml #import posixpath import sys import zipfile import shutil #%% LOGGING for Spyder! Disable for production. logger = logging.getLogger() logger.handlers = [] # Set level logger.setLevel(logging.DEBUG) # Create formatter #FORMAT = "%(asctime)s - %(levelno)s - %(module)-15s - %(funcName)-15s - %(message)s" #FORMAT = "%(asctime)s L%(levelno)s: %(message)s" FORMAT = "%(asctime)s - %(funcName)-20s: %(message)s" DATE_FMT = "%Y-%m-%d %H:%M:%S" formatter = logging.Formatter(FORMAT, DATE_FMT) # Create handler and assign handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatter) logger.handlers = [handler] logger.critical("Logging started") logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) #%% IO LOCAL_PROJECT_PATH = glob.glob(os.path.expanduser('~/git/gardenstate'))[0] assert os.path.exists(LOCAL_PROJECT_PATH) LOCAL_DATA_PATH = os.path.join(LOCAL_PROJECT_PATH,'IMAGES') assert os.path.exists(LOCAL_DATA_PATH)#%% LOCAL_API_PATH = os.path.join(LOCAL_PROJECT_PATH,'API_PATH.yml') assert os.path.exists(LOCAL_API_PATH) #%% with open(LOCAL_API_PATH) as f: api_paths = yaml.load(f) #%% Get all timesteps r = requests.get(api_paths['TIMESTAMPS']) response_data = json.loads(r.text) time_stamps = response_data['timestamps'] logging.debug("Found {} timestamps".format(len(time_stamps))) [ts['key'] for ts in time_stamps] ts_series = pd.Series([ts['key'] for ts in time_stamps]) ts_dt_series = pd.to_datetime(ts_series,unit='s') ts_df = pd.concat([ts_dt_series,ts_series], axis=1) ts_df.columns = ['datetime','mtime'] ts_df['delta'] = (ts_df['datetime']-ts_df['datetime'].shift()).fillna(0) mean_timestep = ts_df['delta'].iloc[1::].mean() total_time_elapsed = ts_df['datetime'].iloc[-1] - ts_df['datetime'][0] logging.debug("mean timestep: {}".format(mean_timestep)) logging.debug("Total time elapsed:{}".format(total_time_elapsed)) #%% def download_save_image(t_url,out_path): # GET the wall image #TODO Check that os.path.join is cross-platform for URLs! r = requests.get(t_url) image = r.content #logging.debug("Downloaded image with size {}".format(len(image))) with open(out_path, 'wb') as f: f.write(image) #logging.debug("Saved image {}".format(out_path)) logging.debug("Downloaded {:7} bytes to {}".format(len(image),out_path)) def zip_flowers(path_folder,path_zip_out): # Collect the flower files all_image_files = glob.glob(os.path.join(path_folder, '*.jpg')) with zipfile.ZipFile(path_zip_out, 'w') as zip_this: for file in all_image_files: this_fname = os.path.split(file)[-1] zip_this.write(file, arcname = this_fname, compress_type=zipfile.ZIP_DEFLATED) logging.debug("Zipped {} files into {}".format(len(all_image_files),path_zip_out)) #%% #ts_df = ts_df[0:3] for i,record in ts_df.iterrows(): wall_url_name = record['mtime']+'.jpg' image_dt = record['datetime'] image_dt_str = image_dt.strftime('%Y%m%dT%H%M%S') logging.debug("Processing timestep {}".format(image_dt)) # Path handling, new directory for this timestamp path_folder_timestep = os.path.join(LOCAL_DATA_PATH,image_dt_str) path_this_wall = os.path.join(path_folder_timestep,image_dt_str+' wall'+'.jpg') path_flower_zip = os.path.join(path_folder_timestep+ ' flowers'+'.zip') # Skip if we already processed this timestamp if os.path.exists(path_flower_zip): logging.debug("Skipping {}, already exsists".format(image_dt)) continue if not os.path.exists(path_folder_timestep): os.mkdir(path_folder_timestep) wall_url = os.path.join(api_paths['BASE_API_URL'],'wall',wall_url_name) download_save_image(wall_url,path_this_wall) # Iterate over flowers for flnum in range(1,101): flower_fname = "flower{}.jpg".format(flnum) url_this_flwr = os.path.join(api_paths['BASE_API_URL'],'flowers',record['mtime'],flower_fname) #logging.debug("{} - {} {} bytes".format(flower_fname,r.status_code,len(flwr_image))) path_flwr = os.path.join(path_folder_timestep,image_dt_str + " "+ flower_fname) download_save_image(url_this_flwr,path_flwr) # Archive this timestamp zip_flowers(path_folder_timestep,path_flower_zip) # Clean up the directory #os.rmdir(path_folder_timestep) shutil.rmtree(path_folder_timestep, ignore_errors=False, onerror=None) #%% <file_sep>/src/get_json.py import requests import logging import json #from datPython import Dat #import datpy import pandas as pd import glob, os import datetime import re import yaml #%% #dat = datpy.Dat() #r = dat.download(BASE_URL, 'data') #print(r) #datetime.datetime.now().isoformat() #%% IO LOCAL_PROJECT_PATH = glob.glob(os.path.expanduser('~/git/gardenstate'))[0] assert os.path.exists(LOCAL_PROJECT_PATH) LOCAL_DATA_PATH = os.path.join(LOCAL_PROJECT_PATH,'DATA') assert os.path.exists(LOCAL_DATA_PATH) LOCAL_API_PATH = os.path.join(LOCAL_PROJECT_PATH,'API_PATH.yml') assert os.path.exists(LOCAL_API_PATH) #%% Get all links with open(LOCAL_API_PATH) as f: api_paths = yaml.load(f) r = requests.get(api_paths['BASE_URL']) all_base_links = json.loads(r.text) #%% Loop over each individually all_data = list() for l in all_base_links: if re.search('^ flower\d+',l['name']): file_url = requests.compat.urljoin(api_paths['BASE_URL'],l['path']) r = requests.get(file_url) this_data = json.loads(r.text) all_data.append(this_data['Flower']) print("Saved", l) else: print("Skip",l) #print(l) #%% Save data # Create a DF df = pd.DataFrame.from_records(all_data).set_index('id') df['date'] = pd.to_datetime(df['timestamp'],unit='s') df.sort_index(inplace=True) # Save to disk timestamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%SB") path_csv = os.path.join(LOCAL_DATA_PATH,timestamp+".csv") df.to_csv(path_csv) print("Saved to {}".format(path_csv)) #%% Get all data at once # This has a problem - no flower_id!!! if 0: r = requests.get("https://flowertokens.hashbase.io/all_flowers.json") df = pd.DataFrame(all_data,index = '') #%% # This has a problem - no flower ID!!!
356f09ed09e20d50f3b455b929f195af9069c836
[ "Markdown", "Python" ]
3
Markdown
bmj-hackathon/gardenstate
e2e1bf0bd0b05522b0cbec0e6e8b35ff6a9ea762
6dfdbb064160409d03f9a7503d440035d637ad7b
refs/heads/master
<file_sep>using System; using Microsoft.AspNetCore.Connections; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Orleans.Connections.Security; namespace Orleans { public static class TlsConnectionBuilderExtensions { public static void UseServerTls( this IConnectionBuilder builder, TlsOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } var loggerFactory = builder.ApplicationServices.GetService(typeof(ILoggerFactory)) as ILoggerFactory ?? NullLoggerFactory.Instance; builder.Use(next => { var middleware = new TlsServerConnectionMiddleware(next, options, loggerFactory); return middleware.OnConnectionAsync; }); } public static void UseClientTls( this IConnectionBuilder builder, TlsOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } var loggerFactory = builder.ApplicationServices.GetService(typeof(ILoggerFactory)) as ILoggerFactory ?? NullLoggerFactory.Instance; builder.Use(next => { var middleware = new TlsClientConnectionMiddleware(next, options, loggerFactory); return middleware.OnConnectionAsync; }); } } } <file_sep>using System; using System.Runtime.CompilerServices; namespace Orleans.Runtime { internal class RuntimeContext { public ISchedulingContext ActivationContext { get; private set; } [ThreadStatic] private static RuntimeContext context; public static RuntimeContext Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => context ??= new RuntimeContext(); } internal static ISchedulingContext CurrentActivationContext { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => Current?.ActivationContext; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void SetExecutionContext(ISchedulingContext shedContext) { Current.ActivationContext = shedContext; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ResetExecutionContext() { context.ActivationContext = null; } public override string ToString() { return String.Format("RuntimeContext: ActivationContext={0}", ActivationContext != null ? ActivationContext.ToString() : "null"); } } }
c35c60691dc43ca631cbe0fd09409458df3ff6e5
[ "C#" ]
2
C#
igitur/orleans
fadace6a2bee298f12365e988ebf7bc77ec50faa
21a39cc2b19589d5f12a15e6e85d3c4b5c9ee0f2
refs/heads/master
<repo_name>MinSiThu/YawYwatWar<file_sep>/yywEditor/Elements/Selector/Option.js let AbstractElement = require('../AbstractElement'); class Option extends AbstractElement{ constructor(config){ super('option'); this.element.innerText = config.text; this.element.value = config.value; } } module.exports = Option;<file_sep>/yywEditor/Elements/ToolItem/index.js let ContentTypes = require('../../ContentTypes'); let ContentInterfaces = require('../../ContentInterfaces'); let AbstractElement = require('../AbstractElement'); let Button = require('../Button'); let Selector = require('../Selector'); class ToolItem extends AbstractElement { static create(contentType){ switch (contentType) { case ContentTypes.BOLD: return new Button(ContentInterfaces.BOLD) break; case ContentTypes.ITALIC: return new Button(ContentInterfaces.ITALIC) break; case ContentTypes.UNDERLINE: return new Button(ContentInterfaces.UNDERLINE) break; case ContentTypes.IMAGE: return new Button(ContentInterfaces.LINK) break; case ContentTypes.LINK: return new Button(ContentInterfaces.IMAGE) break; case ContentTypes.HEADING: return new Selector(ContentInterfaces.HEADING) break; case ContentTypes.LEFT_ALIGN: return new Button(ContentInterfaces.LEFT_ALIGN) break; case ContentTypes.RIGHT_ALIGN: return new Button(ContentInterfaces.RIGHT_ALIGN) break; case ContentTypes.CENTER_ALIGN: return new Button(ContentInterfaces.CENTER_ALIGN) break; case ContentTypes.ORDERED_LIST: return new Button(ContentInterfaces.ORDERED_LIST) break; case ContentTypes.UNORDERED_LIST: return new Button(ContentInterfaces.UNORDERED_LIST) break; default: break; } } } module.exports = ToolItem;<file_sep>/yywEditor/ContentInterfaces/index.js let SingletonDOM = require('../SingletonDOM'); const ContentInterfaces = { BOLD:{ ICON:"<b>B</b>", shortcutKey:"ctrl+b", toggle:true, state: () => document.queryCommandState('bold'), activate:()=>{ SingletonDOM.element.focus(); document.execCommand('bold',false); } }, ITALIC:{ ICON:"<i>i</i>", shortcutKey:"ctrl+i", toggle:true, state: () => document.queryCommandState('italic'), activate(){ SingletonDOM.element.focus(); document.execCommand('italic',false); } }, UNDERLINE:{ ICON:"<u>U</u>", shortcutKey:"ctrl+u", toggle:true, state: () => document.queryCommandState('underline'), activate(){ SingletonDOM.element.focus(); document.execCommand('underline',false); } }, LEFT_ALIGN:{ ICON:`<i class="fa fa-align-left"></i>`, shortcutKey:"", toggle:true, state: () => document.queryCommandState('justifyleft'), activate(){ SingletonDOM.element.focus(); document.execCommand('justifyleft',false); } }, RIGHT_ALIGN:{ ICON:`<i class="fa fa-align-right"></i>`, shortcutKey:"", toggle:true, state: () => document.queryCommandState('justifyright'), activate(){ SingletonDOM.element.focus(); document.execCommand('justifyright',false); } }, CENTER_ALIGN:{ ICON:`<i class="fa fa-align-center"></i>`, shortcutKey:"", toggle:true, state: () => document.queryCommandState('justifycenter'), activate(){ SingletonDOM.element.focus(); document.execCommand('justifycenter',false); } }, ORDERED_LIST:{ ICON:`<i class="fa fa-list-ol"></i>`, shortcutKey:"", toggle:true, activate(){ SingletonDOM.element.focus(); document.execCommand('insertorderedlist',false); } }, UNORDERED_LIST:{ ICON:`<i class="fa fa-list-ul"></i>`, shortcutKey:"", toggle:true, activate(){ SingletonDOM.element.focus(); document.execCommand('insertunorderedlist',false); } }, HEADING:{ ICON:`<i class="fas fa-user">H</i>`, toggle:false, options:[ { "text":"Main-Heading", "value":"h1" }, { "text":"Sub-Heading", "value":"h4" } ], activate(value){ SingletonDOM.element.focus(); document.execCommand('formatblock',false,value) } }, LINK:{ ICON:`<i class="fa fa-link"></i>`, toggle:false, activate(){ SingletonDOM.element.focus(); let src = prompt('Enter HTTP URL!') if(src != null){ document.execCommand('createLink',false,src); } } }, IMAGE:{ ICON:`<i class="fa fa-image"></i>`, toggle:false, async getInput(){ return prompt('Enter Image URL!'); }, async activate(){ SingletonDOM.element.focus(); let src = await this.getInput(); if(src != null){ document.execCommand('insertImage',false,src); } } }, } ContentInterfaces.setPlugin = function(interfaceName,cb){ switch (interfaceName){ case "IMAGE": ContentInterfaces["IMAGE"].getInput = cb; break; } } module.exports = ContentInterfaces;<file_sep>/yywEditor/plugins/imageExplorer/index.js function openFileExplorer(State) { return new Promise((resolve,reject)=>{ let fileInput = document.createElement("input"); fileInput.setAttribute("type","file"); fileInput.click(); fileInput.onchange = function(e){ let file = this.files[0]; State.imageFiles.push(file); //push plugins State Here let reader = new FileReader(); reader.onload = function(e){ resolve(e.target.result) } reader.readAsDataURL(file); } }) } module.exports = function(State){ return async function(){ let path = await openFileExplorer(State); return path; } }<file_sep>/README.md # YawYwatWar ``` npm i --save yawywatwar-editor ``` ```html <link rel="stylesheet" href="/https://unpkg.com/yawywatwar-editor@latest/yywEditor/stylesheets/TextEditor.css"> <div id="content"> </div> <script src="https://unpkg.com/yawywatwar-editor@latest/index.js"><script> ``` ```js function bootstrap(){ let txeditor = new YawYwatWarEditor(document.getElementById('content')) txeditor.setUp({ toolbarConfig:["bold","italic","underline","link", "image","heading", "left-align","right-align","center-align", "ordered-list","unordered-list", ], plugins: { IMAGE:Plugins.imageExplorer, } }) } bootstrap() ``` <file_sep>/yywEditor/index.js let TextEditor = require('./Elements/TextEditor'); let {State} = require("./plugins"); let ContentInterfaces = require("./ContentInterfaces"); let SingletonDOM = require("./SingletonDOM"); //SuperEditor is for better stylesheets Management class YawYwatWarEditor{ constructor(element){ this.mainElement = element; this.textEditor = new TextEditor(); this.mainElement.appendChild(this.textEditor.getHTMLElement()) this.theme = ""; } setUp({toolbarConfig,plugins,theme="primaryStyle"}){ this.textEditor.setUp({toolbarConfig,theme}) this.setPlguins(plugins) this.setUpTheme(theme); } setUpTheme(theme){ this.theme = theme; this.mainElement.setAttribute('class',this.theme) } setPlguins(plugins){ for(var prop in plugins){ ContentInterfaces.setPlugin(prop,plugins[prop]); } } getHTML(){ return SingletonDOM.getHTML(); } } if(window){ window.YawYwatWarEditor = YawYwatWarEditor; } module.exports = YawYwatWarEditor;<file_sep>/yywEditor/plugins/index.js let State = { imageFiles:[] } let imageExplorer = require("./imageExplorer")(State); let Plugins = { imageExplorer, State, } if(window){ window.Plugins = Plugins; } module.exports = Plugins;<file_sep>/yywEditor/ContentTypes/index.js const ContentTypes = { BOLD:'bold', ITALIC:'italic', LINK:"link", IMAGE:"image", HEADING:"heading", UNDERLINE:"underline", LEFT_ALIGN:"left-align", RIGHT_ALIGN:"right-align", CENTER_ALIGN:"center-align", ORDERED_LIST:"ordered-list", UNORDERED_LIST:"unordered-list", } module.exports = ContentTypes;<file_sep>/yywEditor/KeyBoard/index.js let keyboardJS = require('keyboardjs') const couplers = []; module.exports.add = function(workingInterface,eventHandler){ couplers.push({workingInterface,eventHandler}); if(workingInterface.shortcutKey != undefined && workingInterface.shortcutKey != ""){ keyboardJS.bind(workingInterface.shortcutKey, eventHandler); } }<file_sep>/index.test.js function bootstrap(){ let txeditor = new YawYwatWarEditor(document.getElementById('content')) txeditor.setUp({ toolbarConfig:["bold","italic","underline","link", "image","heading", "left-align","right-align","center-align", "ordered-list","unordered-list", ], plugins: { IMAGE:Plugins.imageExplorer, } }) } bootstrap()<file_sep>/yywEditor/Elements/Button/index.js let AbstractElement = require('../AbstractElement'); let SingletonDOM = require("../../SingletonDOM"); //let KeyBoard = require('../../KeyBoard'); class Button extends AbstractElement{ constructor(workingInterface){ super('button'); this.clickCounter = false; this.workingInterface = workingInterface; let eventHandler =(toolItem)=>{ return function(e){ /* toolItem.clickCounter = !toolItem.clickCounter; if(toolItem.clickCounter == true && toolItem.workingInterface.toggle == true){ toolItem.element.setAttribute('class',"clicked") }else if(toolItem.clickCounter == false && toolItem.workingInterface.toggle == true){ toolItem.element.setAttribute('class',"") }*/ toolItem.workingInterface.activate(); if(toolItem.workingInterface.state){ this.classList[toolItem.workingInterface.state()?"add":"remove"]("clicked"); } } } SingletonDOM.getDOM().addEventListener("mouseup",()=>{ if(this.workingInterface.state){ this.element.classList[this.workingInterface.state()?"add":"remove"]("clicked"); } }) SingletonDOM.getDOM().addEventListener("keyup",()=>{ if(this.workingInterface.state){ this.element.classList[this.workingInterface.state()?"add":"remove"]("clicked"); } }) //element events this.element.innerHTML = this.workingInterface.ICON; this.element.addEventListener('click',eventHandler(this)) // KeyBoard.add(this.workingInterface,eventHandler(this)) } } module.exports = Button;<file_sep>/yywEditor/Elements/TextEditor/index.js let ToolBar = require('../ToolBar'); let Footer = require('../Footer'); let AbstractElement = require('../AbstractElement'); let SingletonDOM = require('../../SingletonDOM'); class TextEditor extends AbstractElement{ constructor(){ super('div'); this.theme = ""; this.element.setAttribute('contenteditable',true); SingletonDOM.setDOM(this.element); } setUp({toolbarConfig,theme="primaryStyle"}){ this.setUpTheme(theme) this.setUpToolBar(toolbarConfig) this.setUpFooter(); } setUpToolBar(toolbarConfig){ let toolBar = new ToolBar(this.theme); toolBar.setConfig(toolbarConfig); this.element.insertAdjacentElement('beforeBegin',toolBar.getHTMLElement()) } setUpFooter(){ let footer = Footer.createProductFooter(); this.element.insertAdjacentElement('afterend',footer.getHTMLElement()); } setUpTheme(theme){ this.theme = theme; SingletonDOM.setTheme(this.theme); this.element.classList.add(theme+"--textEditor") } } module.exports = TextEditor; <file_sep>/yywEditor/Elements/AbstractElement/index.js class AbstractElement{ constructor(elementName){ this.element = document.createElement(elementName); } getHTMLElement(){ return this.element; } add(Element){ this.element.appendChild(Element.getHTMLElement()); } } module.exports = AbstractElement;
86dfc612768c41c2e6ae8161203012cc9db8ba60
[ "JavaScript", "Markdown" ]
13
JavaScript
MinSiThu/YawYwatWar
e81b463a7c7adbc180f8207bc9bdc06a6532c345
64ca644d478b0844fb6d6c629a4829e470029d1d
refs/heads/master
<file_sep># miscellaneous fun programming * A Vide Player GUI * Face detection using HAAR classifier * Testing for a ploygon * Robot manipulation in a point cloud data * Basic python excercises <file_sep>import java.util.*; public class Integers { public static void main(String []args) { System.out.println("enter the number of integers : "); List integer_list=new ArrayList(); Scanner scan=new Scanner(System.in); int input=scan.nextInt(); for (int j=1; j<=input;j++) { integer_list.add(scan.nextInt()); } int sum=0; for (int j=0; j<integer_list.size();j++) { sum += (Integer)integer_list.get(j); } int product=1; for (int j=0; j<integer_list.size();j++) { product = product *(Integer)integer_list.get(j); } int average=1; for (int j=0; j<integer_list.size();j++) { average = sum / input; } float var=0; for (int j=0; j<integer_list.size();j++) { var +=(((Integer)integer_list.get(j)-average)*((Integer)integer_list.get(j)-average))/input; } int maxvalue= (Integer)integer_list.get(0); for (int j=0; j<integer_list.size();j++) { if((Integer)integer_list.get(j) > maxvalue){ maxvalue = (Integer)integer_list.get(j); } } int minvalue= (Integer)integer_list.get(0); for (int j=0; j<integer_list.size();j++) { if((Integer)integer_list.get(j) < minvalue){ minvalue = (Integer)integer_list.get(j); } } System.out.println("integer list : "+integer_list); System.out.println("sum of integers : "+sum); System.out.println("product of integers : "+product); System.out.println("average of the integers : "+average); System.out.println("variance of the integers : "+var); System.out.println("maximun value of the integers : "+maxvalue); System.out.println("maximun value of the integers : "+minvalue); } } <file_sep>## Instructions to build `mkdir build` `cd build` `cmake ..` `make` ## Instructions to run `./test_polygon` ## Implementation See [here](https://stackoverflow.com/questions/8721406/how-to-determine-if-a-point-is-inside-a-2d-convex-polygon) for algorithm for how to determine if a point is inside a polygon <file_sep>cmake_minimum_required(VERSION 2.6) project(polygon_test) set(CMAKE_CXX_STANDARD 11) include_directories( . ) add_executable(test_polygon polygon.cpp test_polygon.cpp ) target_link_libraries(test_polygon) <file_sep>#include <polygon.h> Polygon::Polygon(const std::vector<std::pair<double, double>> &points) { this->points = points; } Polygon::~Polygon() { } bool Polygon::isPointInPolygon(const std::pair<double, double> &p) { int i; int j; bool result = false; for (i = 0, j = points.size() - 1; i < points.size(); j = i++) { if ((points[i].second > p.second) != (points[j].second > p.second) && (p.first < (points[j].first - points[i].first) * (p.second - points[i].second) / (points[j].second-points[i].second) + points[i].first)) { result = !result; } } return result; } <file_sep>mkdir build cd build cmake .. make ## Instructions to run ./test_polygon <file_sep>#include <polygon.h> #define CATCH_CONFIG_MAIN #include <catch.hpp> TEST_CASE("IsPointInPolygon test", "[polygon]") { std::vector<std::pair<double, double>> points; points.push_back(std::make_pair<double, double>(1.0, 1.0)); points.push_back(std::make_pair<double, double>(1.0, 2.0)); points.push_back(std::make_pair<double, double>(2.0, 2.0)); points.push_back(std::make_pair<double, double>(2.0, 1.0)); // TODO insert more vertices of the polygon here Polygon p(points); std::pair<double, double> test_point = std::make_pair<double, double>(3.0, 3.0); bool isPointInPolygon = p.isPointInPolygon(test_point); REQUIRE(isPointInPolygon == false); std::pair<double, double> test_point2 = std::make_pair<double, double>(1.5, 1.5); bool isPointInPolygon2 = p.isPointInPolygon(test_point2); REQUIRE(isPointInPolygon2 == true); std::pair<double, double> test_point3 = std::make_pair<double, double>(1.0,1.0); bool isPointInPolygon3 = p.isPointInPolygon(test_point3); REQUIRE(isPointInPolygon3 == true); // TODO: write more test cases here (i.e. with different test_points) //REQUIRE(isPointInPolygon == false); } <file_sep>#ifndef POLYGON_H #define POLYGON_H #include <vector> #include <utility> class Polygon { private: // set of vertices of the polygon std::vector<std::pair<double, double>> points; public: Polygon(const std::vector<std::pair<double, double>> &points); virtual ~Polygon(); bool isPointInPolygon(const std::pair<double, double> &p); }; #endif /* POLYGON_H */
35c6be30871b4b667e9d878ca5bc323a284e50a9
[ "CMake", "Markdown", "Java", "C++", "Shell" ]
8
Markdown
someshdev/Random
12347916c0a3219bf235ad3d1b1e425aaa313623
986e7eb24d93ee4242fb4153c7ed43c9636cda72
refs/heads/master
<file_sep>print 'This game is so fun right' print 'You won' def draw_board(bad_guesses): # This is always drawn print("______________") print("| / |") print("|/ |") # different level of hang-ness if bad_guesses is 0: print("|") print("|") print("|") elif bad_guesses is 1: print("| O") print("|") print("|") print("|") elif bad_guesses is 2: print("| O") print("| |") print("| |") print("|") elif bad_guesses is 3: print("| __O") print("| |") print("| |") print("|") elif bad_guesses is 4: print("| __O__") print("| |") print("| |") elif bad_guesses is 5: print("| __O__") print("| |") print("| |") print("| /") else: print("| __O__") print("| |") print("| |") print("| / \\") # this is also always drawn print("|") print("|") print("|") print("|________________|") spaces = "__" for i in range(1, len(word)): spaces = spaces + " __" # draw spaces - need to put a function here to insert correct guesses in right location print(spaces) # Fill print word on spaces using variation of afore-said function if bad_guesses >= 6: print("You could not guess the number. It was {0}".format(word))
a4bc3c7cb745ea6ab4200316537683ba005c633a
[ "Python" ]
1
Python
Hosch250/ascii-gallows-club
989bbeef1fb086ea40a27d3fb781f20d68be9c1f
73c789154c4f3cf6e5aaa54707c086382758aaab
refs/heads/master
<repo_name>HYO-Altair/actio-mensura-frontend<file_sep>/src/utils/README.md Folder full of helper functions that are used globally. Export repeated logic to a singular location here and import where needed. <file_sep>/src/routes/statistics/Statistics.js import React, { useEffect } from "react"; import app from "firebase/app"; import "firebase/database"; import Linegraph from "../../components//linegraph/Linegraph"; // set querystring to extract search parameters const queryString = require("query-string"); const config = { apiKey: process.env.REACT_APP_API_KEY, authDomain: process.env.REACT_APP_AUTH_DOMAIN, databaseURL: process.env.REACT_APP_DATABASE_URL, projectId: process.env.REACT_APP_PROJECT_ID, storageBucket: process.env.REACT_APP_STORAGE_BUCKET, messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID, }; // initialize firebase app.initializeApp(config); const db = app.database(); export default function Statistics(props) { // hooks const [id, setID] = React.useState(null); const [serverFound, setServerFound] = React.useState(false); const [stats, setStats] = React.useState({}); useEffect(() => { // extract and set server id let parsed = queryString.parse(props.location.search); setID(parsed.id); // check database for server db.ref(`servers/${queryString.parse(props.location.search).id}`).once( "value", (snapshot) => { // if found if (snapshot.val()) { // indicate server was found setServerFound(true); // track statistics db.ref(snapshot.val() + "/days/").on("value", (snapshot) => { console.log(snapshot.val()); if (snapshot.val() !== stats) setStats(snapshot.val()); }); } else setServerFound(false); return; } ); }, []); return ( <div className='body'> <div> <div className='main-stats'> <h1 className='server-heading'> SERVER STATS for {id} {"\u00A0"} <br /> server found: {serverFound ? "yes" : "no"} <br /> <Linegraph stats={stats} /> </h1> </div> </div> </div> ); } <file_sep>/src/routes/home/Home.js import React from "react"; import { useState, useEffect } from "react"; import { Form, Input, Button, Checkbox } from "antd"; import { Link } from "react-router-dom"; import Box from "@material-ui/core/Box"; export default function Home(props) { const [form] = Form.useForm(); const [buttonDisabled, setButtonDisabled] = React.useState(true); const [id, setID] = React.useState(""); const handleIDChange = (e) => { if (e.target.value === "") setButtonDisabled(true); else setButtonDisabled(false); setID(e.target.value); console.log(e.target.value); }; return ( <div className='body'> <div className='main'> <div> <div> <h1 className='logo'>ACTIO MENSURA</h1> </div> <div className='form'> <Form form={form} layout='inline' name='basic' initialValues={{ remember: true, }} > <Form.Item name='serverID' rules={[ { required: true, message: "Please input your serverID!", }, ]} > <Input placeholder='Enter your serverID' onChange={(e) => handleIDChange(e)} /> </Form.Item> <Form.Item> <Link to={{ pathname: "/statistics", search: "?id=" + id }}> <Button type='primary' htmlType='button' disabled={buttonDisabled} > Submit </Button> </Link> </Form.Item> </Form> </div> <div className='footer'> <p></p> <p>A bot to track your discord server activity | By <NAME></p> <p></p> </div> </div> </div> </div> ); } <file_sep>/src/routes/README.md Components provided directly to react-router's <Route>s. May use Components from src/components, but route entry points are unique in that their best name is where they are not what they do. <file_sep>/src/components/linegraph/Linegraph.js import React from "react"; import { Line, Bar } from "react-chartjs-2"; import Paper from "@material-ui/core/Paper"; export default function Linegraph(props) { const data = { labels: [...Object.keys(props.stats)].reverse(), datasets: [ { label: "Number of Messages", backgroundColor: "rgba(255,99,132,0.2)", borderColor: "rgba(255,99,132,1)", borderWidth: 1, hoverBackgroundColor: "rgba(255,99,132,0.4)", hoverBorderColor: "rgba(255,99,132,1)", data: [...Object.values(props.stats)].reverse(), }, ], }; const options = { scales: { xAxes: [ { type: "time", time: { unit: "day", unitStepSize: 1, displayFormats: { day: "MMM DD" }, }, }, ], yAxes: [{ ticks: { beginAtZero: true } }], }, }; return ( <div> <Paper> <Bar data={data} options={options} /> </Paper> </div> ); } <file_sep>/src/components/README.md Components folder. Structure should follow components └── component-name │ ├── component-name.css │ ├── component-name.js │ └── component-name.test.js │ └── ... etc
44612a40de51bac89f0bcb0daae85944b39ce458
[ "Markdown", "JavaScript" ]
6
Markdown
HYO-Altair/actio-mensura-frontend
4c9d40fd0a0d4e9e1c07702208b6d3b1712d6065
45a733664a835122a0124cd401f886238087e2df
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class Staff { [Key] public int staffId { get; set; } public string staffFname { get; set; } public string staffLname { get; set; } public string staffEmail { get; set; } public string staffExt { get; set; } public int SpecialtyID { get; set; } [ForeignKey("SpecialtyID")] public virtual Speciality Speciality { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using System.Diagnostics; using System.IO; namespace HumberAreaHospitalProject.Controllers { public class QuestionController : Controller { //create db context private HospitalContext db = new HospitalContext(); // GET: Question [Authorize] public ActionResult List() { //This method lists all the questions Debug.WriteLine("Trying to list all the records"); string query = "Select * from questions"; List<Question> questions= db.Questions.SqlQuery(query).ToList(); return View(questions); } [Authorize] public ActionResult New() { //Method to add a new questions return View(); } [HttpPost] public ActionResult New(string QuestionText) { /*This method takes in a new speciality name and writes it to the DB*/ string query = "insert into questions (QuestionText) values(@QuestionText)"; SqlParameter parameter = new SqlParameter("@QuestionText", QuestionText); db.Database.ExecuteSqlCommand(query, parameter); return RedirectToAction("List"); } [Authorize] public ActionResult Update(int id) { /*this method will show the base info of the selected record*/ Debug.WriteLine("I am trying to update record with id" + id); string query = "select * from questions where questionid = @id"; SqlParameter parameter = new SqlParameter("@id", id); Question selectedquestion = db.Questions.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedquestion); } //now the post method [HttpPost] public ActionResult Update(int id,string QuestionText) { //Method to update a record Debug.WriteLine("I am trying to update record with id" + id); string query = "Update questions set QuestionText=@QuestionText where questionid=@id"; SqlParameter[] parameters = new SqlParameter[2]; parameters[0] = new SqlParameter("@QuestionText", QuestionText); parameters[1] = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, parameters); return RedirectToAction("List"); } [Authorize] public ActionResult View(int id) { string query = "Select * from questions where questionid=@id"; SqlParameter parameter = new SqlParameter("@id", id); Question selectedquestion = db.Questions.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedquestion); } [Authorize] public ActionResult Delete(int id) { string query = "Select * from questions where questionid=@id"; SqlParameter parameter = new SqlParameter("@id", id); Question selectedquestion = db.Questions.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedquestion); } [HttpPost] public ActionResult Delete(int? id) { string query = "Delete from questions where questionid=@id"; SqlParameter parameter = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, parameter); return RedirectToAction("List"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models.ViewModels { public class AppointmentViewModel { public virtual Appointment appointment { get; set; } public virtual List<Doctor> doctors { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using System.Diagnostics; using System.Data.SqlClient; using System.Data.Entity; using System.Net; namespace HumberAreaHospitalProject.Controllers { public class VolunteerController : Controller { private HospitalContext db = new HospitalContext(); //Accessible only for user that is login //[Authorize] public ActionResult List(string searchkey, int pagenum = 1) { //Christine Bittle In-Class Example //Query to get All the VOlunteers string query = "Select * from Volunteers"; //Debug.WriteLine(query); //Start creating a Class for sql parameter List<SqlParameter> parameters = new List<SqlParameter>(); //Searchkey is not empty if (searchkey != "") { //Add to the query for Search query = query + " where VolunteerFname like @searchkey OR VolunteerLname like @searchkey"; parameters.Add(new SqlParameter("@searchkey", "%" + searchkey + "%")); } //Execute the sql query for volunteers List<Volunteer> volunteers = db.Volunteers.SqlQuery(query, parameters.ToArray()).ToList(); //Add Variable for how many per page int perpage = 3; //Debug.WriteLine("Volunteer Count is "+volunteers.Count()); //Get the total count values of volunteers int volunteercount = volunteers.Count(); //Max page will be the Count Divided by per page. Rounding this to the upper limit so that //rows which are not divisible to the perpage will still be shown int maxpage = (int)Math.Ceiling((decimal)volunteercount / perpage); //Maxpage is greater than 0, maxpage will be zero if (maxpage < 0) maxpage = 0; //Page number less than 1 will always be 1 if (pagenum < 1) pagenum = 1; //If page number is greater than maxpage, pagenum will be equal to maxpage if (pagenum > maxpage) pagenum = maxpage; //Start value should be 0, but should be ascending depending on the perpage value //Start with index 0, and then next will be 3, since perpage is 3. So the next page will start with index 3. //The first page will show 0,1,2 index row and the next page will be 3,4,5 indexes and so on. int start = (int)(perpage * pagenum) - perpage; //Debug.WriteLine("start number is: "+start); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; ViewData["maxpage"] = maxpage; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum) + " of " + (maxpage); List<SqlParameter> newparams = new List<SqlParameter>(); if (searchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + searchkey + "%")); ViewData["searchkey"] = searchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by VolunteerID offset @start rows fetch first @perpage rows only "; //string pagedquery = query + " order by VolunteerID offset 1 rows fetch first 3 rows only "; Debug.WriteLine(pagedquery); //Debug.WriteLine("offset " + start); //Debug.WriteLine("fetch first " + perpage); //Re-write the execution of sql query with page listing volunteers = db.Volunteers.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } return View(volunteers); } //Accessible only for user that is login //[Authorize] //Get View for the specific volunteer public ActionResult View(int id) { //Execute the sql with the Query on it Volunteer selectedvolunteer = db.Volunteers.SqlQuery("Select * from Volunteers where VolunteerID = @id", new SqlParameter("@id", id)).First(); return View(selectedvolunteer); } //Use to apply also on the other view //[ActionName("Apply_today")] //This function is needed for the User to Show as a different URL public ActionResult Create() { return View(); } //Use to apply also on the other view [HttpPost] public ActionResult Create(string volunteerFname, string volunteerLname, string address, string email, string homePhone, string workPhone, string skills, ICollection<string> day, string time, string preference, string notes) { String seperator = ","; string listdays = ""; //All value on the days will be concatenated here //Joining "days" and the "separator" and storing them in a variable "listdays" listdays += String.Join(seperator, day); try { //Try if the SQL query will work string query = "INSERT into Volunteers (VolunteerFname, VolunteerLname, Address, Email, HomePhone, WorkPhone, Skills, Day, Time, Preference, Notes)" + " values (@fname, @lname, @address, @email, @homephone, @workphone, @skills, @day, @time, @preference, @notes)"; //Debug.WriteLine(query); SqlParameter[] parameters = new SqlParameter[11]; parameters[0] = new SqlParameter("@fname", volunteerFname); parameters[1] = new SqlParameter("@lname", volunteerLname); parameters[2] = new SqlParameter("@address", address); parameters[3] = new SqlParameter("@email", email); parameters[4] = new SqlParameter("@homephone", homePhone); parameters[5] = new SqlParameter("@workphone", workPhone); parameters[6] = new SqlParameter("@skills", skills); parameters[7] = new SqlParameter("@day", listdays); parameters[8] = new SqlParameter("@time", time); parameters[9] = new SqlParameter("@preference", preference); parameters[10] = new SqlParameter("@notes", notes); db.Database.ExecuteSqlCommand(query, parameters); // Debug.WriteLine("The new record being added in Volunteers"); return RedirectToAction("List"); } catch { //Get Bad Request if Sql got error return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } //Accessible only for user that is login //[Authorize] public ActionResult Update(int? id) { if (id == null) { //If no id value has been presented, will return a BadRequest return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } string query = "Select * from Volunteers where VolunteerID=@id"; //Debug.WriteLine(query); SqlParameter parameter = new SqlParameter("@id", id); Volunteer selectedvolunteer = db.Volunteers.SqlQuery(query, parameter).First(); if (selectedvolunteer == null) { //If value is null on selectedvolunteer, no value on the database return HttpNotFound(); } return View(selectedvolunteer); } [HttpPost] public ActionResult Update(int id, string volunteerFname, string volunteerLname, string address, string email, string homePhone, string workPhone, string skills, ICollection<string> day, string time, string preference, string notes) { try { String seperator = ","; string listdays = ""; //All value on the days will be concatenated here //Joining "days" and the "separator" and storing them in a variable "listdays" listdays += String.Join(seperator, day); //ArticleTitle, ArticleBody, Date,Featured, AuthorID string query = "UPDATE Volunteers set VolunteerFname = @fname, VolunteerLname = @lname, Email = @email, HomePhone = @homephone, " + "WorkPhone = @workphone, Skills = @skills, Day = @day, Time = @time, Preference = @preference, Notes = @notes where VolunteerID = @id "; //Debug.WriteLine(query); SqlParameter[] parameters = new SqlParameter[12]; parameters[0] = new SqlParameter("@fname", volunteerFname); parameters[1] = new SqlParameter("@lname", volunteerLname); parameters[2] = new SqlParameter("@address", address); parameters[3] = new SqlParameter("@email", email); parameters[4] = new SqlParameter("@homephone", homePhone); parameters[5] = new SqlParameter("@workphone", workPhone); parameters[6] = new SqlParameter("@skills", skills); parameters[7] = new SqlParameter("@day", listdays); parameters[8] = new SqlParameter("@time", time); parameters[9] = new SqlParameter("@preference", preference); parameters[10] = new SqlParameter("@notes", notes); parameters[11] = new SqlParameter("@id", id); //Debug.WriteLine(query); db.Database.ExecuteSqlCommand(query, parameters); return RedirectToAction("List"); } catch { //Get Bad Request if Sql got error return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } //Use to apply also on the other view //[Authorize] public ActionResult Delete(int? id) { if (id == null) { //If no id value has been presented, will return a BadRequest return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Volunteer selectedvolunteer = db.Volunteers.SqlQuery("Select * from Volunteers where VolunteerID = @id", new SqlParameter("@id", id)).First(); if (selectedvolunteer == null) { //If value is null on selectedvolunteer, no value on the database return HttpNotFound(); } return View(selectedvolunteer); } [HttpPost] public ActionResult Delete(int id) { try { //query for deleting Volunteer string query = "DELETE from Volunteers where VolunteerID= @id"; //Debug.WriteLine(query); SqlParameter parameters = new SqlParameter("@id", id); //Run the sql command db.Database.ExecuteSqlCommand(query, parameters); return RedirectToAction("List"); } catch { //Get Bad Request if Sql got error return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } public ActionResult Apply_today() { return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class Speciality { //This class has id & name. I also need to represent the doctors table to depict the "Many" in One speciality to many doctors. [Key] public int SpecialityID { get; set; } public string Name { get; set; } //now the "Many" in one speciality to many doctors. public ICollection<Doctor> Doctors { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models.ViewModels { public class UpdateDoctor { /*While updating a doctor we need to update details of doctor and also the speciality*/ public Doctor doctor { get; set; } public List<Speciality> specialities { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class Survey { /*this class will have * response_id * response_text * question_id*/ [Key] public int ResponseID { get; set; } public string ResponseText { get; set; } public string UserName { get; set; } //Now I need to reference the question id public int QuestionID { get; set; } [ForeignKey("QuestionID")] public virtual Question Questions { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models { public class Job { /* Description about Job * * JobID - Job Identity * JobTitle - Job Title * JobCategory - Category of the job * JobType - job type such as partimr or full time * Description - Job Description * Requirements - Job Requirements * PostDate - Job post date */ [Key] public int JobID { get; set; } public string JobTitle { get; set; } public string JobCategory { get; set; } public string JobType { get; set; } public string Description { get; set; } public string Requirements { get; set; } public DateTime PostDate { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; //sql Parameteres using System.Data.SqlClient; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using System.Diagnostics; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; namespace HumberAreaHospitalProject.Controllers { public class SocialServiceClubsController : Controller { // GET: SocialServiceClubs //db context private HospitalContext db = new HospitalContext(); // GET: SocialServiceClubs public ActionResult List(string sscsearchkey, int pagenum = 0) { //can we access the search key? //Debug.WriteLine("The search key is "+sscsearchkey); string query = "Select * from SocialServiceClubs"; //order by is needed for offset //easier in a list.. we don't know how many more we'll add yet List<SqlParameter> sqlparams = new List<SqlParameter>(); if (sscsearchkey != "") { //modify the query to include the search key query = query + " where SocialServiceClubs_title like @searchkey or SocialServiceClubs_details like @searchkey"; sqlparams.Add(new SqlParameter("@searchkey", "%" + sscsearchkey + "%")); //Debug.WriteLine("The query is "+ query); } List<SocialServiceClubs> ssc = db.SocialServiceClubs.SqlQuery(query, sqlparams.ToArray()).ToList(); //Start of Pagination Algorithm (Raw MSSQL) int perpage = 3; int remcount = ssc.Count(); int maxpage = (int)Math.Ceiling((decimal)remcount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) pagenum = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); List<SqlParameter> newparams = new List<SqlParameter>(); if (sscsearchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + sscsearchkey + "%")); ViewData["sscsearchkey"] = sscsearchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by SocialServiceClubs_id offset @start rows fetch first @perpage rows only "; Debug.WriteLine(pagedquery); Debug.WriteLine("offset " + start); Debug.WriteLine("fetch first " + perpage); ssc = db.SocialServiceClubs.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } //End of Pagination Algorithm return View(ssc); } public ActionResult User_list(string sscsearchkey, int pagenum = 0) { //can we access the search key? //Debug.WriteLine("The search key is "+sscsearchkey); string query = "Select * from SocialServiceClubs"; //order by is needed for offset //easier in a list.. we don't know how many more we'll add yet List<SqlParameter> sqlparams = new List<SqlParameter>(); if (sscsearchkey != "") { //modify the query to include the search key query = query + " where SocialServiceClubs_title like @searchkey or SocialServiceClubs_details like @searchkey"; sqlparams.Add(new SqlParameter("@searchkey", "%" + sscsearchkey + "%")); //Debug.WriteLine("The query is "+ query); } List<SocialServiceClubs> ssc = db.SocialServiceClubs.SqlQuery(query, sqlparams.ToArray()).ToList(); //Start of Pagination Algorithm (Raw MSSQL) int perpage = 3; int remcount = ssc.Count(); int maxpage = (int)Math.Ceiling((decimal)remcount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) pagenum = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); List<SqlParameter> newparams = new List<SqlParameter>(); if (sscsearchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + sscsearchkey + "%")); ViewData["sscsearchkey"] = sscsearchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by SocialServiceClubs_id offset @start rows fetch first @perpage rows only "; Debug.WriteLine(pagedquery); Debug.WriteLine("offset " + start); Debug.WriteLine("fetch first " + perpage); ssc = db.SocialServiceClubs.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } //End of Pagination Algorithm return View(ssc); } /*public ActionResult List() { string query = "Select * from SocialServiceClubs"; List<SocialServiceClubs> SocialServiceClubs = db.SocialServiceClubs.SqlQuery(query).ToList(); return View(SocialServiceClubs); }*/ public ActionResult New() { //add new remedy return View(); } [HttpPost] public ActionResult New(string SocialServiceClubs_title, string SocialServiceClubs_details, string SocialServiceClubs_address, string SocialServiceClubs_map, string SocialServiceClubs_website) { //add social service clubs string query = "insert into SocialServiceClubs (SocialServiceClubs_title, SocialServiceClubs_details, SocialServiceClubs_address, SocialServiceClubs_map, SocialServiceClubs_website) values(@SocialServiceClubs_title,@SocialServiceClubs_details,@SocialServiceClubs_address, @SocialServiceClubs_map,@SocialServiceClubs_website)"; SqlParameter[] sqlparams = new SqlParameter[5]; sqlparams[0] = new SqlParameter("@SocialServiceClubs_title", SocialServiceClubs_title); sqlparams[1] = new SqlParameter("@SocialServiceClubs_details", SocialServiceClubs_details); sqlparams[2] = new SqlParameter("@SocialServiceClubs_address", SocialServiceClubs_address); sqlparams[3] = new SqlParameter("@SocialServiceClubs_map", SocialServiceClubs_address); sqlparams[4] = new SqlParameter("@SocialServiceClubs_website", SocialServiceClubs_website); db.Database.ExecuteSqlCommand(query, sqlparams); return RedirectToAction("List"); } public ActionResult Update(int id) { //fetch existed details of the remedy string query = "select * from SocialServiceClubs where SocialServiceClubs_id = @id"; var parameter = new SqlParameter("@id", id); SocialServiceClubs selectedSocialServiceClub = db.SocialServiceClubs.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedSocialServiceClub); } //update existed details [HttpPost] public ActionResult Update(int id, string SocialServiceClubs_title, string SocialServiceClubs_details, string SocialServiceClubs_address, string SocialServiceClubs_map, string SocialServiceClubs_website) { //Debug.WriteLine("selected club is" + id); string query = "Update SocialServiceClubs set SocialServiceClubs_title=@SocialServiceClubs_title, SocialServiceClubs_details=@SocialServiceClubs_details, SocialServiceClubs_address=@SocialServiceClubs_address,SocialServiceClubs_map=@SocialServiceClubs_map,SocialServiceClubs_website=@SocialServiceClubs_website where SocialServiceClubs_id=@id"; SqlParameter[] sqlparams = new SqlParameter[6]; sqlparams[0] = new SqlParameter("@SocialServiceClubs_title", SocialServiceClubs_title); sqlparams[1] = new SqlParameter("@SocialServiceClubs_details", SocialServiceClubs_details); sqlparams[2] = new SqlParameter("@SocialServiceClubs_address", SocialServiceClubs_address); sqlparams[3] = new SqlParameter("@SocialServiceClubs_map", SocialServiceClubs_map); sqlparams[4] = new SqlParameter("@SocialServiceClubs_website", SocialServiceClubs_website); sqlparams[5] = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, sqlparams); return RedirectToAction("List"); } public ActionResult View(int id) { string query = "Select * from SocialServiceClubs where SocialServiceClubs_id=@id"; var parameter = new SqlParameter("@id", id); SocialServiceClubs selectedSocialServiceClub = db.SocialServiceClubs.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedSocialServiceClub); } public ActionResult User_view(int id) { string query = "Select * from SocialServiceClubs where SocialServiceClubs_id=@id"; var parameter = new SqlParameter("@id", id); SocialServiceClubs selectedSocialServiceClub = db.SocialServiceClubs.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedSocialServiceClub); } public ActionResult Delete(int id) { string query = "Select * from SocialServiceClubs where SocialServiceClubs_id=@id"; var parameter = new SqlParameter("@id", id); SocialServiceClubs selectedSocialServiceClub = db.SocialServiceClubs.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedSocialServiceClub); } [HttpPost] public ActionResult Delete(int? id) { string query = "Delete from SocialServiceClubs where SocialServiceClubs_id=@id"; var parameter = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, parameter); return RedirectToAction("List"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class Article { [Key] public int ArticleID { get; set; } public string ArticleTitle { get; set; } public string ArticleBody { get; set; } public DateTime Published { get; set; } //Featured is YES or NO public string Featured { get; set; } //Reference of Author Id as a Foreign key //Representing the "One" in (Many Articles to One Author) public int AuthorID { get; set; } [ForeignKey("AuthorID")] public virtual Author Authors { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using System.Diagnostics; using System.IO; using Microsoft.AspNet.Identity; using ApplicationUser = HumberAreaHospitalProject.Data.ApplicationUser; namespace HumberAreaHospitalProject.Controllers { public class SpecialityController : Controller { //create db context private HospitalContext db = new HospitalContext(); // GET: Speciality [Authorize] public ActionResult List() { //Method to list all specialities Debug.WriteLine("Trying to list all the records"); string query = "Select * from specialities"; List<Speciality> specialities = db.Specialities.SqlQuery(query).ToList(); return View(specialities); } [Authorize] public ActionResult New() { //Method to add a new speciality string currentUserId = User.Identity.GetUserId(); ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId); Debug.WriteLine("The current userid is " + currentUserId); var a = User.Identity.GetUserName(); Debug.WriteLine("The current userid is " + a); //This method only needs the add page, Nothing from the db return View(); } [HttpPost] public ActionResult New(string SpecialityName) { /*This method takes in a new speciality name and writes it to the DB*/ string query = "insert into specialities (Name) values(@SpecialityName)"; SqlParameter parameter = new SqlParameter("@SpecialityName", SpecialityName); db.Database.ExecuteSqlCommand(query, parameter); return RedirectToAction("List"); } [Authorize] public ActionResult Update(int id) { /*this method will show the base info of the selected record*/ Debug.WriteLine("I am trying to update record with id" + id); string query = "select * from specialities where specialityid = @id"; SqlParameter parameter = new SqlParameter("@id", id); Speciality selectedspeciality = db.Specialities.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedspeciality); } //now the post method when the user clicks on update [HttpPost] public ActionResult Update(int id, string SpecialityName) { Debug.WriteLine("I am trying to update record with id" + id); string query = "Update specialities set Name=@SpecialityName where specialityid=@id"; SqlParameter[] parameters = new SqlParameter[2]; parameters[0] = new SqlParameter("@SpecialityName", SpecialityName); parameters[1] = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, parameters); return RedirectToAction("List"); } [Authorize] public ActionResult View(int id) { //View a particluar record string query = "Select * from specialities where specialityid=@id"; SqlParameter parameter = new SqlParameter("@id", id); Speciality selectedspeciality = db.Specialities.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedspeciality); } [Authorize] public ActionResult Delete(int id) { //base info for a particular record string query = "Select * from specialities where specialityid=@id"; SqlParameter parameter = new SqlParameter("@id", id); Speciality selectedspeciality = db.Specialities.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedspeciality); } [HttpPost] public ActionResult Delete(int? id) { //Method to delete a record string query = "Delete from specialities where specialityid=@id"; SqlParameter parameter = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, parameter); return RedirectToAction("List"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class Author { [Key] public int AuthorID { get; set; } public string AuthorFname { get; set; } public string AuthorLname { get; set; } public string Email { get; set; } public string Phone { get; set; } //Representing the "Many" in (One Author to many Articles) public ICollection<Article> Articles { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace HumberAreaHospitalProject.Models.ViewModels { public class UpdateFAQController { public FAQ FAQ { get; set; } public List<FAQCategory> FAQCategory { get; set; } } }<file_sep>namespace HumberAreaHospitalProject.Migrations { using System; using System.Data.Entity.Migrations; public partial class updated_FAQ_Removed : DbMigration { public override void Up() { DropColumn("dbo.FAQs", "FAQLikes"); } public override void Down() { AddColumn("dbo.FAQs", "FAQLikes", c => c.Int(nullable: false)); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; //sql Parameteres using System.Data.SqlClient; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using System.Diagnostics; namespace HumberAreaHospitalProject.Controllers { public class RemedySourceController : Controller { //db context private HospitalContext db = new HospitalContext(); // GET: RemedySource public ActionResult List(string remedysrcsearchkey, int pagenum = 0) { //can we access the search key? //Debug.WriteLine("The search key is "+remedysrcsearchkey); string query = "Select * from RemedySources"; List<SqlParameter> sqlparams = new List<SqlParameter>(); if (remedysrcsearchkey != "") { //modify the query to include the search key query = query + " where RemedySource_name like @searchkey or RemedySource_url like @searchkey"; sqlparams.Add(new SqlParameter("@searchkey", "%" + remedysrcsearchkey + "%")); //Debug.WriteLine("The query is "+ query); } List<RemedySource> remedysrc = db.RemedySource.SqlQuery(query, sqlparams.ToArray()).ToList(); //Start of Pagination Algorithm (Raw MSSQL) int perpage = 3; int remsrccount = remedysrc.Count(); int maxpage = (int)Math.Ceiling((decimal)remsrccount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) pagenum = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); List<SqlParameter> newparams = new List<SqlParameter>(); if (remedysrcsearchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + remedysrcsearchkey + "%")); ViewData["remedysrcsearchkey"] = remedysrcsearchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by RemedySource_id offset @start rows fetch first @perpage rows only "; Debug.WriteLine(pagedquery); Debug.WriteLine("offset " + start); Debug.WriteLine("fetch first " + perpage); remedysrc = db.RemedySource.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } //End of Pagination Algorithm return View(remedysrc); } public ActionResult New() { //add new remedy src return View(); } [HttpPost] public ActionResult New(string RemedySource_name, string RemedySource_url) { //add remedy src string query = "insert into RemedySources (RemedySource_name, RemedySource_url) values(@RemedySource_name,@RemedySource_url)"; SqlParameter[] sqlparams = new SqlParameter[2]; sqlparams[0] = new SqlParameter("@RemedySource_name", RemedySource_name); sqlparams[1] = new SqlParameter("@RemedySource_url", RemedySource_url); db.Database.ExecuteSqlCommand(query, sqlparams); return RedirectToAction("List"); } public ActionResult Update(int id) { //fetch existed details of the remedy srcs string query = "select * from RemedySources where RemedySource_id = @id"; var parameter = new SqlParameter("@id", id); RemedySource selectedRemedysrc = db.RemedySource.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedRemedysrc); } //update existed details [HttpPost] public ActionResult Update(int id, string RemedySource_name, string RemedySource_url) { //Debug.WriteLine("selected remedysrc is" + id); string query = "Update RemedySources set RemedySource_name=@RemedySource_name, RemedySource_url=@RemedySource_url where RemedySource_id=@id"; SqlParameter[] sqlparams = new SqlParameter[3]; sqlparams[0] = new SqlParameter("@RemedySource_name", RemedySource_name); sqlparams[1] = new SqlParameter("@RemedySource_url", RemedySource_url); sqlparams[2] = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, sqlparams); return RedirectToAction("List"); } public ActionResult View(int id) { string query = "Select * from RemedySources where RemedySource_id=@id"; var parameter = new SqlParameter("@id", id); RemedySource selectedRemedysrc = db.RemedySource.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedRemedysrc); } public ActionResult Delete(int id) { string query = "Select * from RemedySources where RemedySource_id=@id"; var parameter = new SqlParameter("@id", id); RemedySource selectedRemedysrc = db.RemedySource.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedRemedysrc); } [HttpPost] public ActionResult Delete(int? id) { string query = "Delete from RemedySources where RemedySource_id=@id"; var parameter = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, parameter); return RedirectToAction("List"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models.ViewModels { public class StaffSpecialty { public virtual Staff staff { get; set; } public virtual List<Speciality> Specialities { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using HumberAreaHospitalProject.Models.ViewModels; using System.Diagnostics; using System.IO; using Microsoft.AspNet.Identity; using PagedList; namespace HumberAreaHospitalProject.Controllers { public class DoctorController : Controller { //create db context private HospitalContext db = new HospitalContext(); // GET: Doctor [Authorize] public ActionResult List(string searchBy, string search, int? page) {//This method is used to list all the doctors and has the search and pagination functionality if (searchBy == "First Name") { return View(db.Doctors.Where(x => x.DoctorFname.Contains(search) || search == null).ToList().ToPagedList(page ?? 1, 3)); } else if(searchBy=="Last Name") { return View(db.Doctors.Where(x => x.DoctorLname.Contains(search) || search == null).ToList().ToPagedList(page ?? 1, 3)); } else { return View(db.Doctors.Where(x => x.Specialities.Name.Contains(search) || search == null).ToList().ToPagedList(page ?? 1, 3)); } } [Authorize] public ActionResult New() { //This method needs the list of specialities string query = "Select * from specialities"; List<Speciality> specialities = db.Specialities.SqlQuery(query).ToList(); return View(specialities); } [HttpPost] public ActionResult New(string doctortitle, string doctorfname, string doctorlname, string speciality) { //This method add the new doctor to the DB string query = "insert into doctors (Title, DoctorFname, DoctorLname,SpecialityID) values(@doctortitle, @doctorfname, @doctorlname,@speciality)"; SqlParameter[] parameters = new SqlParameter[4]; parameters[0] = new SqlParameter("@doctortitle", doctortitle); parameters[1] = new SqlParameter("@doctorfname", doctorfname); parameters[2] = new SqlParameter("@doctorlname", doctorlname); parameters[3] = new SqlParameter("@speciality", speciality); db.Database.ExecuteSqlCommand(query, parameters); Debug.WriteLine("The new record being added has firstname:" + doctorfname); return RedirectToAction("List"); } [Authorize] public ActionResult View(int id) { //This method will use a viewmodel. It needs a particular doctor and list of similar doctors. Debug.WriteLine("I am trying to view record of doctor having id:" + id); string query = "Select * from doctors where DoctorID=@id"; SqlParameter parameter = new SqlParameter("@id", id); Doctor selecteddoctor = db.Doctors.SqlQuery(query, parameter).FirstOrDefault(); var speciality = selecteddoctor.SpecialityID; string secondquery = "Select * from doctors where doctorid!=@id and Doctors.SpecialityID=@speciality"; SqlParameter[] parameters = new SqlParameter[2]; parameters[0] = new SqlParameter("@id", id); parameters[1] = new SqlParameter("@speciality", speciality); List<Doctor> similardoctors = db.Doctors.SqlQuery(secondquery, parameters).ToList(); var ViewDoctor = new ViewDoctor(); ViewDoctor.doctor = selecteddoctor; ViewDoctor.similardoctors = similardoctors; return View(ViewDoctor); /*Select * from doctors where doctorid!=1 and Doctors.SpecialityID=1*/ } [Authorize] public ActionResult Update(int id) { /*this method is used to show the base info of an individual doctor and also gives the user to select a speciality. Hence, We need a ViewModel*/ string query = "Select * from doctors where DoctorID=@id"; SqlParameter parameter = new SqlParameter("@id", id); Doctor selecteddoctor = db.Doctors.SqlQuery(query, parameter).FirstOrDefault(); string secondquery = "Select * from specialities"; List<Speciality> selectedspeciality = db.Specialities.SqlQuery(secondquery).ToList(); var UpdateDoctor = new UpdateDoctor(); UpdateDoctor.doctor = selecteddoctor; UpdateDoctor.specialities = selectedspeciality; return View(UpdateDoctor); } [HttpPost] public ActionResult Update(int id, string Title, string DoctorFname, string DoctorLname, string SpecialityID) { //Method to be used once the user clicks update string query = "Update doctors set Title=@Title, DoctorFname=@DoctorFname, DoctorLname=@DoctorLname, SpecialityID=@SpecialityID where DoctorID=@id"; SqlParameter[] parameters = new SqlParameter[5]; parameters[0] = new SqlParameter("@Title", Title); parameters[1] = new SqlParameter("@DoctorFname", DoctorFname); parameters[2] = new SqlParameter("@DoctorLname", DoctorLname); parameters[3] = new SqlParameter("@SpecialityID", SpecialityID); parameters[4] = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, parameters); Debug.WriteLine("The record being updated has firstname:" + DoctorFname); return RedirectToAction("List"); } [Authorize] public ActionResult Delete(int id) { //To show base info of a doctor Debug.WriteLine("I am trying to view record of doctor having id:" + id); string query = "Select * from doctors where DoctorID=@id"; SqlParameter parameter = new SqlParameter("@id", id); Doctor selecteddoctor = db.Doctors.SqlQuery(query, parameter).FirstOrDefault(); return View(selecteddoctor); } [HttpPost] public ActionResult Delete(int? id) { //to be executed once the user clicks delete string query = "Delete from doctors where DoctorID=@id"; SqlParameter parameter = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, parameter); Debug.WriteLine("The record being deleted has an id of:" + id); return RedirectToAction("List"); } } }<file_sep>namespace HumberAreaHospitalProject.Migrations { using System; using System.Data.Entity.Migrations; public partial class Appointment_Staff : DbMigration { public override void Up() { CreateTable( "dbo.Appointments", c => new { appointmentId = c.Int(nullable: false, identity: true), appointmentFname = c.String(), appointmentLname = c.String(), appointmentPhone = c.String(), appointmentEmail = c.String(), appointmentDate = c.DateTime(nullable: false), DoctorID = c.Int(nullable: false), }) .PrimaryKey(t => t.appointmentId) .ForeignKey("dbo.Doctors", t => t.DoctorID, cascadeDelete: true) .Index(t => t.DoctorID); CreateTable( "dbo.Staffs", c => new { staffId = c.Int(nullable: false, identity: true), staffFname = c.String(), staffLname = c.String(), staffEmail = c.String(), staffExt = c.String(), SpecialtyID = c.Int(nullable: false), }) .PrimaryKey(t => t.staffId) .ForeignKey("dbo.Specialities", t => t.SpecialtyID, cascadeDelete: true) .Index(t => t.SpecialtyID); } public override void Down() { DropForeignKey("dbo.Staffs", "SpecialtyID", "dbo.Specialities"); DropForeignKey("dbo.Appointments", "DoctorID", "dbo.Doctors"); DropIndex("dbo.Staffs", new[] { "SpecialtyID" }); DropIndex("dbo.Appointments", new[] { "DoctorID" }); DropTable("dbo.Staffs"); DropTable("dbo.Appointments"); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using HumberAreaHospitalProject.Models.ViewModels; using System.Diagnostics; using System.IO; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; namespace HumberAreaHospitalProject.Controllers { public class AppointmentController : Controller { private HospitalContext db = new HospitalContext(); //Viewing appointments //pagination method from <NAME> //search method from <NAME> public ActionResult List(string appointmentSearchKey, int pagenum = 0) { //checking if the users logged in if((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { List<Appointment> appointments = db.Appointments.Where(a => (appointmentSearchKey != null) ? a.appointmentLname.Contains(appointmentSearchKey) : true).ToList(); int perpage = 8; int appointmentCount = appointments.Count(); int maxpage = (int)Math.Ceiling((decimal)appointmentCount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) perpage = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); appointments = db.Appointments .Where(a => (appointmentSearchKey != null) ? a.appointmentLname.Contains(appointmentSearchKey) : true) .OrderBy(a => a.appointmentId) .Skip(start) .Take(perpage) .ToList(); } return View(appointments); } else //if not sends to login page { return RedirectToAction("Login","Account"); } } //Adding an appointment public ActionResult Create() { //checks if user is logged in if ((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { AppointmentViewModel appointmentViewModel = new AppointmentViewModel(); appointmentViewModel.doctors = db.Doctors.ToList(); //using a view model to also show doctors return View(appointmentViewModel); } else { return RedirectToAction("index"); } } //sends added appointment [HttpPost] public ActionResult Create(string firstName, string lastName, string phoneNum, string email, DateTime dateTime, int doctorID) { string query = "insert into appointments (appointmentFname, appointmentLname, appointmentPhone, appointmentEmail, appointmentDate, DoctorID)" + "values (@appointmentFname, @appointmentLname, @appointmentPhone, @appointmentEmail, @appointmentDate, @DoctorID)"; SqlParameter[] sqlParameters = new SqlParameter[6]; sqlParameters[0] = new SqlParameter("@appointmentFname", firstName); sqlParameters[1] = new SqlParameter("@appointmentLname", lastName); sqlParameters[2] = new SqlParameter("@appointmentPhone", phoneNum); sqlParameters[3] = new SqlParameter("@appointmentEmail", email); sqlParameters[4] = new SqlParameter("@appointmentDate", dateTime); sqlParameters[5] = new SqlParameter("@DoctorID", doctorID); db.Database.ExecuteSqlCommand(query, sqlParameters); return RedirectToAction("List"); } //selects appointment to update public ActionResult Update(int id) { //checks if logged in if((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { string query = "select * from appointments where appointmentID = @id"; var Parameter = new SqlParameter("@id", id); Appointment appointment = db.Appointments.SqlQuery(query, Parameter).FirstOrDefault(); AppointmentViewModel appointmentViewModel = new AppointmentViewModel(); appointmentViewModel.appointment = appointment; appointmentViewModel.doctors = db.Doctors.ToList(); //using a view model to also show doctors return View(appointmentViewModel); } else { return RedirectToAction("index"); } } //sends update [HttpPost] public ActionResult Update(int id, string firstName, string lastName, string phoneNum, string email, DateTime dateTime, int doctorID) { string query = "update appointments set appointmentFname = @firstName, appointmentLname = @lastName, appointmentPhone = @phoneNum, appointmentEmail = @email, appointmentDate = @dateTime, DoctorID = @doctorID where appointmentID = @id"; SqlParameter[] sqlParameters = new SqlParameter[7]; sqlParameters[0] = new SqlParameter("@firstName", firstName); sqlParameters[1] = new SqlParameter("@lastName", lastName); sqlParameters[2] = new SqlParameter("@phoneNum", phoneNum); sqlParameters[3] = new SqlParameter("@email", email); sqlParameters[4] = new SqlParameter("@dateTime", dateTime); sqlParameters[5] = new SqlParameter("@doctorID", doctorID); sqlParameters[6] = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, sqlParameters); return RedirectToAction("List"); } //confirms delete public ActionResult Delete(int id) { if ((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { string query = "select * from appointments where appointmentID = @id"; var Parameter = new SqlParameter("@id", id); Appointment appointment = db.Appointments.SqlQuery(query, Parameter).FirstOrDefault(); return View(appointment); } else { return RedirectToAction("index"); } } //deletes an appointment [HttpPost] public ActionResult DeleteApp(int id) { string query = "delete from appointments where appointmentID = @id"; var Parameter = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, Parameter); return RedirectToAction("List"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models { public class FAQCategory { [Key] public int FAQCategoryID { get; set; } public string FAQCategoryName { get; set; } //Name of the category } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using HumberAreaHospitalProject.Models.ViewModels; using System.Diagnostics; using System.IO; using Microsoft.AspNet.Identity; using ApplicationUser = HumberAreaHospitalProject.Data.ApplicationUser; namespace HumberAreaHospitalProject.Controllers { public class SurveyController : Controller { private HospitalContext db = new HospitalContext(); // GET: Response [Authorize] public ActionResult Form() { Debug.WriteLine("Trying to list all the records"); string query = "Select * from questions"; List<Question> questions = db.Questions.SqlQuery(query).ToList(); return View(questions); } [HttpPost] public ActionResult Form (ICollection <string> ResponseText, ICollection<int> Count) { //string currentUserId = User.Identity.GetUserId(); //ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId); //Debug.WriteLine("The current userid is " + currentUserId); string username = User.Identity.GetUserName(); Debug.WriteLine("The username is " + username); var result = ResponseText.Zip(Count, (r, q) => new { Response=r, Question=q}); foreach (var rq in result) { string query = "Insert into surveys (ResponseText,QuestionID,UserName) values(@ResponseText,@id,@UserName)"; SqlParameter[] parameters = new SqlParameter[3]; parameters[0] = new SqlParameter("@ResponseText", rq.Response); parameters[1] = new SqlParameter("@id", rq.Question); parameters[2] = new SqlParameter("@UserName", username); db.Database.ExecuteSqlCommand(query, parameters); } return RedirectToAction("Thanks"); } [Authorize] public ActionResult Thanks() { return View(); } [Authorize] public ActionResult List() { ListSurvey question = new ListSurvey(); question.questions = db.Questions.ToList(); question.surveys = db.Surveys.ToList(); return View(question); //return View(); } [HttpPost] public ActionResult List(string id) { string basequery = "Select * from questions"; List<Question> questions = db.Questions.SqlQuery(basequery).ToList(); string query = "Select * from surveys where questionid=@id"; SqlParameter parameter = new SqlParameter("@id", id); List<Survey> answers = db.Surveys.SqlQuery(query, parameter).ToList(); var ListSurvey = new ListSurvey(); ListSurvey.surveys = answers; ListSurvey.questions = questions; return View(ListSurvey); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models.ViewModels { public class ViewDoctor { public virtual Doctor doctor { get; set; } public List<Doctor> similardoctors { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using HumberAreaHospitalProject.Models; using System.Data.Entity; using HumberAreaHospitalProject.Data; using System.Diagnostics; using HumberAreaHospitalProject.Models.ViewModels; namespace HumberAreaHospitalProject.Controllers { public class JobController : Controller { private HospitalContext db = new HospitalContext(); // GET: Job Admin perspective where admin gets to see the edit update and delete buttons public ActionResult List(String jobsearchkey, int pagenum=0) { string query = "select * from Jobs";//SQL query to select everything from Jobs table List<SqlParameter> sqlparams = new List<SqlParameter>(); if (jobsearchkey!= "") //Checkign if the search key is empty or null { query = query + " where JobTitle like @searchkey";//Appending sql query to existing query sqlparams.Add(new SqlParameter("@searchkey", "%" + jobsearchkey + "%")); } List<Job> jobs = db.Jobs.SqlQuery(query, sqlparams.ToArray()).ToList(); //Pagination for jobs int perpage = 5; int petcount = jobs.Count(); int maxpage = (int)Math.Ceiling((decimal)petcount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) pagenum = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); List<SqlParameter> newparams = new List<SqlParameter>(); if (jobsearchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + jobsearchkey + "%")); ViewData["jobsearchkey"] = jobsearchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by JobID offset @start rows fetch first @perpage rows only "; jobs = db.Jobs.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } //End of Pagination return View(jobs); } //Add new job to the table [HttpPost] public ActionResult New(string JobTitle, string JobCategory, string JobType, string Description, string Requirements) { DateTime now = DateTime.Now; DateTime PostDate = now; string query = "insert into Jobs (JobTitle, JobCategory, JobType, Description, Requirements, PostDate) values (@JobTitle, @JobCategory, @JobType, @Description, @Requirements, @PostDate)"; SqlParameter[] sqlparams = new SqlParameter[6]; sqlparams[0] = new SqlParameter("@JobTitle", JobTitle); sqlparams[1] = new SqlParameter("@JobCategory", JobCategory); sqlparams[2] = new SqlParameter("@JobType", JobType); sqlparams[3] = new SqlParameter("@Description", Description); sqlparams[4] = new SqlParameter("@Requirements", Requirements); sqlparams[5] = new SqlParameter("@PostDate", PostDate); db.Database.ExecuteSqlCommand(query, sqlparams); return RedirectToAction("List"); } public ActionResult New() { return View(); } //Display individual job details public ActionResult Show(int? id) { Job job = db.Jobs.SqlQuery("Select * from Jobs Where JobID=@JobID", new SqlParameter("@JobID", id)).FirstOrDefault(); string query = "select * from Applications where JobID = @id"; SqlParameter parameter = new SqlParameter("@id", id); List<Application> applications = db.Applications.SqlQuery(query, parameter).ToList(); ShowJob ViewModel = new ShowJob(); ViewModel.Job = job; ViewModel.Applications = applications; return View(ViewModel); } //Update public ActionResult Update(int id) { //need information about a particular job Job selectedjob = db.Jobs.SqlQuery("select * from Jobs where JobID = @id", new SqlParameter("@id", id)).FirstOrDefault(); //string query = "select * from Jobs"; return View(selectedjob); } //[HttpPost] Update [HttpPost] public ActionResult Update(int id, string JobTitle, string JobCategory, string JobType, string Description, string Requirements) { //query to update jobs string query = "update Jobs set JobTitle =@JobTitle, JobCategory=@JobCategory, JobType=@JobType, Description=@Description, Requirements=@Requirements where JobID=@id"; //key pair values to hold new values SqlParameter[] sqlparams = new SqlParameter[6]; sqlparams[0] = new SqlParameter("@JobTitle", JobTitle); sqlparams[1] = new SqlParameter("@JobCategory", JobCategory); sqlparams[2] = new SqlParameter("@JobType", JobType); sqlparams[3] = new SqlParameter("@Description", Description); sqlparams[4] = new SqlParameter("@Requirements", Requirements); sqlparams[5] = new SqlParameter("@id", id); //Exceuting the sql query with new values db.Database.ExecuteSqlCommand(query, sqlparams); //Return to list view of Jobd return RedirectToAction("List"); } //Deletion of job public ActionResult Delete(int id) { //Query to delete particualr job from the table based on the jobID string query = "delete from Jobs where JobID=@id"; SqlParameter[] parameter = new SqlParameter[1]; //storing the id of the job to be deleted parameter[0] = new SqlParameter("@id", id); //Excecuting the query db.Database.ExecuteSqlCommand(query, parameter); // returning to lsit view of the jobs after deleting return RedirectToAction("List"); } // GET: Job and display in users persepective where all the buttons will be removed so the user is restriceted to only see aand apply for the job public ActionResult User_Perspective_List(String jobsearchkey, int pagenum = 0) { string query = "select * from Jobs";//SQL query to select everything from Jobs table List<SqlParameter> sqlparams = new List<SqlParameter>(); if (jobsearchkey != "") //Checkign if the search key is empty or null { query = query + " where JobTitle like @searchkey";//Appending sql query to existing query sqlparams.Add(new SqlParameter("@searchkey", "%" + jobsearchkey + "%")); } List<Job> jobs = db.Jobs.SqlQuery(query, sqlparams.ToArray()).ToList(); //Pagination for jobs int perpage = 5; int petcount = jobs.Count(); int maxpage = (int)Math.Ceiling((decimal)petcount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) pagenum = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); List<SqlParameter> newparams = new List<SqlParameter>(); if (jobsearchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + jobsearchkey + "%")); ViewData["jobsearchkey"] = jobsearchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by JobID offset @start rows fetch first @perpage rows only "; jobs = db.Jobs.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } //End of Pagination return View(jobs); } //Function to Display individual user perspective of job details public ActionResult User_Show(int id) { string query = "select * from Jobs where JobID = @JobID"; //sql query to slect all fromJobs table based on JobID var parameter = new SqlParameter("@JobID", id); Job jobs = db.Jobs.SqlQuery(query, parameter).FirstOrDefault(); return View(jobs); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models.ViewModels { public class UpdateHomeRemedy { public HomeRemedies HomeRemedies { get; set; } public List<RemedySource> RemedySources { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using HumberAreaHospitalProject.Models; using System.Data.Entity; using HumberAreaHospitalProject.Data; using System.Diagnostics; namespace HumberAreaHospitalProject.Controllers { public class FAQCategoryController : Controller { private HospitalContext db = new HospitalContext(); // GET: FAQCategory public ActionResult List() { List<FAQCategory> FAQCategories = db.FAQCategories.SqlQuery("Select * from FAQCategories").ToList(); return View(FAQCategories); } //Add Category public ActionResult New() { return View(); } // [HttpPost] Add [HttpPost] public ActionResult New(String FAQCategoryName) { //query to add new Make into the make table string query = "insert into FAQCategories (FAQCategoryName) values (@Name)"; SqlParameter parameter = new SqlParameter("@Name", FAQCategoryName); db.Database.ExecuteSqlCommand(query, parameter); return RedirectToAction("List"); } // [HttpPost] Update public ActionResult Update(int id) { string query = "Select * from FAQCategories where FAQCategoryID=@id"; SqlParameter parameter = new SqlParameter("@id", id); FAQCategory selectedCategory = db.FAQCategories.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedCategory); } [HttpPost] public ActionResult Update(int id, String FAQCategoryName) { //query to update the particualar category based on the id string query = "update FAQCategories set FAQCategoryName=@Name where FAQCategoryID=@id"; //key pair values to store Make details SqlParameter[] parameter = new SqlParameter[2]; parameter[0] = new SqlParameter("@Name", FAQCategoryName); parameter[1] = new SqlParameter("@id", id); //excecuting the query to update db.Database.ExecuteSqlCommand(query, parameter); //retunring to list view of the categories after adding return RedirectToAction("List"); } //show Category public ActionResult Show(int? id) { FAQCategory category = db.FAQCategories.SqlQuery("select * from FAQCategories where FAQCategoryID=@categoryID", new SqlParameter("@categoryID", id)).FirstOrDefault(); if (category == null) { return HttpNotFound(); } //returning individual Category return View(category); } //delete public ActionResult Delete(int id) { //Query to delete particualr category from the table based on the category id string query = "delete from FAQCategories where FAQCategoryID=@id"; SqlParameter[] parameter = new SqlParameter[1]; //storing the id of the category to be deleted parameter[0] = new SqlParameter("@id", id); //Excecuting the query db.Database.ExecuteSqlCommand(query, parameter); // returning to lsit view of the categories after deleting return RedirectToAction("List"); } } }<file_sep>namespace HumberAreaHospitalProject.Migrations { using System; using System.Data.Entity.Migrations; public partial class addsocialserviceclubs : DbMigration { public override void Up() { CreateTable( "dbo.SocialServiceClubs", c => new { SocialServiceClubs_id = c.Int(nullable: false, identity: true), SocialServiceClubs_title = c.String(), SocialServiceClubs_details = c.String(), SocialServiceClubs_address = c.String(), SocialServiceClubs_map = c.String(), SocialServiceClubs_website = c.String(), }) .PrimaryKey(t => t.SocialServiceClubs_id); } public override void Down() { DropTable("dbo.SocialServiceClubs"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class RemedySource { [Key] public int RemedySource_id { get; set; } public string RemedySource_name { get; set; } public string RemedySource_url { get; set; } public ICollection<HomeRemedies> Remedies { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using HumberAreaHospitalProject.Models; namespace HumberAreaHospitalProject.Data { public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } public class HospitalContext : IdentityDbContext<ApplicationUser> { public HospitalContext() : base("name=HospitalContext") { } public static HospitalContext Create() { return new HospitalContext(); } //Anshuk Start public DbSet<Doctor> Doctors { get; set; } public DbSet<Speciality> Specialities { get; set; } //Madhu public DbSet<Job> Jobs { get; set; } public DbSet<Application> Applications { get; set; } //MarL public DbSet<Article> Articles { get; set; } public DbSet<Author> Authors { get; set; } public DbSet<Volunteer> Volunteers { get; set; } //Anshuk public DbSet<Question> Questions { get; set; } public DbSet<Survey> Surveys { get; set; } //madhu public DbSet<FAQCategory> FAQCategories { get; set; } public DbSet<FAQ> FAQs { get; set; } //<NAME> public DbSet<HomeRemedies> HomeRemedies { get; set; } public DbSet<RemedySource> RemedySource { get; set; } public DbSet<SocialServiceClubs> SocialServiceClubs { get; set; } //Cynthia public DbSet<Appointment> Appointments { get; set; } public DbSet<Staff> Staffs { get; set; } } }<file_sep># HumberAreaHospital ## <NAME> - N01387542 - [x] Fix Merge/Conflict Errors ### 1.News Page Feature - [x] CRUD - [x] Pagination and Search Functionality - [x] User View - [x] CSS Responsive Design - [x] WireFrames and ERD, Using 2 Tables, One Author to many Articles ### 2. Volunteer Feature - [x] CRUD - [x] Pagination and Search Functionality - [x] User View - [x] CSS Responsive Design - [x] WireFrames and ERD ## <NAME> - N01176789 - [x] Design Layout & CSS ### 3. Appointment Feature - [x] CRUD - [x] Pagination and Search Functionality - [ ] User View - [x] Admin View - [x] CSS Responsive Design Files: AppointmentController.cs , Views: Appointment/Create.cshtml, Appointment/Delete.cshtml. Appointment/List.cshtml, Appointment/Update.cshtml, Model: Appointment.cs, Viewmodel: AppointmentViewModel.cs ### 2. Staff Directory Feature - [x] CRUD - [x] Pagination and Search Functionality - [x] User View - [x] Admin View - [x] CSS Responsive Design Files: StaffController.cs, Views: Staff/Create.cshtml, Staff/Delete.cshtml, Staff/List.cshtml, Staff/Update,cshtml Model: Staff.cs, ViewModel: StaffSpecialty.cs ## <NAME> - N01397262 ### 1. HomeRemedies - [x] CRUD - [x] Pagination and Search Functionality - [x] User View - [x] Admin View - [x] CSS Responsive Design Controller: HomeRemediesController.cs Views: Delete.cshtml, List.cshtml, New.cshtml, Update.cshtml, User_list.cshtml, User_view.cshtml, View.cshtml Model: HomeRemedies.cs ViewModel: UpdateHomeRemedy.cs ### 1(a).Table connected with HomeRemedies ----- RemedySource - [x] CRUD - [x] Pagination and Search Functionality - [x] User View - [x] CSS Responsive Design Controller: RemedySource.cs Views: Delete.cshtml, List.cshtml, New.cshtml, Update.cshtml, View.cshtml Model: RemedySource.cs ViewModel: UpdateHomeRemedy.cs ### 2. Social Service Clubs - [x] CRUD - [x] Pagination and Search Functionality - [x] User View - [x] Admin View - [x] CSS Responsive Design Controller: SocialServiceClubsController.cs Views: Delete.cshtml, List.cshtml, New.cshtml, Update.cshtml, User_list.cshtml, User_view.cshtml, View.cshtml Models: SocialServiceClubs.cs ## <NAME> - N01399681 ### 1. Find a Doctor - [x] CRUD - [x] Pagination and Search Functionality - [x] User View - [x] CSS Responsive Design Controller: DoctorController.cs Views: Delete.cshtml, List.cshtml, New.cshtml, Update.cshtml,View.cshtml Model: Doctor.cs ViewModel: ViewDoctor.cs, UpdateDoctor.cs ### 1(a).Table connected with Find a Doctor ----- Speciality - [x] CRUD - [x] User View - [x] CSS Responsive Design Controller: SpecialityController.cs Views: Delete.cshtml, List.cshtml, New.cshtml, Update.cshtml, View.cshtml Model: Speciality.cs ### 2. Survey Question - [x] CRUD - [x] User View - [x] Admin View - [x] CSS Responsive Design Controller: QuestionController.cs Views: Delete.cshtml, List.cshtml, New.cshtml, Update.cshtml,View.cshtml Models: Question.cs ### 2(a).Table connected Question ----- Surveys - [x] CRUD - [x] User View - [x] CSS Responsive Design Controller: SurveyController.cs Views: Form.cshtml, List.cshtml, Thanks.cshtml Model: Survey.cs ## <NAME> - N01363180 ### 1.Hospital Career Services - [x] CRUD - [x] Pagination and Search Functionality - [x] User View - [x] Admin View - [x] Responsive Design - [x] WireFrames and ERD, Using 2 Tables, One job to many Applications ### 2. Hospital FAQs - [x] CRUD - [x] Pagination - [x] User View - [x] Admin View - [x] Responsive Design - [x] WireFrames and ERD , using two tables, One FAQCategory to Many FAQs <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models.ViewModels { public class ShowJob { public virtual Job Job { get; set; } public List<Application> Applications { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using HumberAreaHospitalProject.Models.ViewModels; using System.Diagnostics; using System.IO; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; namespace HumberAreaHospitalProject.Controllers { public class StaffController:Controller { private HospitalContext db = new HospitalContext(); //Viewing Staff //pagination method from <NAME> //search method from <NAME> public ActionResult List(string staffSearchKey, int pagenum = 0) { //sending data to the view instead of using viewmodel TempData["isLogged"] = ((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated); List<Staff> staff = db.Staffs.Where(a => (staffSearchKey != null) ? a.staffLname.Contains(staffSearchKey) : true).ToList(); int perpage = 5; int staffCount = staff.Count(); int maxpage = (int)Math.Ceiling((decimal)staffCount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) perpage = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); staff = db.Staffs .Where(a => (staffSearchKey != null) ? a.staffLname.Contains(staffSearchKey) : true) .OrderBy(a => a.staffId) .Skip(start) .Take(perpage) .ToList(); } return View(staff); } //Adding staff public ActionResult Create() { if ((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { StaffSpecialty staffSpecialty = new StaffSpecialty(); staffSpecialty.Specialities = db.Specialities.ToList(); return View(staffSpecialty); } else { return RedirectToAction("index"); } } //sending added staff [HttpPost] public ActionResult Create(string firstName, string lastName, string email, string ext, int specialtyID) { string query = "insert into staffs (staffFname, staffLname, staffEmail, staffExt, specialtyID)" + "values (@staffFname, @staffLname, @staffEmail, @staffExt, @specialtyID)"; SqlParameter[] sqlParameters = new SqlParameter[5]; sqlParameters[0] = new SqlParameter("@staffFname", firstName); sqlParameters[1] = new SqlParameter("@staffLname", lastName); sqlParameters[2] = new SqlParameter("@staffEmail", email); sqlParameters[3] = new SqlParameter("@staffExt", ext); sqlParameters[4] = new SqlParameter("@specialtyID", specialtyID); db.Database.ExecuteSqlCommand(query, sqlParameters); return RedirectToAction("List"); } //selects staff to update public ActionResult Update(int id) { if ((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { string query = "select * from staffs where staffId = @id"; var Parameter = new SqlParameter("@id", id); Staff staff = db.Staffs.SqlQuery(query, Parameter).FirstOrDefault(); StaffSpecialty staffSpecialty = new StaffSpecialty(); staffSpecialty.staff = staff; staffSpecialty.Specialities = db.Specialities.ToList(); return View(staffSpecialty); } else { return RedirectToAction("index"); } } //sends update [HttpPost] public ActionResult Update(int id, string firstName, string lastName, string email, string ext, int specialtyID) { string query = "update staffs set staffFname = @firstName, staffLname = @lastName, staffEmail = @email, staffExt = @ext, SpecialtyID = @specialtyID where staffId = @id"; SqlParameter[] sqlParameters = new SqlParameter[6]; sqlParameters[0] = new SqlParameter("@firstName", firstName); sqlParameters[1] = new SqlParameter("@lastName", lastName); sqlParameters[2] = new SqlParameter("@ext", ext); sqlParameters[3] = new SqlParameter("@email", email); sqlParameters[4] = new SqlParameter("@specialtyID", specialtyID); sqlParameters[5] = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, sqlParameters); return RedirectToAction("List"); } //confirms delete public ActionResult Delete(int id) { if ((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { string query = "select * from staffs where staffId = @id"; var Parameter = new SqlParameter("@id", id); Staff staff = db.Staffs.SqlQuery(query, Parameter).FirstOrDefault(); return View(staff); } else { return RedirectToAction("index"); } } //deletes staff [HttpPost] public ActionResult DeleteStaff(int id) { string query = "delete from staffs where staffId = @id"; var Parameter = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, Parameter); return RedirectToAction("List"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using HumberAreaHospitalProject.Models; using HumberAreaHospitalProject.Models.ViewModels; using System.Data.Entity; using HumberAreaHospitalProject.Data; using System.Diagnostics; namespace HumberAreaHospitalProject.Controllers { public class HomeRemediesController : Controller { // GET: HomeRemedies private HospitalContext db = new HospitalContext(); //Get list of remedies for user to see public ActionResult User_list(string remedysearchkey, int pagenum = 0) { //check if we can access the search key //Debug.WriteLine("The search key is "+remedysearchkey); //query to fecth allthe remedies string query = "Select * from HomeRemedies"; List<SqlParameter> sqlparams = new List<SqlParameter>(); if (remedysearchkey != "") { //changing the query to add search key query = query + " where HomeRemedies_title like @searchkey"; sqlparams.Add(new SqlParameter("@searchkey", "%" + remedysearchkey + "%")); //Debug.WriteLine("The query is "+ query); } List<HomeRemedies> remedy = db.HomeRemedies.SqlQuery(query, sqlparams.ToArray()).ToList(); //Start of Pagination int perpage = 3; int remcount = remedy.Count(); int maxpage = (int)Math.Ceiling((decimal)remcount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) pagenum = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); List<SqlParameter> newparams = new List<SqlParameter>(); if (remedysearchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + remedysearchkey + "%")); ViewData["remedysearchkey"] = remedysearchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by HomeRemedies_id offset @start rows fetch first @perpage rows only "; Debug.WriteLine(pagedquery); Debug.WriteLine("offset " + start); Debug.WriteLine("fetch first " + perpage); remedy = db.HomeRemedies.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } //End of Pagination return View(remedy); } // GET: HomeRemedies public ActionResult List(string remedysearchkey, int pagenum = 0) { //check if we can access the search key //Debug.WriteLine("The search key is "+remedysearchkey); //query to fecth all the remedies string query = "Select * from HomeRemedies"; List<SqlParameter> sqlparams = new List<SqlParameter>(); if (remedysearchkey != "") { //changing the query to add search key query = query + " where HomeRemedies_title like @searchkey"; sqlparams.Add(new SqlParameter("@searchkey", "%" + remedysearchkey + "%")); //Debug.WriteLine("The query is "+ query); } List<HomeRemedies> remedy = db.HomeRemedies.SqlQuery(query, sqlparams.ToArray()).ToList(); //Start of Pagination, Christine's code int perpage = 3; int remcount = remedy.Count(); int maxpage = (int)Math.Ceiling((decimal)remcount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) pagenum = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); List<SqlParameter> newparams = new List<SqlParameter>(); if (remedysearchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + remedysearchkey + "%")); ViewData["remedysearchkey"] = remedysearchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by HomeRemedies_id offset @start rows fetch first @perpage rows only "; Debug.WriteLine(pagedquery); Debug.WriteLine("offset " + start); Debug.WriteLine("fetch first " + perpage); remedy = db.HomeRemedies.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } //End of Pagination Algorithm return View(remedy); } public ActionResult New() { //add new remedy string query = "Select * from RemedySources"; List<RemedySource> remedySources = db.RemedySource.SqlQuery(query).ToList(); return View(remedySources); } [HttpPost] public ActionResult New(string HomeRemedies_title, string HomeRemedies_desc, string remedySource) { //query to add new remedy string query = "insert into HomeRemedies (HomeRemedies_title, HomeRemedies_desc, RemedySource_id) values(@HomeRemedies_title,@HomeRemedies_desc, @remedySource)"; SqlParameter[] sqlparams = new SqlParameter[3]; sqlparams[0] = new SqlParameter("@HomeRemedies_title", HomeRemedies_title); sqlparams[1] = new SqlParameter("@HomeRemedies_desc", HomeRemedies_desc); sqlparams[2] = new SqlParameter("@remedySource", remedySource); db.Database.ExecuteSqlCommand(query, sqlparams); return RedirectToAction("List"); } public ActionResult Update(int id) { //query to fetch existed details of the remedy, which you want yo update string query = "select * from HomeRemedies where HomeRemedies_id = @id"; SqlParameter parameter = new SqlParameter("@id", id); HomeRemedies selectedHomeRemedies = db.HomeRemedies.SqlQuery(query, parameter).FirstOrDefault(); //fetching the remedysource which chosen for the remedy through ViewModel string urlQuery = "Select * from RemedySources"; List<RemedySource> selectedsrc = db.RemedySource.SqlQuery(urlQuery).ToList(); var UpdateHomeRemedy = new UpdateHomeRemedy(); UpdateHomeRemedy.HomeRemedies = selectedHomeRemedies; UpdateHomeRemedy.RemedySources = selectedsrc; return View(UpdateHomeRemedy); } [HttpPost] //update existed details witha new one... public ActionResult Update(int id, string HomeRemedies_title, string HomeRemedies_desc, string RemedySource_id) { //Debug.WriteLine("selected remedy is" + id); string query = "Update HomeRemedies set HomeRemedies_title=@HomeRemedies_title, HomeRemedies_desc=@HomeRemedies_desc, RemedySource_id=@RemedySource_id where HomeRemedies_id=@id"; SqlParameter[] sqlparams = new SqlParameter[4]; sqlparams[0] = new SqlParameter("@HomeRemedies_title", HomeRemedies_title); sqlparams[1] = new SqlParameter("@HomeRemedies_desc", HomeRemedies_desc); sqlparams[2] = new SqlParameter("@RemedySource_id", RemedySource_id); sqlparams[3] = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, sqlparams); return RedirectToAction("List"); } //once the user clicks on the title, it will show the details of just that remedy.. public ActionResult View(int id) { //fetching the details of that perticular remedy string query = "Select * from HomeRemedies where HomeRemedies_id=@id"; var parameter = new SqlParameter("@id", id); HomeRemedies selectedHomeRemedies = db.HomeRemedies.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedHomeRemedies); } //user view do not allow to add, update and delete... public ActionResult User_view(int id) { string query = "Select * from HomeRemedies where HomeRemedies_id=@id"; var parameter = new SqlParameter("@id", id); HomeRemedies selectedHomeRemedies = db.HomeRemedies.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedHomeRemedies); } public ActionResult Delete(int id) { string query = "Select * from HomeRemedies where HomeRemedies_id=@id"; var parameter = new SqlParameter("@id", id); HomeRemedies selectedHomeRemedies = db.HomeRemedies.SqlQuery(query, parameter).FirstOrDefault(); return View(selectedHomeRemedies); } [HttpPost] public ActionResult Delete(int? id) { string query = "Delete from HomeRemedies where HomeRemedies_id=@id"; var parameter = new SqlParameter("@id", id); db.Database.ExecuteSqlCommand(query, parameter); return RedirectToAction("List"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using System.Diagnostics; using System.Data.SqlClient; using HumberAreaHospitalProject.Models.ViewModels; using System.Data.Entity; using System.Net; namespace HumberAreaHospitalProject.Controllers { public class ArticleController : Controller { private HospitalContext db = new HospitalContext(); //Accessible only for user that is login //[Authorize] public ActionResult NewsPage() { string query = "SELECT * from Articles"; List<Article> articles = db.Articles.SqlQuery(query).ToList(); return View(articles); } public ActionResult List(string searchkey, int pagenum = 1) { //<NAME> In-Class Example //Query to get All the Articles string query = "Select * from Articles INNER JOIN Authors ON Articles.AuthorID = Authors.AuthorID"; //Debug.WriteLine(query); //Start creating a Class for sql parameter List<SqlParameter> parameters = new List<SqlParameter>(); //Searchkey is not empty if (searchkey != "") { //Add to the query for Search query = query + " where ArticleTitle like @searchkey"; parameters.Add(new SqlParameter("@searchkey", "%" + searchkey + "%")); } //Execute the sql query for articles List<Article> articles = db.Articles.SqlQuery(query, parameters.ToArray()).ToList(); //Add Variable for how many per page int perpage = 3; //Get the total count values of articles //Debug.WriteLine("Article Count is " + articles.Count()); int volunteercount = articles.Count(); //Max page will be the Count Divided by per page. Rounding this to the upper limit so that //rows which are not divisible to the perpage will still be shown int maxpage = (int)Math.Ceiling((decimal)volunteercount / perpage); //Maxpage is greater than 0, maxpage will be zero if (maxpage < 0) maxpage = 0; //Page number less than 1 will always be 1 if (pagenum < 1) pagenum = 1; //If page number is greater than maxpage, pagenum will be equal to maxpage if (pagenum > maxpage) pagenum = maxpage; //Start value should be 0, but should be ascending depending on the perpage value //Start with index 0, and then next will be 3, since perpage is 3. So the next page will start with index 3. //The first page will show 0,1,2 index row and the next page will be 3,4,5 indexes and so on. int start = (int)(perpage * pagenum) - perpage; //Debug.WriteLine("start number is: "+start); Debug.WriteLine("start number is: " + start); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; ViewData["maxpage"] = maxpage; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum) + " of " + (maxpage); List<SqlParameter> newparams = new List<SqlParameter>(); if (searchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + searchkey + "%")); ViewData["searchkey"] = searchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by ArticleID offset @start rows fetch first @perpage rows only "; //Debug.WriteLine(pagedquery); //Debug.WriteLine("offset " + start); //Debug.WriteLine("fetch first " + perpage); //Re-write the execution of sql query with page listing articles = db.Articles.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } return View(articles); } //Accessible only for user that is login //Use to apply also on the other view //[ActionName("NewsPage")] public ActionResult View(int id) { Article selectedarticle = db.Articles.SqlQuery("Select * from Articles INNER JOIN Authors ON Articles.AuthorID = Authors.AuthorID where Articles.ArticleID = @id", new SqlParameter("@id", id)).FirstOrDefault(); return View(selectedarticle); } //Accessible only for user that is login //[Authorize] //This function is needed for the User to Show as a different URL public ActionResult Create() { string query = "Select * from Authors"; List<Author> authors = db.Authors.SqlQuery(query).ToList(); return View(authors); } [HttpPost] public ActionResult Create(string articleTitle, string articleBody, DateTime published, string featured, int authorId) { try { //Try if the SQL query will work string query = "insert into Articles (ArticleTitle, ArticleBody, Published,Featured, AuthorID) values(@articletitle, @articlebody, @published,@featured,@authorId)"; //Debug.WriteLine(query); SqlParameter[] parameters = new SqlParameter[5]; parameters[0] = new SqlParameter("@articletitle", articleTitle); parameters[1] = new SqlParameter("@articlebody", articleBody); parameters[2] = new SqlParameter("@published", published); parameters[3] = new SqlParameter("@featured", featured); parameters[4] = new SqlParameter("@authorId", authorId); db.Database.ExecuteSqlCommand(query, parameters); //Debug.WriteLine("The new record being added in Articles"); return RedirectToAction("List"); } catch { //Get Bad Request if Sql got error return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } //Accessible only for user that is login //[Authorize] public ActionResult Update(int? id) { if (id == null) { //If no id value has been presented, will return a BadRequest return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } string query = "Select * from Articles where ArticleID=@id"; //Debug.WriteLine(query); //Debug.WriteLine("Article ID of: " + id); SqlParameter parameter = new SqlParameter("@id", id); Article selectedarticle = db.Articles.SqlQuery(query, parameter).First(); //Query to get all the Authors string query2 = "Select * from Authors"; //Sql Execute for 2nd Query List<Author> authors = db.Authors.SqlQuery(query2).ToList(); var UpdateArticle = new UpdateArticle(); //Add list of authors and an article in a model view UpdateArticle.authors = authors; UpdateArticle.article = selectedarticle; if (selectedarticle == null) { //if article is not found in the database return HttpNotFound(); } return View(UpdateArticle); } [HttpPost] public ActionResult Update(int id, string articleTitle, string articleBody, DateTime published, string featured, int authorId) { try { //ArticleTitle, ArticleBody, Date,Featured, AuthorID // TODO: Add update logic here string query = "UPDATE Articles set ArticleTitle = @articletitle, ArticleBody = @articlebody, Published = @published, Featured = @featured, AuthorID = @authorId where ArticleID = @id "; SqlParameter[] parameters = new SqlParameter[6]; parameters[0] = new SqlParameter("@articletitle", articleTitle); parameters[1] = new SqlParameter("@articlebody", articleBody); parameters[2] = new SqlParameter("@published", published); parameters[3] = new SqlParameter("@featured", featured); parameters[4] = new SqlParameter("@authorId", authorId); parameters[5] = new SqlParameter("@id", id); //Debug.WriteLine(query); //Debu.WriteLine("The Article ID is :" + id); db.Database.ExecuteSqlCommand(query, parameters); return RedirectToAction("List"); } catch { //Get Bad Request if Sql got error return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } //Use to accessible only for login user //[Authorize] public ActionResult Delete(int? id) { if (id == null) { //If no id value has been presented, will return a BadRequest return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Article selectedarticle = db.Articles.SqlQuery("Select * from Articles INNER JOIN Authors ON Articles.AuthorID = Authors.AuthorID where Articles.ArticleID = @id", new SqlParameter("@id", id)).FirstOrDefault(); if (selectedarticle == null) { //If article has no value in the database return HttpNotFound(); } return View(selectedarticle); } [HttpPost] public ActionResult Delete(int id) { try { ////query to delete the Book in the books table string deletearticle = "DELETE from Articles where ArticleID= @id"; //query to delete the relationship on the bridging table //Debug.WriteLine(delbooks); //Debug.WriteLine(delrelationship); SqlParameter parameters = new SqlParameter("@id", id); //Run the sql command db.Database.ExecuteSqlCommand(deletearticle, parameters); return RedirectToAction("List"); } catch { //Get Bad Request if Sql got error return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } } }<file_sep>namespace HumberAreaHospitalProject.Migrations { using System; using System.Data.Entity.Migrations; public partial class Added_FAQ : DbMigration { public override void Up() { CreateTable( "dbo.FAQs", c => new { FAQID = c.Int(nullable: false, identity: true), FAQCategoryID = c.Int(nullable: false), FAQQuestion = c.Int(nullable: false), FAQAnswer = c.Int(nullable: false), FAQLikes = c.Int(nullable: false), }) .PrimaryKey(t => t.FAQID) .ForeignKey("dbo.FAQCategories", t => t.FAQCategoryID, cascadeDelete: true) .Index(t => t.FAQCategoryID); } public override void Down() { DropForeignKey("dbo.FAQs", "FAQCategoryID", "dbo.FAQCategories"); DropIndex("dbo.FAQs", new[] { "FAQCategoryID" }); DropTable("dbo.FAQs"); } } } <file_sep>namespace HumberAreaHospitalProject.Migrations { using System; using System.Data.Entity.Migrations; public partial class added_author_article_volunteer : DbMigration { public override void Up() { CreateTable( "dbo.Articles", c => new { ArticleID = c.Int(nullable: false, identity: true), ArticleTitle = c.String(), ArticleBody = c.String(), Date = c.DateTime(nullable: false), Featured = c.String(), AuthorID = c.Int(nullable: false), }) .PrimaryKey(t => t.ArticleID) .ForeignKey("dbo.Authors", t => t.AuthorID, cascadeDelete: true) .Index(t => t.AuthorID); CreateTable( "dbo.Authors", c => new { AuthorID = c.Int(nullable: false, identity: true), AuthorFname = c.String(), AuthorLname = c.String(), Email = c.String(), Phone = c.String(), }) .PrimaryKey(t => t.AuthorID); CreateTable( "dbo.Volunteers", c => new { VolunteerID = c.Int(nullable: false, identity: true), VolunteerFname = c.String(), VolunteerLname = c.String(), Address = c.String(), Email = c.String(), HomePhone = c.String(), WorkPhone = c.String(), Skills = c.String(), Day = c.String(), Time = c.String(), Department = c.String(), Notes = c.String(), }) .PrimaryKey(t => t.VolunteerID); } public override void Down() { DropForeignKey("dbo.Articles", "AuthorID", "dbo.Authors"); DropIndex("dbo.Articles", new[] { "AuthorID" }); DropTable("dbo.Volunteers"); DropTable("dbo.Authors"); DropTable("dbo.Articles"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models.ViewModels { public class UpdateArticle { //Updatin the Article should also see the list of authors available public Article article { get; set; } public List<Author> authors { get; set; } } }<file_sep>namespace HumberAreaHospitalProject.Migrations { using System; using System.Data.Entity.Migrations; public partial class Added_Application : DbMigration { public override void Up() { CreateTable( "dbo.Applications", c => new { ApplicationID = c.Int(nullable: false, identity: true), JobID = c.Int(nullable: false), ApplicantFirstName = c.String(), ApplicantLastName = c.String(), ApplicantEmail = c.String(), ApplicantPhone = c.String(), ApplicantAddress = c.String(), ApplicantCity = c.String(), ApplicantProvince = c.String(), ApplicantZipCode = c.String(), ApplicantResume = c.String(), }) .PrimaryKey(t => t.ApplicationID) .ForeignKey("dbo.Jobs", t => t.JobID, cascadeDelete: true) .Index(t => t.JobID); } public override void Down() { DropForeignKey("dbo.Applications", "JobID", "dbo.Jobs"); DropIndex("dbo.Applications", new[] { "JobID" }); DropTable("dbo.Applications"); } } } <file_sep>namespace HumberAreaHospitalProject.Migrations { using System; using System.Data.Entity.Migrations; public partial class updated_FAQ : DbMigration { public override void Up() { AlterColumn("dbo.FAQs", "FAQQuestion", c => c.String()); AlterColumn("dbo.FAQs", "FAQAnswer", c => c.String()); } public override void Down() { AlterColumn("dbo.FAQs", "FAQAnswer", c => c.Int(nullable: false)); AlterColumn("dbo.FAQs", "FAQQuestion", c => c.Int(nullable: false)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using HumberAreaHospitalProject.Models; using System.Data.Entity; using HumberAreaHospitalProject.Data; using System.Diagnostics; using HumberAreaHospitalProject.Models.ViewModels; namespace HumberAreaHospitalProject.Controllers { public class FAQController : Controller { private HospitalContext db = new HospitalContext(); //List FAQs public ActionResult List( int pagenum = 0) { string query = "select * from FAQs";//SQL query to select everything from FAQs table List<SqlParameter> sqlparams = new List<SqlParameter>(); List<FAQ> FAQs = db.FAQs.SqlQuery(query, sqlparams.ToArray()).ToList(); //pagination code reffered from christine's petgrooming project //Pagination for FAQs int perpage = 3; int petcount = FAQs.Count(); int maxpage = (int)Math.Ceiling((decimal)petcount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) pagenum = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); List<SqlParameter> newparams = new List<SqlParameter>(); newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by JobID offset @start rows fetch first @perpage rows only "; FAQs = db.FAQs.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } //End of Pagination return View(FAQs); } [HttpPost] public ActionResult New(string FAQQuestion, string FAQAnswer, int FAQCategoryID) { string query = "insert into FAQs (FAQQuestion, FAQAnswer,FAQCategoryID ) values (@FAQQuestion,@FAQAnswer,@FAQCategoryID)";//Sql quey to insert FAQ into database SqlParameter[] sqlparams = new SqlParameter[3]; sqlparams[0] = new SqlParameter("@FAQQuestion", FAQQuestion); sqlparams[1] = new SqlParameter("@FAQAnswer", FAQAnswer); sqlparams[2] = new SqlParameter("@FAQCategoryID", FAQCategoryID); db.Database.ExecuteSqlCommand(query, sqlparams); //returning list of FAQs After adding return RedirectToAction("List"); } // GET: FAQ public ActionResult New() { List<FAQCategory> categories = db.FAQCategories.SqlQuery("select * from FAQCategories").ToList(); return View(categories); } //update FAQ public ActionResult Update(int id) { //need information about a particular FAQ FAQ selectedFAQ = db.FAQs.SqlQuery("select * from FAQs where FAQID = @id", new SqlParameter("@id", id)).FirstOrDefault(); List<FAQCategory> categories = db.FAQCategories.SqlQuery("select * from FAQCategories").ToList(); UpdateFAQController UpdateFAQViewModel = new UpdateFAQController(); UpdateFAQViewModel.FAQ = selectedFAQ; UpdateFAQViewModel.FAQCategory = categories; return View(UpdateFAQViewModel); } //[HttpPost] Update [HttpPost] public ActionResult Update(int id, string FAQQuestion, string FAQAnswer, int FAQCategoryID ) { //query to update FAQs string PostDate = DateTime.Now.ToString("dd/MM/yyyy"); string query = "update FAQs set FAQQuestion =@FAQQuestion, FAQAnswer=@FAQAnswer, FAQCategoryID=@FAQCategoryID where FAQID=@id";//Sql query to update FAQ //key pair values to hold new values SqlParameter[] sqlparams = new SqlParameter[6]; sqlparams[0] = new SqlParameter("@FAQQuestion", FAQQuestion); sqlparams[1] = new SqlParameter("@FAQAnswer", FAQAnswer); sqlparams[2] = new SqlParameter("@FAQCategoryID", FAQCategoryID); sqlparams[5] = new SqlParameter("@id", id); //Exceuting the sql query with new values db.Database.ExecuteSqlCommand(query, sqlparams); //Return to list view of FAQs return RedirectToAction("List"); } //Display Detais about individual FAQ public ActionResult Show(int? id) { //need information about a particular FAQ FAQ selectedFAQ = db.FAQs.SqlQuery("select * from FAQs where FAQID = @id", new SqlParameter("@id", id)).FirstOrDefault(); List<FAQCategory> categories = db.FAQCategories.SqlQuery("select * from FAQCategories").ToList(); UpdateFAQController UpdateFAQViewModel = new UpdateFAQController(); UpdateFAQViewModel.FAQ = selectedFAQ; UpdateFAQViewModel.FAQCategory = categories; return View(UpdateFAQViewModel); } //delete public ActionResult Delete(int id) { //Query to delete particualr FAQ from the table based on the FAQ id string query = "delete from FAQs where FAQID=@id"; SqlParameter[] parameter = new SqlParameter[1]; //storing the id of the FAQ to be deleted parameter[0] = new SqlParameter("@id", id); //Excecuting the query db.Database.ExecuteSqlCommand(query, parameter); // returning to lsit view of the FAQs after deleting return RedirectToAction("List"); } //user_view of FAQ public ActionResult User_view() { List<FAQ> FAQs = db.FAQs.SqlQuery("Select * from FAQs").ToList(); return View(FAQs); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class HomeRemedies { [Key] public int HomeRemedies_id { get; set; } public string HomeRemedies_title { get; set; } public string HomeRemedies_desc { get; set; } /* foreigh key of remedy resources one source has list of remedies One source - many remedies here I have taken primary key of RemedySources table as a foreign key for HomeRemedies table */ public int RemedySource_id { get; set; } [ForeignKey("RemedySource_id")] public virtual RemedySource RemedySource { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class Volunteer { /* List of Information for Volunteer Table Id, First Name, Last Name, Address, Email, HomePhone, Work Phone, Skills, Day Available, Time Available, Department wish to apply, Special Notes */ [Key] public int VolunteerID { get; set; } public string VolunteerFname { get; set; } public string VolunteerLname { get; set; } public string Address { get; set; } public string Email { get; set; } public string HomePhone { get; set; } public string WorkPhone { get; set; } public string Skills { get; set; } //Day is Monday, Tuesday , Wednesday and so on. public string Day { get; set; } //Time is specific time of the day, Morning, Afternoon, Evening //This values are Morning 8:00am- 12:00am, Afternoon 1pm-5pm, Evening 6pm-10pm public string Time { get; set; } //List of Department Child Care, Emergency, public string Preference { get; set; } public string Notes { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class Question { //This class defines the idea of a question /*It will have question id * question text*/ [Key] public int QuestionID { get; set; } public string QuestionText { get; set; } //now the "Many" in one questions to many responses. public ICollection<Survey> Answers { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models { public class Application { /* * Application model consists of applicant details who applies for the job * * ApplicationId - Identity oof the application * JObID - Job identity which is foreign key refereing to jobs table * ApplicantFirstName - First name of the applicant * ApplicantLastName - Last name of the applicant * ApplicantEmail - Email id of the applicant * Applicantphone - Phone number of the applicant * ApplicantAddress - Address of the applicant * ApplicantCity - City of the applicant * ApplicantProvince - Province of the applicant * ApplicantZipCode - Postal code or Zipcode of the applicant * ApplicantResume - Resume of the applicant * ApplicationDate - Date on which the applicant has applied for job */ [Key] public int ApplicationID { get; set; } public int JobID { get; set; } [ForeignKey("JobID")] public virtual Job Job { get; set; } public string ApplicantFirstName { get; set; } public string ApplicantLastName { get; set; } public string ApplicantEmail { get; set; } public string ApplicantPhone { get; set; } public string ApplicantAddress { get; set; } public string ApplicantCity { get; set; } public string ApplicantProvince { get; set; } public string ApplicantZipCode { get; set; } public string ApplicantResume { get; set; } public DateTime ApplicationDate { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using HumberAreaHospitalProject.Models; using System.Data.Entity; using HumberAreaHospitalProject.Data; namespace HumberAreaHospitalProject.Controllers { public class ApplicationController : Controller { private HospitalContext db = new HospitalContext(); // GET: Application public ActionResult List(String appsearchkey, int pagenum = 0) { string query = "select * from Applications";//SQL query to select everything from Applications table List<SqlParameter> sqlparams = new List<SqlParameter>(); if (appsearchkey != "") //Checkign if the search key is empty or null { query = query + " where ApplicantFirstName like @searchkey";//Appending sql query to existing query sqlparams.Add(new SqlParameter("@searchkey", "%" + appsearchkey + "%")); } List<Application> Applications = db.Applications.SqlQuery(query, sqlparams.ToArray()).ToList(); //pagination code reffered from christine's petgrooming project //Pagination for Applications int perpage = 5; int petcount = Applications.Count(); int maxpage = (int)Math.Ceiling((decimal)petcount / perpage) - 1; if (maxpage < 0) maxpage = 0; if (pagenum < 0) pagenum = 0; if (pagenum > maxpage) pagenum = maxpage; int start = (int)(perpage * pagenum); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum + 1) + " of " + (maxpage + 1); List<SqlParameter> newparams = new List<SqlParameter>(); if (appsearchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + appsearchkey + "%")); ViewData["appsearchkey"] = appsearchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by ApplicationDate offset @start rows fetch first @perpage rows only "; Applications = db.Applications.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } //End of Pagination return View(Applications); } //Add new Application [HttpPost] public ActionResult New(int JobID, string ApplicantFirstName, string ApplicantLastName, string ApplicantEmail, string ApplicantPhone, string ApplicantAddress, string ApplicantCity,string ApplicantProvince,string ApplicantZipCode) { string ApplicationDate = DateTime.Now.ToString("dd/MM/yyyy"); string query = "insert into Applications (ApplicantFirstName, ApplicantLastName, ApplicantEmail, ApplicantPhone, ApplicantAddress, ApplicantCity, ApplicantProvince, ApplicantZipCode, ApplicantionDate,JobID) values (@JobTitle, @JobCategory, @JobType, @Description, @Requirements, @ApplicationDate,@JobID)";//Sql query to add new application SqlParameter[] sqlparams = new SqlParameter[9]; sqlparams[0] = new SqlParameter("ApplicantFirstName", ApplicantFirstName); sqlparams[1] = new SqlParameter("@ApplicantLastName", ApplicantLastName); sqlparams[2] = new SqlParameter("@ApplicantEmail", ApplicantEmail); sqlparams[3] = new SqlParameter("@ApplicantPhone", ApplicantPhone); sqlparams[4] = new SqlParameter("@ApplicantAddress", ApplicantAddress); sqlparams[5] = new SqlParameter("@ApplicantCity", ApplicantCity); sqlparams[6] = new SqlParameter("@ApplicantProvince", ApplicantProvince); sqlparams[7] = new SqlParameter("@ApplicantZipCode", ApplicantZipCode); sqlparams[8] = new SqlParameter("@ApplicationDate", ApplicationDate); sqlparams[8] = new SqlParameter("@JobID", JobID); db.Database.ExecuteSqlCommand(query, sqlparams); return RedirectToAction("List"); } public ActionResult New() { return View(); } //Display individual Application Details public ActionResult Show(int? id) { string query = "select * from Applications where ApplicationID = @ApplicationID"; //sql query to slect all from Applications table based on ApplicationID var parameter = new SqlParameter("@ApplicationID", id); Application application = db.Applications.SqlQuery(query, parameter).FirstOrDefault(); return View(application); } //Update public ActionResult Update(int id) { //need information about a particular Application Application selectedapplication = db.Applications.SqlQuery("select * from Applications where ApplicationID = @id", new SqlParameter("@id", id)).FirstOrDefault(); return View(selectedapplication); } //[HttpPost] Update [HttpPost] public ActionResult Update(int id, string ApplicantFirstName, string ApplicantLastName, string ApplicantEmail, string ApplicantPhone, string ApplicantAddress ,string ApplicantCity, string ApplicantProvince,string ApplicantZipCode) { //query to update Application string query = "update Applications set ApplicantFirstName =@ApplicantFirstName, ApplicantLastName=@ApplicantLastName, ApplicantEmail=@ApplicantEmail, ApplicantPhone=@ApplicantPhone, ApplicantAddress=@ApplicantAddress,ApplicantCity=@ApplicantCity,ApplicantProvince=@ApplicantProvince,ApplicantZipCode=@ApplicantZipCode where ApplicationID=@id"; //key pair values to hold new values SqlParameter[] sqlparams = new SqlParameter[9]; sqlparams[0] = new SqlParameter("@ApplicantFirstName", ApplicantFirstName); sqlparams[1] = new SqlParameter("@ApplicantLastName", ApplicantLastName); sqlparams[2] = new SqlParameter("@ApplicantEmail", ApplicantEmail); sqlparams[3] = new SqlParameter("@ApplicantPhone", ApplicantPhone); sqlparams[4] = new SqlParameter("@ApplicantAddress", ApplicantAddress); sqlparams[5] = new SqlParameter("@ApplicantCity", ApplicantCity); sqlparams[6] = new SqlParameter("@ApplicantProvince", ApplicantProvince); sqlparams[7] = new SqlParameter("@ApplicantZipCode", ApplicantZipCode); sqlparams[8] = new SqlParameter("@id", id); //Exceuting the sql query with new values db.Database.ExecuteSqlCommand(query, sqlparams); //Return to list view of Applications return RedirectToAction("List"); } //delete public ActionResult Delete(int id) { //Query to delete particualr make from the table based on the make id string query = "delete from Applications where ApplicationID=@id"; SqlParameter[] parameter = new SqlParameter[1]; //storing the id of the make to be deleted parameter[0] = new SqlParameter("@id", id); //Excecuting the query db.Database.ExecuteSqlCommand(query, parameter); // returning to lsit view of the make after deleting return RedirectToAction("List"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class Appointment { /*Defines appointment*/ [Key] public int appointmentId { get; set; } public string appointmentFname { get; set; } public string appointmentLname { get; set; } public string appointmentPhone { get; set; } public string appointmentEmail { get; set; } public DateTime appointmentDate { get; set; } public int DoctorID { get; set; } [ForeignKey("DoctorID")] public virtual Doctor Doctor { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using HumberAreaHospitalProject.Data; using HumberAreaHospitalProject.Models; using System.Diagnostics; using System.Data.SqlClient; using System.Data.Entity; using System.Net; namespace HumberAreaHospitalProject.Controllers { public class AuthorController : Controller { private HospitalContext db = new HospitalContext(); //Accessible only for user that is login //[Authorize] public ActionResult List(string searchkey, int pagenum = 1) { //Christine Bittle In-Class Example //Query to get All the Authors string query = "Select * from Authors"; //Debug.WriteLine(query); //Debug.WriteLine(query); //Run the Sql command List<SqlParameter> parameters = new List<SqlParameter>(); //Searchkey is not empty if (searchkey != "") { //Add to the query for Search query = query + " where AuthorFname like @searchkey"; parameters.Add(new SqlParameter("@searchkey", "%" + searchkey + "%")); } //Execute the sql query List<Author> authors = db.Authors.SqlQuery(query, parameters.ToArray()).ToList(); //Add Variable for how many per page int perpage = 3; //Debug.WriteLine("Authors Count is " + authors.Count()); //Get the total count values int volunteercount = authors.Count(); //Max page will be the Count Divided by per page. Rounding this to the upper limit so that //rows which are not divisible to the perpage will still be shown int maxpage = (int)Math.Ceiling((decimal)volunteercount / perpage); //Maxpage is greater than 0, maxpage will be zero if (maxpage < 0) maxpage = 0; //Page number less than 1 will always be 1 if (pagenum < 1) pagenum = 1; //If page number is greater than maxpage, pagenum will be equal to maxpag if (pagenum > maxpage) pagenum = maxpage; //Start value should be 0, but should be ascending depending on the perpage value //Start with index 0, and then next will be 3, since perpage is 3. So the next page will start with index 3. //The first page will show 0,1,2 index row and the next page will be 3,4,5 indexes and so on. int start = (int)(perpage * pagenum) - perpage; Debug.WriteLine("start number is: " + start); ViewData["pagenum"] = pagenum; ViewData["pagesummary"] = ""; ViewData["maxpage"] = maxpage; if (maxpage > 0) { ViewData["pagesummary"] = (pagenum) + " of " + (maxpage); List<SqlParameter> newparams = new List<SqlParameter>(); if (searchkey != "") { newparams.Add(new SqlParameter("@searchkey", "%" + searchkey + "%")); ViewData["searchkey"] = searchkey; } newparams.Add(new SqlParameter("@start", start)); newparams.Add(new SqlParameter("@perpage", perpage)); string pagedquery = query + " order by AuthorID offset @start rows fetch first @perpage rows only "; //Debug.WriteLine(pagedquery); //Debug.WriteLine("offset " + start); //Debug.WriteLine("fetch first " + perpage); //Re-write the execution of sql query with page listing authors = db.Authors.SqlQuery(pagedquery, newparams.ToArray()).ToList(); } return View(authors); } //Accessible only for user that is login //[Authorize] //Get View for the specific Author public ActionResult View(int id) { //Execute the sql with the Query on it Author selectedauthor = db.Authors.SqlQuery("Select * from Authors where AuthorID = @id", new SqlParameter("@id", id)).First(); return View(selectedauthor); } //Accessible only for user that is login //[Authorize] public ActionResult Create() { return View(); } // POST: Article/Create [HttpPost] public ActionResult Create(string authorFname, string authorLname, string email, string phone) { try { //Try if the SQL query will work string query = "INSERT into Authors (AuthorFname, AuthorLname, Email, Phone) values(@fname, @lname, @email,@phone)"; //Debug.WriteLine(query); SqlParameter[] parameters = new SqlParameter[4]; parameters[0] = new SqlParameter("@fname", authorFname); parameters[1] = new SqlParameter("@lname", authorLname); parameters[2] = new SqlParameter("@email", email); parameters[3] = new SqlParameter("@phone", phone); db.Database.ExecuteSqlCommand(query, parameters); // Debug.WriteLine("The new record being added in Author"); return RedirectToAction("List"); } catch { //Get Bad Request if Sql got error return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } //Accessible only for user that is login //[Authorize] public ActionResult Update(int? id) { if (id == null) { //If no id value has been presented, will return a BadRequest return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //Debug.WriteLine("Author id: " + id); string query = "Select * from Authors where AuthorID=@id"; SqlParameter parameter = new SqlParameter("@id", id); Author selectedauthor = db.Authors.SqlQuery(query, parameter).First(); if (selectedauthor == null) { //If value is null on selectedauthor, no value on the database return HttpNotFound(); } return View(selectedauthor); } // POST: Article/Edit/5 [HttpPost] public ActionResult Update(int id, string authorFname, string authorLname, string email, string phone) { try { //Sql for Authors string query = "UPDATE Authors set AuthorFname = @fname, AuthorLname = @lname, Email = @email, Phone = @phone where AuthorID = @id "; //Debug.WriteLine(query); SqlParameter[] parameters = new SqlParameter[5]; parameters[0] = new SqlParameter("@fname", authorFname); parameters[1] = new SqlParameter("@lname", authorLname); parameters[2] = new SqlParameter("@email", email); parameters[3] = new SqlParameter("@phone", phone); parameters[4] = new SqlParameter("@id", id); //Debug.WriteLine("Author Id = " +id); db.Database.ExecuteSqlCommand(query, parameters); return RedirectToAction("List"); } catch { //Get Bad Request if Sql got error return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } //Use to apply also on the other view //[Authorize] public ActionResult Delete(int? id) { if (id == null) { //If no id value has been presented, will return a BadRequest return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Author selectedauthor = db.Authors.SqlQuery("Select * from Authors where AuthorID = @id", new SqlParameter("@id", id)).First(); if (selectedauthor == null) { //If value is null on selectedauthor, no value on the database return HttpNotFound(); } return View(selectedauthor); } [HttpPost] public ActionResult Delete(int id) { try { //query for deleting Author string deleteauthor = "DELETE from Authors where AuthorID= @id"; //Debug.WriteLine(query); SqlParameter parameters = new SqlParameter("@id", id); //Run the sql command db.Database.ExecuteSqlCommand(deleteauthor, parameters); return RedirectToAction("List"); } catch { //Get Bad Request if Sql got error return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HumberAreaHospitalProject.Models { public class Doctor { /*This class defines a doctor. Let's see what defines a doctor in general or what is the idea of a doctor ID Title First Name Last Name It also needs to reference the speciality */ [Key] public int DoctorID { get; set; } public string Title { get; set; } public string DoctorFname { get; set; } public string DoctorLname { get; set; } /*Now I need to refernce the speciality*/ public int SpecialityID { get; set; } [ForeignKey("SpecialityID")] public virtual Speciality Specialities { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models { public class FAQ /* * FAQ Model Describes * FAQID - Identity of FAQ * FAQCategoryID - Identity of FAQCategory in the FAQCAtegories Table also, A foreign Key * FAQQuestion - The Actual question * FAQAnswer - The Actual answer for the question * */ { [Key] public int FAQID { get; set; } [ForeignKey("FAQCategory")] public int FAQCategoryID { get; set; } public FAQCategory FAQCategory { get; set; } public string FAQQuestion{ get; set; } public string FAQAnswer { get; set; } } }<file_sep> using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HumberAreaHospitalProject.Models.ViewModels { public class ListSurvey { /*This class requires list of question and list of answers*/ public List<Question> questions { get; set; } public List<Survey> surveys { get; set; } } }
33b1c1b3218ee37175413f4eee5e7dcec8023478
[ "Markdown", "C#" ]
49
C#
AnshukAggarwal/HumberAreaHospital
a6126d280329e72c50c42c295a695b9e48647f2f
37e129087f364b7e6d9ae2313c493e4c2b21f9fe
refs/heads/master
<file_sep>#!/usr/bin/env node --harmony var fs = require('fs'); var program = require('commander'); var chalk = require('chalk'); var opentype = require('opentype.js'); var outputFileName = 'output.json' program .arguments('<file>') .option('-o, --output <filename>', 'The output filename, default: output.json') .action(function(file) { if (program.output) { outputFileName = program.output; } var font = opentype.loadSync(file); var html, tablename, table, property, value; // Array: name var names = font.tables['post']['names'].filter ( function(x) { return x.length !== 0 }); // Object : key - hex ,value - index var indexMap = font.tables['cmap']['glyphIndexMap']; // process var sortable = []; for (var key in indexMap) { sortable.push([key, indexMap[key]]); } sortable.sort(function(a, b) { return a[1] - b[1]; }); //output json var json = {}; for (var i = 0 ; i < sortable.length; i++) { var value = sortable[i][0]; var key = names[i]; json[key] = Number(value); } var jsonContent = JSON.stringify(json); fs.writeFile(outputFileName, jsonContent, 'utf8', function (err) { if (err) { console.log(chalk.red("An error occured while writing JSON Object to File.")); return console.log(chalk.red(err)); } console.log(chalk.green("success")); }); }) .parse(process.argv);<file_sep># iconfont2json ## Preview iconfont2json is a cli tool that can convert name and code of ttf to json. This json can be used in react-native-vector-icons for custom icons. if you have two icon in ttf , one is github logo and another is twitter logo. so json content : ```json {"github":60143,"twitter":60144,} ``` ## How to use **install** ``` npm install iconfont2json ``` in shell ``` iconfont2json some.ttf ``` default save json content to output.file. Or you can specify a file name by using the -o parameter. ## License MIT
b2bcb4b9c2cb03bdcbc76ac630d5ae27c0f0853b
[ "JavaScript", "Markdown" ]
2
JavaScript
EvoIos/iconfont2json
db0ac0ab35e4bd402ab7a413dc869f0a872adc07
5fd0db97be4d2877ba8b4fa7694f76a6f1dcf4ca
refs/heads/master
<repo_name>rammak/netsim<file_sep>/netstack/l2_ethernet.py from netstack.common import * def type_to_str(ether_type: int): if ether_type == 0x0800: return "IPv4" elif ether_type == 0x0806: return "ARP" elif ether_type == 0x0842: return "Wake-on-LAN" elif ether_type == 0x86DD: return "IPv6" else: return "Unknown" class frame_ethernet: mac_dst = bytearray(6) mac_src = bytearray(6) ether_type = 0 payload = bytearray() fcs = bytearray(4) length = 0 def __init__(self): pass def set(self, mac_dst: bytearray, mac_src: bytearray, payload: bytes, ether_type: int = bytearray(b'\x08\x00')): if len(mac_dst) != 6 or len(mac_src) != 6: return None self.mac_src = mac_src self.mac_dst = mac_dst self.ether_type = ether_type self.payload = payload def get(self, data : bytes): self.mac_dst = data[:6] self.mac_src = data[6:12] self.ether_type = (data[12] << 8) + data[13] self.payload = data[14:] def print_header(self): print("Dst : ", hex_to_str(self.mac_dst), "\tSrc : ", hex_to_str(self.mac_src), "\tType : ", type_to_str(self.ether_type)) <file_sep>/netstack/common.py def hex_to_str(hex_array: bytes): out = "" for i in range(len(hex_array)): out += "{0:0{1}x}".format(hex_array[i], 2) + ':' return out[:-1] def str_to_hex(string: str): temp = str.split(':') out = bytearray(6) for i in range(len(temp)): out[i] = int(temp[i], 16) return out def str_to_ip(string: str): temp = string.split('.') if len(temp) != 4: return None out = bytearray(4) for i in range(4): out[i] = int(temp[i]) return out def ip_to_str(ip: bytes): out = "" for i in range(4): out += str(ip[i]) + "." return out[:-1] <file_sep>/netstack/l0_interface.py import subprocess def check_dummy_module(): lsmod = subprocess.Popen(['sudo', 'lsmod'], stdout=subprocess.PIPE) grep = subprocess.run(['grep', 'dummy'], stdin=lsmod.stdout) lsmod.wait() if grep.returncode == 0: return True else: return False def load_dummy_module(unload=False): if unload is False: print("Loading dummy module...") mod = subprocess.run(['sudo', 'modprobe', 'dummy']) else: print("Removing dummy module...") mod = subprocess.run(['sudo', 'rmmod', 'dummy']) class VirtualInterface: interface_name = None def __init__(self, name): # todo: test for valid name self.interface_name = name if check_dummy_module(): print("Dummy module is already loaded") else: load_dummy_module() def __del__(self): print("Deleting interface ", self.interface_name) load_dummy_module(unload=True) def initialize(self, ip_address): print("Initializing virtual interface ", self.interface_name, " with IP ", ip_address) link = subprocess.run(['sudo', 'ip', 'link', 'add', self.interface_name, 'type', 'dummy']) # todo: change mac using "sudo ifconfig eth10 hw ether 00:22:22:ff:ff:ff" # todo: test for valid ip address ip = subprocess.run(['sudo', 'ip', 'addr', 'add', ip_address, 'brd', '+', 'dev', self.interface_name, 'label', self.interface_name + ':0']) <file_sep>/main.py from netstack.l1_interface import Interface from netstack.l2_ethernet import frame_ethernet i = Interface(interface_name='dum0') while True: f = i.receive() fe = frame_ethernet() fe.get(f) fe.print_header() <file_sep>/netstack/l1_interface.py import socket ETH_P_ALL = 3 MAX_PKT_SIZE = 4096 class Interface: name = None rawSocket = None def __init__(self, interface_name): print("Initializing interface...") self.name = interface_name self.rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL)) self.rawSocket.bind((self.name, 0)) def receive(self): return self.rawSocket.recv(MAX_PKT_SIZE) def send(self, data): return self.rawSocket.send(data) def __del__(self): print("Deinitializing ethernet...") self.rawSocket.close() <file_sep>/netstack/device.py from enum import Enum from netstack.l1_interface import Interface class DeviceType(Enum): TYPE_HOST = 1 TYPE_L0 = 2 TYPE_L1 = 3 TYPE_L2 = 4 TYPE_L3 = 5 class NetDevice: type = None name = None l1 = None def __init__(self, device_name, device_type: DeviceType = DeviceType['TYPE_HOST']): # todo: test for device type and name validity self.type = device_type self.name = device_name print("Initializing ", device_name, " of ", device_type) def add_interface(self, name): self.l1 = Interface(name) def __del__(self): pass
8068a9a3107ee82b506e7049897085af8e59c66f
[ "Python" ]
6
Python
rammak/netsim
734d204e39296b55219dbaee84d41164ada68433
435d2f333cf37e2dbe89480c2d77b1ab36d9af07
refs/heads/master
<file_sep>import mechanize import cookielib # import lxml.html as lh import time import random import threading from sets import Set import socket import sys #timeout in seconds see http://docs.python.org/library/socket.html#socket.setdefaulttimeout # import lxml; br = mechanize.Browser() # cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1)Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] try: #LOGIN PAGE: print "running on python"; r=br.open('https://wwws.mint.com/login.event?task=L'); html=r.read() # doc=lh.fromstring(html) formcount=0 # There are ~4 forms on this page. Pick out the one with the title form-login: for frm in br.forms(): if str(frm.attrs["id"])=="form-login": break formcount=formcount+1 br.select_form(nr=formcount) br.form['username']='<EMAIL>' br.form['password']='<PASSWORD>' r=br.submit(); print "first form submitted" #Sleep a bit so they don't suspect you're a bot sooner than they otherwise would. time.sleep(2.0); html2=r.read() thislink=0 for link in br.links(): #print link.text; if link.text=="Investments": thislink=link formcount=formcount+1; #Sleep a bit so they don't suspect you're a bot sooner than they otherwise would. time.sleep(2.0); #Follow the link to investments: r=br.follow_link(thislink) print "link followed" html3=r.read(); print html3; except Exception: print Exception.message <file_sep>Rewards_app =========== Users with multiple credit card information get recommendations on the optimal card at Point of sale to maximize reward benefits. Team Prashanth Jayanth Sreenivas Pratik
f69475ccf674d951bf275dce4bf33aadcfb0e6b8
[ "Markdown", "Python" ]
2
Python
jaysetty/Rewards_app
8d281aa1505b31aefc3ecc69dc133605b83df68a
9019bb5c6f5a1088a0b90be092811245ff11efc0
refs/heads/master
<repo_name>desktophero/postgres-replication-cookbook<file_sep>/CHANGELOG.md # 0.2.1 * Fix archiving # 0.2.0 * Listen on primary IP by default # 0.1.0 * Initial Commit <file_sep>/test/integration/master/archive_spec.rb # Make sure we have no archive command errors describe file('/var/lib/postgresql/9.3/main/mnt/server/archivedir/000000010000000000000001') do it { should exist } end
a3950a968dd7d966d394d16dfa9353ec2f63fa88
[ "Markdown", "Ruby" ]
2
Markdown
desktophero/postgres-replication-cookbook
0cb330e7c3b8a23409d6827990323dbc1d5bad6a
7b9b6f48379c9e16b3de60bd3b53a0b4c487ffa9
refs/heads/master
<file_sep>package company.com.dtos; import company.com.helpers.TestUser; import company.com.core.SeleniumCore; import java.util.ArrayList; import java.util.List; public class TestBaseDto { private SeleniumCore driver; private TestUser testUser; private List<String> reservedUserNames = new ArrayList<>(); public SeleniumCore getDriver() { return driver; } public void setDriver(SeleniumCore driver) { this.driver = driver; } public TestUser getTestUser() { return testUser; } public void setTestUser(TestUser testUser) { this.testUser = testUser; } public List<String> getReservedUserNames() { return reservedUserNames; } public void addReservedUserName(String reservedUserName) { reservedUserNames.add(reservedUserName); } } <file_sep>package company.com.extentReports; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import java.util.HashMap; import java.util.Map; public class ExtentTestManager { private static Map extentTestMap = new HashMap(); private static ExtentReports extent = ExtentManager.getReporter(); private static synchronized ExtentTest getTest() { return (ExtentTest) extentTestMap.get((int) (long) (Thread.currentThread().getId())); } public static synchronized void endTest() { extent.endTest((ExtentTest) extentTestMap.get((int) (long) (Thread.currentThread().getId()))); } public static synchronized ExtentTest startTest(String testName) { ExtentTest test = extent.startTest(testName); extentTestMap.put((int) (long) (Thread.currentThread().getId()), test); return test; } public synchronized static void log(LogStatus s1, String message) { getTest().log(s1, message); } public synchronized static void logWithScreenShot(LogStatus s1, String message, String screenShotPath) { try { getTest().log(s1, message); getTest().log(s1, ExtentTestManager.getTest().addScreenCapture(screenShotPath)); } catch (Exception e) { e.printStackTrace(); } } }<file_sep>package company.com.core; import company.com.constants.SeleniumCoreConstants; import io.github.bonigarcia.wdm.ChromeDriverManager; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.SystemUtils; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; public class SeleniumCore { private static final Logger LOG = LoggerFactory.getLogger(SeleniumCore.class); private static final String SCREENSHOT_PATH = "target/screenshots/"; private static final String CHROME_DRIVER_DOCKER_PATH = "/usr/bin/chromedriver"; private final File downloadDir; private final WebDriver driver; private final WebDriverWait wait; private ChromeDriverService driverService; public SeleniumCore() { downloadDir = new File(SeleniumCoreConstants.FILE_DOWNLOAD_DIR); if (!downloadDir.exists()) { downloadDir.mkdir(); } if (SystemUtils.IS_OS_WINDOWS) { driver = initializeDriverSession(); } else { driver = initializeHeadlessDriverSession(); } driver.manage().window().setSize(new Dimension(1366, 768)); wait = new WebDriverWait(driver, 80, 2000); } private static File prepareScreenshotFile(String methodName) { Date date = new Date(); Timestamp currentTime = new Timestamp(date.getTime()); String fileDate = SeleniumCoreConstants.PATTERN_COLON.matcher(currentTime.toString()).replaceAll("-"); String fileName = SeleniumCoreConstants.PATTERN_SPACE.matcher(fileDate).replaceAll("_") + '_' + methodName + ".png"; String absoluteFileName = SCREENSHOT_PATH + fileName; return new File(absoluteFileName); } private WebDriver initializeDriverSession() { ChromeDriverManager.getInstance().setup(); Map<String, Object> chromePrefs = new HashMap<>(); chromePrefs.put("profile.default_content_settings.popups", 0); chromePrefs.put("download.default_directory", downloadDir.getAbsolutePath()); chromePrefs.put("download.prompt_for_download", false); ChromeOptions browserOptions = new ChromeOptions(); browserOptions.setExperimentalOption("prefs", chromePrefs); browserOptions.addArguments("--disable-extensions"); browserOptions.addArguments("--no-sandbox"); return new ChromeDriver(browserOptions); } private WebDriver initializeHeadlessDriverSession() { System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_DOCKER_PATH); Map<String, Object> chromePrefs = new HashMap<>(); chromePrefs.put("download.directory_upgrade", true); chromePrefs.put("profile.default_content_settings.popups", 0); chromePrefs.put("download.default_directory", downloadDir.getAbsolutePath()); chromePrefs.put("download.prompt_for_download", false); Map<String, Object> commandParams = new HashMap<>(); commandParams.put("cmd", "Page.setDownloadBehavior"); commandParams.put("params", chromePrefs); ChromeOptions browserOptions = new ChromeOptions(); browserOptions.setExperimentalOption("prefs", commandParams); browserOptions.addArguments("--disable-extensions"); browserOptions.addArguments("--no-sandbox"); browserOptions.addArguments("--dns-prefetch-disable"); browserOptions.addArguments("--headless"); browserOptions.addArguments("--disable-gpu"); browserOptions.addArguments("--hide-scrollbars"); driverService = ChromeDriverService.createDefaultService(); return new ChromeDriver(driverService, browserOptions); } public WebDriver getDriver() { return driver; } public WebDriverWait getWait() { return wait; } public void cleanWebDriverSession() { driver.manage().deleteAllCookies(); } public void navigate(String URL) { if (System.getProperty("environment") == null) { driver.get(SeleniumCoreConstants.HTTP_ENV_ADDRESS + URL); } else { driver.get(System.getProperty("environment") + URL); } } public void waitForPageLoad() { waitForDocumentReadyStateComplete(); waitForButtonsVisibility(); } private void waitForButtonsVisibility() { wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(".//*[@class = 'mouseOut']"))); } public void updateWindowReadyStateToLoading() { executeScript("document.readyState = 'loading';"); } private void switchToFrame(String frameId) { driver.switchTo().frame(frameId); waitForDocumentReadyStateComplete(); } private void switchToDefaultFrame() { driver.switchTo().defaultContent(); waitForDocumentReadyStateComplete(); } public void close() { driver.close(); } public void waitForDocumentReadyStateComplete() { wait.until((ExpectedCondition<Boolean>) d -> Objects .equals(executeScript("return document.readyState"), "complete")); } private Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } public boolean isElementDisplayed(String xpath) { return !driver.findElements(By.xpath(xpath)).isEmpty(); } public void overwriteInputFieldValueWithoutScroll(WebElement inputField, String value) { if (value.isEmpty()) { inputField.sendKeys(Keys.chord(Keys.CONTROL, "a"), Keys.DELETE); } else { inputField.sendKeys(Keys.chord(Keys.CONTROL, "a"), value); } } public String takeScreenshot(String methodName) { driver.manage().window().setSize(new Dimension(1366, 13600)); TakesScreenshot takesScreenshot = (TakesScreenshot) driver; File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE); File screenshotFile = prepareScreenshotFile(methodName); try { FileUtils.copyFile(scrFile, screenshotFile); } catch (IOException e) { LOG.error("Unable to create screenshot", e); } return screenshotFile.getAbsolutePath(); } public void sleep(int seconds) { try { TimeUnit.SECONDS.sleep(seconds); } catch (InterruptedException e) { throw new IllegalStateException(e); } } public void clickAndWaitForPageLoad(WebElement element) { element.click(); waitForPageLoad(); } public void clickAndWaitForPageLoadWithFrameChange(WebElement element, String frameId) { element.click(); waitForPageLoad(); switchToFrame(frameId); } public void clickAndWaitForPageLoadWithBackToDefaultFrame(WebElement element) { element.click(); waitForPageLoad(); switchToDefaultFrame(); } public void clickElement(WebElement element) { element.click(); } public void scrollToElement(WebElement element) { executeScript("arguments[0].scrollIntoView({behavior: 'instant', block: 'end', inline: 'end'});", element); } public WebElement findElement(By by) { return driver.findElement(by); } } <file_sep>package company.com.dtos; public class NewUserDto { private String firstName; private String lastName; private int phoneNumber; private String email; private String address; private String city; private String state; private int postalCode; private String countryName; private String userName; private String password; public NewUserDto(String firstName, String lastName, int phoneNumber, String email, String address, String city, String state, int postalCode, String countryName, String userName, String password) { this.firstName = firstName; this.lastName = lastName; this.phoneNumber = phoneNumber; this.email = email; this.address = address; this.city = city; this.state = state; this.postalCode = postalCode; this.countryName = countryName; this.userName = userName; this.password = <PASSWORD>; } public String getFirstName() { return firstName; } public NewUserDto setFirstName(String firstName) { this.firstName = firstName; return this; } public String getLastName() { return lastName; } public NewUserDto setLastName(String lastName) { this.lastName = lastName; return this; } public int getPhoneNumber() { return phoneNumber; } public NewUserDto setPhoneNumber(int phoneNumber) { this.phoneNumber = phoneNumber; return this; } public String getEmail() { return email; } public NewUserDto setEmail(String email) { this.email = email; return this; } public String getAddress() { return address; } public NewUserDto setAddress(String address) { this.address = address; return this; } public String getCity() { return city; } public NewUserDto setCity(String city) { this.city = city; return this; } public String getState() { return state; } public NewUserDto setState(String state) { this.state = state; return this; } public int getPostalCode() { return postalCode; } public NewUserDto setPostalCode(int postalCode) { this.postalCode = postalCode; return this; } public String getCountryName() { return countryName; } public NewUserDto setCountryName(String countryName) { this.countryName = countryName; return this; } public String getUserName() { return userName; } public NewUserDto setUserName(String userName) { this.userName = userName; return this; } public String getPassword() { return password; } public NewUserDto setPassword(String password) { this.password = <PASSWORD>; return this; } } <file_sep>package company.com.constants; import java.time.format.DateTimeFormatter; public class DateTimeConstants { public static final DateTimeFormatter AMERICAN_DATE_FORMATTER = DateTimeFormatter.ofPattern("MM-dd-yyyy"); }<file_sep>package company.com.tests; import company.com.constants.SeleniumCoreConstants; import company.com.dtos.StarWarsCharactersDto; import company.com.rest.RestHandler; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertEquals; public class RestAPITest extends TestBase { @Test(groups = SeleniumCoreConstants.CUSTOMER_GROUP, description = "TC - Verify first Star Wars Character- ") public void useRestSpec() { RestHandler restHandler = new RestHandler(); StarWarsCharactersDto starWarsCharactersDto = restHandler.useSpec("people/" + 1 + "/"); assertEquals("Wrong character name", "<NAME>", starWarsCharactersDto.getName()); } } <file_sep>package company.com.core; import company.com.constants.SeleniumCoreConstants; import company.com.constants.StatusesConstants; import company.com.dtos.TestBaseDto; import company.com.helpers.TestUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class SuiteContext { private static final Logger LOG = LoggerFactory.getLogger(SuiteContext.class); private static SuiteContext suiteContext; private static List<String> reservedUserNames; private SuiteContext() { reservedUserNames = new ArrayList<>(); LOG.info("SELENIUM TEST: new SuiteContext instance was created"); } public static synchronized SuiteContext getInstance() { if (suiteContext == null) { suiteContext = new SuiteContext(); } return suiteContext; } public synchronized TestUser fetchAndReserveUser(TestBaseDto testBaseDto, String userAccessLevel) { LocalDateTime timeout = LocalDateTime.now().plusSeconds(SeleniumCoreConstants.CHECK_AVAILABILITY_TIMEOUT_IN_SECONDS); while (LocalDateTime.now().isBefore(timeout)) { for (String userName : SeleniumCoreConstants.USER_NAMES) { if (!reservedUserNames.contains(userName)) { reservedUserNames.add(userName); testBaseDto.addReservedUserName(userName); LOG.info("SELENIUM TEST: user '" + userName + "' was reserved; all reserved users - (" + reservedUserNames + ')'); String userPassword = Objects.equals(StatusesConstants.CUSTOMER_ACCESS_LEVEL, userAccessLevel) ? SeleniumCoreConstants.CUSTOMER_PASSWORD : SeleniumCoreConstants.WORKER_PASSWORD; return new TestUser(userName, userPassword); } } testBaseDto.getDriver().sleep(10); } throw new IllegalStateException( "SELENIUM TEST: no available user; found users - (" + SeleniumCoreConstants.USER_NAMES + "); all reserved users - (" + reservedUserNames + ')'); } public synchronized void cancelUsersReservation(List<String> userNames) { if (!userNames.isEmpty()) { reservedUserNames.removeAll(userNames); LOG.info("SELENIUM TEST: reservation for users was canceled (" + userNames + "); all reserved users - (" + reservedUserNames + ')'); } } public static synchronized int generateRandomPhone() { return (int) ((Math.random() * 900000000) + 100000000); } public static synchronized int generateRandomPostalCode() { return (int) ((Math.random() * 900000) + 100000); } } <file_sep>package company.com.blueprints; import company.com.core.SeleniumCore; import org.openqa.selenium.By; import org.openqa.selenium.support.PageFactory; public class DashboardBlueprint { protected SeleniumCore driver; private static final String REGISTER_BUTTON_XPATH = ".//*[contains(text(), 'REGISTER')]"; private static final String FIND_FLIGHT_PANE_XPATH = ".//*[@name = 'findflight']"; private static final String WELCOME_NEW_USER_XPATH = ".//*[contains(text(), ' Note: Your user name is')]"; private static final String HOME_PANE_XPATH = ".//*[@name = 'home']"; public DashboardBlueprint(SeleniumCore driver) { this.driver = driver; this.driver.waitForDocumentReadyStateComplete(); PageFactory.initElements(driver.getDriver(), this); } public boolean isFindFlightPaneDisplayed() { return driver.isElementDisplayed(FIND_FLIGHT_PANE_XPATH); } public boolean isHomePaneDisplayed() { return driver.isElementDisplayed(HOME_PANE_XPATH); } public void clickRegisterButton() { driver.clickAndWaitForPageLoad(driver.findElement(By.xpath(REGISTER_BUTTON_XPATH))); } public boolean isWelcomeNewRegisteredUserInfoDisplayed() { return driver.isElementDisplayed(WELCOME_NEW_USER_XPATH); } } <file_sep>package company.com.pageobjects; import company.com.blueprints.LogInBlueprint; import company.com.core.SeleniumCore; import company.com.dtos.TestBaseDto; import company.com.helpers.TestUser; public class LogInPageObject { final SeleniumCore driver; final TestBaseDto testBaseDto; private final LogInBlueprint logInBlueprint; public LogInPageObject(TestBaseDto testBaseDto) { this.testBaseDto = testBaseDto; driver = this.testBaseDto.getDriver(); logInBlueprint = new LogInBlueprint(this.testBaseDto.getDriver()); } public LogInBlueprint getBlueprint() { return logInBlueprint; } public void logInAndWaitForNewPage(TestUser user) { logIn(user); logInBlueprint.waitForPageLoad(); } public void logIn(TestUser user) { logInBlueprint.overwriteUsernameText(user.getLogin()); logInBlueprint.overwritePasswordText(user.getPassword()); logInBlueprint.clickLogInButton(); } } <file_sep>package company.com.db; import org.skife.jdbi.v2.DBI; public interface DaoBase { default void close(DBI dbi) { dbi.close(this); } } <file_sep>package company.com.pageobjects; import company.com.blueprints.RegisterBlueprint; import company.com.core.SeleniumCore; import company.com.dtos.NewUserDto; import company.com.dtos.TestBaseDto; import static org.easetech.easytest.util.GeneralUtil.convertToString; public class RegisterPageObject { final SeleniumCore driver; final TestBaseDto testBaseDto; private RegisterBlueprint registerBlueprint; public RegisterPageObject(TestBaseDto testBaseDto) { this.testBaseDto = testBaseDto; driver = this.testBaseDto.getDriver(); registerBlueprint = new RegisterBlueprint(this.testBaseDto.getDriver()); } public RegisterBlueprint getBlueprint() { return registerBlueprint; } public void fillRegisterForm(NewUserDto newUserDto) { provideContactData(newUserDto); provideMailingData(newUserDto); provideUserInfoData(newUserDto); } private void provideContactData(NewUserDto newUserDto) { driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getFirstName(), newUserDto.getFirstName()); driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getLastName(), newUserDto.getLastName()); driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getPhone(), convertToString(newUserDto.getPhoneNumber())); driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getEmail(), newUserDto.getEmail()); } private void provideMailingData(NewUserDto newUserDto) { driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getAddres(), newUserDto.getAddress()); driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getCity(), newUserDto.getCity()); driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getState(), newUserDto.getState()); driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getPostal(), convertToString(newUserDto.getPostalCode())); getBlueprint().selectCountry(newUserDto.getCountryName()); } private void provideUserInfoData(NewUserDto newUserDto) { driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getUserName(), newUserDto.getUserName()); driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getPassword(), newUserDto.getPassword()); driver.overwriteInputFieldValueWithoutScroll(getBlueprint().getConfirmPassword(), newUserDto.getPassword()); } } <file_sep>package company.com.constants; public class StatusesConstants { public static final String CUSTOMER_ACCESS_LEVEL = "CUSTOMER"; public static final String INVALID_USER_ACCESS_LEVEL = "INVALID"; private StatusesConstants() { } } <file_sep># WebAppTestFramework This is a framework which can be used for WEB APP and REST API testing. # Technologies/tools - Java, - mvn, - TestNG, - ExtentReports, - restAssured, - AssertJ, - log4J. This framework is based on Page object Model with some modifications. It allows You to run automated Web app and Web API tests in parallel. Screenshots and reporting included. It handles race condition with user reservation for parallel tests. It can be easily integrated with CI/CD and also is prepared for connection to database. In this framework You can find various ways of locating elements on pages and it also fits for frame based apps. # QUICK START To start using it, You only need to have installed java sdk ("1.8.0_181"), chrome, mvn (apache-maven-3.5.4) and Java IDE (I preffer IntelliJ) --(tools vers. can be upgraded) 1. Download source code. 2. Open it in IDE. 3. Enable auto-import functionality and let mvn resolve all dependencies. 4. Right click on "testScope.xml" and click Run. 5. Report can be found under /target/report/ 6. Scrreenshots can be found under /target/screenshots 7. Feel free to break tests and try to write more. # Example of test report: ![My image](https://github.com/kwolkowicz/WebAppTestFramework/blob/master/reportResults.PNG) <file_sep>package company.com.tests; import company.com.constants.SeleniumCoreConstants; import company.com.constants.StatusesConstants; import company.com.core.TestBaseManager; import company.com.dtos.TestBaseDto; import company.com.pageobjects.DashboardPageObject; import org.testng.annotations.Test; import static org.junit.Assert.assertFalse; import static org.testng.AssertJUnit.assertTrue; public class LogInTest extends TestBase { @Test(groups = SeleniumCoreConstants.CUSTOMER_GROUP, description = "TC - log in as customer - ") public void logInCustomer() { TestBaseDto testBaseDto = TestBaseManager.fetchTestBaseInstance(); initializeTest(testBaseDto, StatusesConstants.CUSTOMER_ACCESS_LEVEL); DashboardPageObject dashboardPageObject = new DashboardPageObject(testBaseDto); assertTrue("Wrong page loaded", dashboardPageObject.getBlueprint().isFindFlightPaneDisplayed()); } @Test(groups = SeleniumCoreConstants.CUSTOMER_GROUP, description = "TC - log in with invalid credentials - ") public void logInUserInvalidCredentials() { TestBaseDto testBaseDto = TestBaseManager.fetchTestBaseInstance(); initializeTest(testBaseDto, StatusesConstants.INVALID_USER_ACCESS_LEVEL); DashboardPageObject dashboardPageObject = new DashboardPageObject(testBaseDto); assertFalse("Wrong page loaded!", dashboardPageObject.getBlueprint().isFindFlightPaneDisplayed()); } } <file_sep>package company.com.db; import company.com.daos.dbDao; public enum DaoProvider { DAO_PROVIDER; private final dbDao dbDao; DaoProvider() { DbManager dbManager = new DbManager(); dbDao = dbManager.getDbDao(); dbManager.close(); } public dbDao getDbDao() { return dbDao; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <groupId>jeppesen.com</groupId> <artifactId>SeleniumTests</artifactId> <version>1.0-SNAPSHOT</version> <modelVersion>4.0.0</modelVersion> <name>SeleniumTests</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.9.1</version> </dependency> <dependency> <groupId>io.github.bonigarcia</groupId> <artifactId>webdrivermanager</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.easetech</groupId> <artifactId>easytest-core</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> <version>1.4.01</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.9.10</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.antlr</groupId> <artifactId>stringtemplate</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-chrome-driver</artifactId> <version>3.14.0</version> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <exclusions> <exclusion> <artifactId>hamcrest-core</artifactId> <groupId>org.hamcrest</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.11.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jdbi</groupId> <artifactId>jdbi</artifactId> <version>2.73</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.3-1100-jdbc41</version> </dependency> <dependency> <groupId>com.relevantcodes</groupId> <artifactId>extentreports</artifactId> <version>2.41.2</version> </dependency> </dependencies> <build> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build> </project>
dea9ae3fbfffb4067cd88d82bfbe043144b0101a
[ "Markdown", "Java", "Maven POM" ]
16
Java
kwolkowicz/WebAppTestFramework
150cb33178b009e604b90ff044ebe094838bfd91
0158570896196b3ec4a081f5419216f349e91be8
refs/heads/master
<file_sep># Функция возвращает датафрейм с наблюдениями только для указанных генов. test_data <- as.data.frame(list(name = c("p4@HPS1", "p7@HPS2", "p4@HPS3", "p7@HPS4", "p7@HPS5", "p9@HPS6", "p11@HPS7", "p10@HPS8", "p15@HPS9"), expression = c(118.84, 90.04, 106.6, 104.99, 93.2, 66.84, 90.02, 108.03, 111.83))) names <- c("HPS5", "HPS6", "HPS9", "HPS2", "HPS3", "HPS7", "HPS4", "HPS8") my_names <- function (dataset, names){ matches <- paste(names, collapse = "|") dataset[grepl(matches, dataset[[1]]), ] } my_names(test_data, names) # В этой задаче мы хотели бы вытащить из каждого списка только значение p - value. # То есть получить новый список или вектор только с одним показателем (p - value) для каждой переменной. normality_tests_p <- lapply(iris[, 1:4], shapiro.test) s2 <- sapply(normality_tests, '[') s2[2,] # Напишите функцию one_sample_t, которая получает на вход два аргумента: # 1. Dataframe произвольного размера с произвольным числом переменных различного типа. # 2. Числовое значение среднего в генеральной совокупности. # Ваша функция должна применять одновыборочный t - test к каждой числовой переменной в данных, и сравнивать среднее # значение этой переменной с указанным значением среднего в генеральной совокупности (второй аргумент функции). # Функция должна возвращать список, где каждый элемент это вектор, состоящий из t - значения, числа степеней свобод # (df) и значения p - value. one_sample_t <- function(test_data, general_mean){ tested <- test_data[sapply(test_data, is.numeric)] res <- lapply(tested, function(x) c(t.test(x,mu=general_mean)$statistic,t.test(x,mu=general_mean)$parameter, t.test(x,mu=general_mean)$p.value)) return(res) } one_sample_t(iris[, 1:4], 4)
a05bb59687db3f307e61a7abe94b9cbad743f087
[ "R" ]
1
R
grigorevmp/R_Stepic_tasks
2aa9b0d7bbe3642fd04c278eeb39b88ee3ae5086
2820559fed29a190fdc8fa8655adff15b4dc0af9
refs/heads/master
<repo_name>nuochan/a1<file_sep>/assignment1/main.cpp // // main.cpp // assignment 1 // Name:<NAME> // Student ID:200327119 // // Created by <NAME> on 1/19/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #include <iostream> using namespace std; int main() { //declair variables and initialization const float annualInterestRate = 0.05; float monthlyInterestRate = annualInterestRate / 12; int deposite = 0; float balance = 0; int depositeMonth = 6; //prompt user to input monthly deposit. cout << "How much would you like to deposit each month?" << endl; cin >> deposite; //for loop to calculate final balance for(int n = 0;n < depositeMonth ; n++ ) { balance = ( deposite + balance ) * ( 1 + monthlyInterestRate ); } //output balance cout << "Your balance after " << depositeMonth << " months will be " << balance << " dollar." << endl; return 0; }
e34af8213e04c8e8a03700fbc545240ef8c9b8bc
[ "C++" ]
1
C++
nuochan/a1
14f3f297eed5062c19d756513b24740a15de50c1
05c12e5972f30c8f0f2e7bb3c64825adbc9d1b87
refs/heads/master
<repo_name>deus-amd/microsoft-ui-xaml<file_sep>/dev/Generated/InfoBarPanel.properties.cpp // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // DO NOT EDIT! This file was generated by CustomTasks.DependencyPropertyCodeGen #include "pch.h" #include "common.h" #include "InfoBarPanel.h" namespace winrt::Microsoft::UI::Xaml::Controls::Primitives { CppWinRTActivatableClassWithDPFactory(InfoBarPanel) } #include "InfoBarPanel.g.cpp" GlobalDependencyProperty InfoBarPanelProperties::s_HorizontalMarginProperty{ nullptr }; GlobalDependencyProperty InfoBarPanelProperties::s_VerticalMarginProperty{ nullptr }; InfoBarPanelProperties::InfoBarPanelProperties() { EnsureProperties(); } void InfoBarPanelProperties::EnsureProperties() { if (!s_HorizontalMarginProperty) { s_HorizontalMarginProperty = InitializeDependencyProperty( L"HorizontalMargin", winrt::name_of<winrt::Thickness>(), winrt::name_of<winrt::InfoBarPanel>(), true /* isAttached */, ValueHelper<winrt::Thickness>::BoxedDefaultValue(), nullptr); } if (!s_VerticalMarginProperty) { s_VerticalMarginProperty = InitializeDependencyProperty( L"VerticalMargin", winrt::name_of<winrt::Thickness>(), winrt::name_of<winrt::InfoBarPanel>(), true /* isAttached */, ValueHelper<winrt::Thickness>::BoxedDefaultValue(), nullptr); } } void InfoBarPanelProperties::ClearProperties() { s_HorizontalMarginProperty = nullptr; s_VerticalMarginProperty = nullptr; } void InfoBarPanelProperties::SetHorizontalMargin(winrt::DependencyObject const& target, winrt::Thickness const& value) { target.SetValue(s_HorizontalMarginProperty, ValueHelper<winrt::Thickness>::BoxValueIfNecessary(value)); } winrt::Thickness InfoBarPanelProperties::GetHorizontalMargin(winrt::DependencyObject const& target) { return ValueHelper<winrt::Thickness>::CastOrUnbox(target.GetValue(s_HorizontalMarginProperty)); } void InfoBarPanelProperties::SetVerticalMargin(winrt::DependencyObject const& target, winrt::Thickness const& value) { target.SetValue(s_VerticalMarginProperty, ValueHelper<winrt::Thickness>::BoxValueIfNecessary(value)); } winrt::Thickness InfoBarPanelProperties::GetVerticalMargin(winrt::DependencyObject const& target) { return ValueHelper<winrt::Thickness>::CastOrUnbox(target.GetValue(s_VerticalMarginProperty)); } <file_sep>/dev/Generated/InfoBarPanel.properties.h // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // DO NOT EDIT! This file was generated by CustomTasks.DependencyPropertyCodeGen #pragma once class InfoBarPanelProperties { public: InfoBarPanelProperties(); static void SetHorizontalMargin(winrt::DependencyObject const& target, winrt::Thickness const& value); static winrt::Thickness GetHorizontalMargin(winrt::DependencyObject const& target); static void SetVerticalMargin(winrt::DependencyObject const& target, winrt::Thickness const& value); static winrt::Thickness GetVerticalMargin(winrt::DependencyObject const& target); static winrt::DependencyProperty HorizontalMarginProperty() { return s_HorizontalMarginProperty; } static winrt::DependencyProperty VerticalMarginProperty() { return s_VerticalMarginProperty; } static GlobalDependencyProperty s_HorizontalMarginProperty; static GlobalDependencyProperty s_VerticalMarginProperty; static void EnsureProperties(); static void ClearProperties(); };
93a4a5fae0fd4c3efb486580cb5b0e0a88178ae6
[ "C++" ]
2
C++
deus-amd/microsoft-ui-xaml
9acab7164700cb3dfcf1a66de96c41f900426646
3bf58ce5139286b785351dd3b0ecce448bdfee35
refs/heads/main
<repo_name>daniel-um/poc-node-api-addon<file_sep>/README.md ## how to use ### build, bundle, test - may first need to run `node-gyp configure` (try next step and see if it tells you to do this first) - `yarn build-addon && yarn transpile-and-bundle && yarn test` ## history ### add babel for es6 - `yarn add -D @babel/cli @babel/preset-env` for minimal babel - `yarn add -D babel-loader @babel/core` to transpile via webpack ### add webpack - `yarn add -D webpack webpack-cli node-loader` - `touch webpack.config.js` - move addon.js to src, rename to main.js - require statement now requires `.node` extension ### bare minimum node-api example - `.vscode/c_cpp_propeties` may need to be adjusted to find node_api.h<file_sep>/src/main.js const addon = require('../build/Release/addon.node'); const value = 8; console.log(`${value} times 2 equals`, addon.timesTwo(value)); console.log('returned object: ', addon.returnObject()); console.log('returned array: ', addon.returnArray());<file_sep>/addon.cc #include <addon.h> napi_value TimesTwo(napi_env env, napi_callback_info info) { napi_status status; size_t argc = 1; int number = 0; napi_value argv[1]; status = napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); if (status != napi_ok) { napi_throw_error(env, NULL, "Failed to parse arguments"); } status = napi_get_value_int32(env, argv[0], &number); if (status != napi_ok) { napi_throw_error(env, NULL, "Invalid number was passed as argument"); } napi_value myNumber; number = number * 2; status = napi_create_int32(env, number, &myNumber); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to create return value"); } return myNumber; } napi_value ReturnObject(napi_env env, napi_callback_info info) { napi_status status = napi_generic_failure; // const obj = {} napi_value obj, value; status = napi_create_object(env, &obj); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to create object"); } // Create a napi_value for 123 status = napi_create_int32(env, 123, &value); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to create integer"); } // obj.myProp = 123 status = napi_set_named_property(env, obj, "myProp", value); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to set named property"); } return obj; } napi_value ReturnArray(napi_env env, napi_callback_info info) { napi_status status = napi_generic_failure; // const arr = []; napi_value arr, value; status = napi_create_array(env, &arr); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to create array"); } // Create a napi_value for 'hello' status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &value); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to create string"); } // arr[123] = 'hello'; status = napi_set_element(env, arr, 123, value); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to set element"); } return arr; } napi_value Init(napi_env env, napi_value exports) { napi_status status; napi_value fn; status = napi_create_function(env, NULL, 0, TimesTwo, NULL, &fn); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to wrap native function"); } status = napi_set_named_property(env, exports, "timesTwo", fn); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to populate exports"); } status = napi_create_function(env, NULL, 0, ReturnObject, NULL, &fn); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to wrap native function"); } status = napi_set_named_property(env, exports, "returnObject", fn); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to populate exports"); } status = napi_create_function(env, NULL, 0, ReturnArray, NULL, &fn); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to wrap native function"); } status = napi_set_named_property(env, exports, "returnArray", fn); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to populate exports"); } return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
d896a196d69cd22d3a251101bd417c10b735a470
[ "Markdown", "JavaScript", "C++" ]
3
Markdown
daniel-um/poc-node-api-addon
d5a083baafd5c747d08be91d4b69cbcedc00590f
03a651d9ad53e3c829e1901407a6c44cc121f99a
refs/heads/master
<file_sep>package payrollsystem; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author <NAME> * @duedate */ public class PayrollSystemGUI extends javax.swing.JFrame { final int MANAGERS_PAYCODE = 1; final int HOURLY_WORKERS_PAYCODE = 2; final int COMMISSION_WORKERS_PAYCODE = 3; final int TAX = 7; // in percentage private int daysWorked = 0; private int hoursWorked = 0; private double grossSalary; Employee employee = new Employee(); DefaultTableModel model; /** * Creates new form PayrollSystemGUI */ public PayrollSystemGUI() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jDialogEmployeeEntry = new javax.swing.JDialog(); jPanel1 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jComboBoxEmpTypeEmpEntry = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); jTextFieldEmpNameEmpEntry = new javax.swing.JTextField(); jButtonSaveEmployee = new javax.swing.JButton(); jDialogEmployeeDetails = new javax.swing.JDialog(); jPanel2 = new javax.swing.JPanel(); jTextFieldRatePerHourEmpDetail = new javax.swing.JTextField(); jTextFieldDaysWorkedEmpDetail = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jTextFieldEmpNameEmpDetail = new javax.swing.JTextField(); jTextFieldTotalHoursWorkedEmpDetail = new javax.swing.JTextField(); jPanel5 = new javax.swing.JPanel(); jCheckBoxSaturdayEmpDetailFirstWk = new javax.swing.JCheckBox(); jCheckBoxMondayEmpDetailFirstWk = new javax.swing.JCheckBox(); jCheckBoxThursdayEmpDetailFirstWk = new javax.swing.JCheckBox(); jCheckBoxSaturdayEmpDetailSecondWk = new javax.swing.JCheckBox(); jCheckBoxWednesdayEmpDetailFirstWk = new javax.swing.JCheckBox(); jLabel25 = new javax.swing.JLabel(); jCheckBoxWednesdayEmpDetailSecondWk = new javax.swing.JCheckBox(); jCheckBoxFridayEmpDetailFirstWk = new javax.swing.JCheckBox(); jLabel26 = new javax.swing.JLabel(); jCheckBoxTuesdayEmpDetailFirstWk = new javax.swing.JCheckBox(); jCheckBoxTuesdayEmpDetailSecondWk = new javax.swing.JCheckBox(); jCheckBoxSundayEmpDetailFirstWk = new javax.swing.JCheckBox(); jCheckBoxMondayEmpDetailSecondWk = new javax.swing.JCheckBox(); jCheckBoxFridayEmpDetailSecondWk = new javax.swing.JCheckBox(); jCheckBoxSundayEmpDetailSecondWk = new javax.swing.JCheckBox(); jCheckBoxThursdayEmpDetailSecondWk = new javax.swing.JCheckBox(); jLabel2 = new javax.swing.JLabel(); jTextFieldCommissionSalesEmpDetail = new javax.swing.JTextField(); jTextFieldEmpDetailPayCode = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); jLabel24 = new javax.swing.JLabel(); jTextFieldTaxMonthlyWageEmpDetail = new javax.swing.JTextField(); jTextFieldEmpDetailNetSalary = new javax.swing.JTextField(); jTextFieldEmpDetailDeduction = new javax.swing.JTextField(); jLabel22 = new javax.swing.JLabel(); jLabel23 = new javax.swing.JLabel(); jTextFieldEmpDetailGrossSalary = new javax.swing.JTextField(); jLabel21 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jButtonViewPayCheck = new javax.swing.JButton(); jDialogPayCheck = new javax.swing.JDialog(); jScrollPane1 = new javax.swing.JScrollPane(); model = new DefaultTableModel(); jTablePayRoll = new javax.swing.JTable(model); jButtonAddEmployee = new javax.swing.JButton(); jDialogEmployeeEntry.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jDialogEmployeeEntry.setTitle("Employee Entry"); jDialogEmployeeEntry.setBounds(new java.awt.Rectangle(0, 0, 0, 0)); jDialogEmployeeEntry.setModal(true); jDialogEmployeeEntry.setResizable(false); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Employee details")); jLabel3.setText("Employee type:"); jComboBoxEmpTypeEmpEntry.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Manager", "Hourly Worker", "Commission Worker" })); jComboBoxEmpTypeEmpEntry.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxEmpTypeEmpEntryActionPerformed(evt); } }); jLabel1.setText("Employee name:"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTextFieldEmpNameEmpEntry) .addComponent(jComboBoxEmpTypeEmpEntry, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldEmpNameEmpEntry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jComboBoxEmpTypeEmpEntry) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jButtonSaveEmployee.setText("Add Employee"); jButtonSaveEmployee.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSaveEmployeeActionPerformed(evt); } }); javax.swing.GroupLayout jDialogEmployeeEntryLayout = new javax.swing.GroupLayout(jDialogEmployeeEntry.getContentPane()); jDialogEmployeeEntry.getContentPane().setLayout(jDialogEmployeeEntryLayout); jDialogEmployeeEntryLayout.setHorizontalGroup( jDialogEmployeeEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDialogEmployeeEntryLayout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDialogEmployeeEntryLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonSaveEmployee) .addContainerGap()) ); jDialogEmployeeEntryLayout.setVerticalGroup( jDialogEmployeeEntryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDialogEmployeeEntryLayout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonSaveEmployee) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jDialogEmployeeEntry.getAccessibleContext().setAccessibleDescription(""); jDialogEmployeeDetails.setTitle("Employee Details"); jDialogEmployeeDetails.setBounds(new java.awt.Rectangle(0, 0, 0, 0)); jDialogEmployeeDetails.setModal(true); jDialogEmployeeDetails.setResizable(false); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Employee details")); jPanel2.setToolTipText(""); jTextFieldRatePerHourEmpDetail.setText("0"); jTextFieldRatePerHourEmpDetail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldRatePerHourEmpDetailActionPerformed(evt); } }); jTextFieldDaysWorkedEmpDetail.setEditable(false); jTextFieldDaysWorkedEmpDetail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldDaysWorkedEmpDetailActionPerformed(evt); } }); jLabel14.setText("Rate Per Hour:"); jLabel15.setText("Total hours worked:"); jLabel16.setText("Employee name:"); jLabel17.setText("Pay code:"); jLabel18.setText("Number of days worked:"); jTextFieldEmpNameEmpDetail.setEditable(false); jTextFieldTotalHoursWorkedEmpDetail.setText("0"); jTextFieldTotalHoursWorkedEmpDetail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldTotalHoursWorkedEmpDetailActionPerformed(evt); } }); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Days worked")); jCheckBoxSaturdayEmpDetailFirstWk.setText("Saturday"); jCheckBoxSaturdayEmpDetailFirstWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxSaturdayEmpDetailFirstWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxSaturdayEmpDetailFirstWkActionPerformed(evt); } }); jCheckBoxMondayEmpDetailFirstWk.setText("Monday"); jCheckBoxMondayEmpDetailFirstWk.setToolTipText(""); jCheckBoxMondayEmpDetailFirstWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxMondayEmpDetailFirstWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxMondayEmpDetailFirstWkActionPerformed(evt); } }); jCheckBoxThursdayEmpDetailFirstWk.setText("Thursday"); jCheckBoxThursdayEmpDetailFirstWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxThursdayEmpDetailFirstWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxThursdayEmpDetailFirstWkActionPerformed(evt); } }); jCheckBoxSaturdayEmpDetailSecondWk.setText("Saturday"); jCheckBoxSaturdayEmpDetailSecondWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxSaturdayEmpDetailSecondWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxSaturdayEmpDetailSecondWkActionPerformed(evt); } }); jCheckBoxWednesdayEmpDetailFirstWk.setText("Wednesday"); jCheckBoxWednesdayEmpDetailFirstWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxWednesdayEmpDetailFirstWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxWednesdayEmpDetailFirstWkActionPerformed(evt); } }); jLabel25.setText("Second week"); jCheckBoxWednesdayEmpDetailSecondWk.setText("Wednesday"); jCheckBoxWednesdayEmpDetailSecondWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxWednesdayEmpDetailSecondWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxWednesdayEmpDetailSecondWkActionPerformed(evt); } }); jCheckBoxFridayEmpDetailFirstWk.setText("Friday"); jCheckBoxFridayEmpDetailFirstWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxFridayEmpDetailFirstWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxFridayEmpDetailFirstWkActionPerformed(evt); } }); jLabel26.setText("First week"); jCheckBoxTuesdayEmpDetailFirstWk.setText("Tuesday"); jCheckBoxTuesdayEmpDetailFirstWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxTuesdayEmpDetailFirstWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxTuesdayEmpDetailFirstWkActionPerformed(evt); } }); jCheckBoxTuesdayEmpDetailSecondWk.setText("Tuesday"); jCheckBoxTuesdayEmpDetailSecondWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxTuesdayEmpDetailSecondWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxTuesdayEmpDetailSecondWkActionPerformed(evt); } }); jCheckBoxSundayEmpDetailFirstWk.setText("Sunday"); jCheckBoxSundayEmpDetailFirstWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxSundayEmpDetailFirstWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxSundayEmpDetailFirstWkActionPerformed(evt); } }); jCheckBoxMondayEmpDetailSecondWk.setText("Monday"); jCheckBoxMondayEmpDetailSecondWk.setToolTipText(""); jCheckBoxMondayEmpDetailSecondWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxMondayEmpDetailSecondWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxMondayEmpDetailSecondWkActionPerformed(evt); } }); jCheckBoxFridayEmpDetailSecondWk.setText("Friday"); jCheckBoxFridayEmpDetailSecondWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxFridayEmpDetailSecondWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxFridayEmpDetailSecondWkActionPerformed(evt); } }); jCheckBoxSundayEmpDetailSecondWk.setText("Sunday"); jCheckBoxSundayEmpDetailSecondWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxSundayEmpDetailSecondWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxSundayEmpDetailSecondWkActionPerformed(evt); } }); jCheckBoxThursdayEmpDetailSecondWk.setText("Thursday"); jCheckBoxThursdayEmpDetailSecondWk.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jCheckBoxThursdayEmpDetailSecondWk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxThursdayEmpDetailSecondWkActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBoxMondayEmpDetailFirstWk) .addComponent(jLabel26) .addComponent(jCheckBoxWednesdayEmpDetailSecondWk) .addComponent(jCheckBoxFridayEmpDetailSecondWk) .addComponent(jCheckBoxThursdayEmpDetailFirstWk) .addComponent(jCheckBoxSundayEmpDetailSecondWk) .addComponent(jCheckBoxTuesdayEmpDetailFirstWk) .addComponent(jCheckBoxSaturdayEmpDetailFirstWk)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBoxWednesdayEmpDetailFirstWk) .addComponent(jCheckBoxThursdayEmpDetailSecondWk) .addComponent(jCheckBoxSundayEmpDetailFirstWk) .addComponent(jCheckBoxFridayEmpDetailFirstWk) .addComponent(jCheckBoxTuesdayEmpDetailSecondWk) .addComponent(jCheckBoxSaturdayEmpDetailSecondWk) .addComponent(jCheckBoxMondayEmpDetailSecondWk) .addComponent(jLabel25)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel26) .addComponent(jLabel25)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxMondayEmpDetailFirstWk) .addComponent(jCheckBoxMondayEmpDetailSecondWk)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxTuesdayEmpDetailFirstWk) .addComponent(jCheckBoxTuesdayEmpDetailSecondWk)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxWednesdayEmpDetailSecondWk) .addComponent(jCheckBoxWednesdayEmpDetailFirstWk)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxThursdayEmpDetailFirstWk) .addComponent(jCheckBoxThursdayEmpDetailSecondWk)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxFridayEmpDetailSecondWk) .addComponent(jCheckBoxFridayEmpDetailFirstWk)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxSaturdayEmpDetailFirstWk) .addComponent(jCheckBoxSaturdayEmpDetailSecondWk)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxSundayEmpDetailSecondWk) .addComponent(jCheckBoxSundayEmpDetailFirstWk)) .addGap(0, 0, Short.MAX_VALUE)) ); jLabel2.setText("Sales:"); jTextFieldCommissionSalesEmpDetail.setText("0"); jTextFieldCommissionSalesEmpDetail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldCommissionSalesEmpDetailActionPerformed(evt); } }); jTextFieldEmpDetailPayCode.setEditable(false); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(49, 49, 49) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel16, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel18, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel14, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldEmpNameEmpDetail) .addComponent(jTextFieldTotalHoursWorkedEmpDetail, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldDaysWorkedEmpDetail) .addComponent(jTextFieldRatePerHourEmpDetail) .addComponent(jTextFieldCommissionSalesEmpDetail) .addComponent(jTextFieldEmpDetailPayCode)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(37, 37, 37)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldEmpNameEmpDetail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel16)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel17) .addComponent(jTextFieldEmpDetailPayCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextFieldCommissionSalesEmpDetail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(jTextFieldRatePerHourEmpDetail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jTextFieldTotalHoursWorkedEmpDetail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel18) .addComponent(jTextFieldDaysWorkedEmpDetail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(8, 8, 8) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Deductions")); jLabel24.setText("Tax of Monthly Wage:"); jTextFieldTaxMonthlyWageEmpDetail.setText("7"); jTextFieldTaxMonthlyWageEmpDetail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldTaxMonthlyWageEmpDetailActionPerformed(evt); } }); jTextFieldEmpDetailNetSalary.setEditable(false); jTextFieldEmpDetailDeduction.setEditable(false); jLabel22.setText("Net Salary:"); jLabel23.setText("Gross Salary:"); jTextFieldEmpDetailGrossSalary.setEditable(false); jTextFieldEmpDetailGrossSalary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldEmpDetailGrossSalaryActionPerformed(evt); } }); jLabel21.setText("Total Deduction:"); jLabel6.setText("%"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel24, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel23, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel22, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldEmpDetailGrossSalary, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldEmpDetailNetSalary, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jTextFieldTaxMonthlyWageEmpDetail, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6)))) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel21) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextFieldEmpDetailDeduction, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(3, 3, 3))) .addGap(0, 0, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel24) .addComponent(jTextFieldTaxMonthlyWageEmpDetail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldEmpDetailGrossSalary, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel23)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel21) .addComponent(jTextFieldEmpDetailDeduction, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel22) .addComponent(jTextFieldEmpDetailNetSalary, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); jButtonViewPayCheck.setText("Calculate pay"); jButtonViewPayCheck.setToolTipText(""); jButtonViewPayCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonViewPayCheckActionPerformed(evt); } }); javax.swing.GroupLayout jDialogEmployeeDetailsLayout = new javax.swing.GroupLayout(jDialogEmployeeDetails.getContentPane()); jDialogEmployeeDetails.getContentPane().setLayout(jDialogEmployeeDetailsLayout); jDialogEmployeeDetailsLayout.setHorizontalGroup( jDialogEmployeeDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDialogEmployeeDetailsLayout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jDialogEmployeeDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDialogEmployeeDetailsLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDialogEmployeeDetailsLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonViewPayCheck))) .addContainerGap()) ); jDialogEmployeeDetailsLayout.setVerticalGroup( jDialogEmployeeDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDialogEmployeeDetailsLayout.createSequentialGroup() .addGap(11, 11, 11) .addGroup(jDialogEmployeeDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDialogEmployeeDetailsLayout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 19, Short.MAX_VALUE)) .addGroup(jDialogEmployeeDetailsLayout.createSequentialGroup() .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonViewPayCheck))) .addContainerGap()) ); jDialogPayCheck.setTitle("Pay Check"); jDialogPayCheck.setBackground(new java.awt.Color(255, 204, 51)); jDialogPayCheck.setBounds(new java.awt.Rectangle(0, 0, 340, 430)); jDialogPayCheck.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jDialogPayCheck.setModal(true); jDialogPayCheck.setResizable(false); javax.swing.GroupLayout jDialogPayCheckLayout = new javax.swing.GroupLayout(jDialogPayCheck.getContentPane()); jDialogPayCheck.getContentPane().setLayout(jDialogPayCheckLayout); jDialogPayCheckLayout.setHorizontalGroup( jDialogPayCheckLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 340, Short.MAX_VALUE) ); jDialogPayCheckLayout.setVerticalGroup( jDialogPayCheckLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 430, Short.MAX_VALUE) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Payroll System"); setBounds(new java.awt.Rectangle(0, 0, 0, 0)); setResizable(false); jTablePayRoll.setBorder(javax.swing.BorderFactory.createTitledBorder("")); // jTablePayRoll.setModel(new javax.swing.table.DefaultTableModel( // new Object [][] { // {null, null, null, null}, // {null, null, null, null}, // {null, null, null, null}, // {null, null, null, null} // }, // new String [] { // "Title 1", "Title 2", "Title 3", "Title 4" // } // ) { // boolean[] canEdit = new boolean [] { // false, false, false, false // }; // public boolean isCellEditable(int rowIndex, int columnIndex) { // return canEdit [columnIndex]; // } // }); // String[][] rec = { // { "1", "Steve", "AUS" }, // { "2", "Virat", "IND" }, // { "3", "Kane", "NZ" }, // { "4", "David", "AUS" }, // { "5", "Ben", "ENG" }, // { "6", "Eion", "ENG" } // }; model.addColumn("Employee name"); model.addColumn("Pay code"); model.addColumn("Employee type"); // Append a row // model.addRow(rec); jTablePayRoll.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTablePayRollMouseClicked(evt); } }); jScrollPane1.setViewportView(jTablePayRoll); jButtonAddEmployee.setText("+ Add employee"); jButtonAddEmployee.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAddEmployeeActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonAddEmployee)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jButtonAddEmployee) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonAddEmployeeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddEmployeeActionPerformed jDialogEmployeeEntry.pack(); jDialogEmployeeEntry.setVisible(true); }//GEN-LAST:event_jButtonAddEmployeeActionPerformed private void jButtonSaveEmployeeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveEmployeeActionPerformed // TODO add your handling code here: // Object selectedItem = jComboBoxEmpTypeEmpEntry.getSelectedItem(); int selectedIndex = jComboBoxEmpTypeEmpEntry.getSelectedIndex(); switch (selectedIndex+1) { case MANAGERS_PAYCODE: employee.setPayCode(MANAGERS_PAYCODE); break; case HOURLY_WORKERS_PAYCODE: employee.setPayCode(HOURLY_WORKERS_PAYCODE); break; case COMMISSION_WORKERS_PAYCODE: employee.setPayCode(COMMISSION_WORKERS_PAYCODE); break; } employee.setName(jTextFieldEmpNameEmpEntry.getText()); if (employee.getPayCode() == 1) { String[] rec = { employee.getName(), String.format("%d", employee.getPayCode()), "Manager"}; model.addRow(rec); } else if (employee.getPayCode() == 2) { String[] rec = { employee.getName(), String.format("%d", employee.getPayCode()), "Hourly Worker"}; model.addRow(rec); } else if (employee.getPayCode() == 3) { String[] rec = { employee.getName(), String.format("%d", employee.getPayCode()), "Commission Worker"}; model.addRow(rec); } jDialogEmployeeEntry.dispose(); }//GEN-LAST:event_jButtonSaveEmployeeActionPerformed private void jTablePayRollMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTablePayRollMouseClicked // clear fields for new employee details jTextFieldCommissionSalesEmpDetail.setText(String.format("%.2f", 0.0)); jTextFieldRatePerHourEmpDetail.setText(String.format("%.2f", 0.0)); jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%.2f", 0.0)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%.2f", 0.0)); jTextFieldEmpDetailGrossSalary.setText(String.format("%.2f", 0.0)); jTextFieldEmpDetailDeduction.setText(String.format("%.2f", 0.0)); jTextFieldEmpDetailNetSalary.setText(String.format("%.2f", 0.0)); jCheckBoxSundayEmpDetailFirstWk.setSelected(false); jCheckBoxMondayEmpDetailFirstWk.setSelected(false); jCheckBoxTuesdayEmpDetailFirstWk.setSelected(false); jCheckBoxWednesdayEmpDetailFirstWk.setSelected(false); jCheckBoxThursdayEmpDetailFirstWk.setSelected(false); jCheckBoxFridayEmpDetailFirstWk.setSelected(false); jCheckBoxSaturdayEmpDetailFirstWk.setSelected(false); jCheckBoxSundayEmpDetailSecondWk.setSelected(false); jCheckBoxMondayEmpDetailSecondWk.setSelected(false); jCheckBoxTuesdayEmpDetailSecondWk.setSelected(false); jCheckBoxWednesdayEmpDetailSecondWk.setSelected(false); jCheckBoxThursdayEmpDetailSecondWk.setSelected(false); jCheckBoxFridayEmpDetailSecondWk.setSelected(false); jCheckBoxSaturdayEmpDetailSecondWk.setSelected(false); // set epployee details jTextFieldEmpNameEmpDetail.setText(employee.getName()); jTextFieldEmpDetailPayCode.setText(String.format("%d", employee.getPayCode())); if (employee.getPayCode() == MANAGERS_PAYCODE) { jTextFieldCommissionSalesEmpDetail.setEnabled(false); jTextFieldRatePerHourEmpDetail.setEnabled(true); jTextFieldTotalHoursWorkedEmpDetail.setEnabled(false); jTextFieldCommissionSalesEmpDetail.setEditable(false); jTextFieldRatePerHourEmpDetail.setEditable(true); jTextFieldTotalHoursWorkedEmpDetail.setEditable(false); jCheckBoxSundayEmpDetailFirstWk.setEnabled(false); jCheckBoxMondayEmpDetailFirstWk.setEnabled(false); jCheckBoxTuesdayEmpDetailFirstWk.setEnabled(false); jCheckBoxWednesdayEmpDetailFirstWk.setEnabled(false); jCheckBoxThursdayEmpDetailFirstWk.setEnabled(false); jCheckBoxFridayEmpDetailFirstWk.setEnabled(false); jCheckBoxSaturdayEmpDetailFirstWk.setEnabled(false); jCheckBoxSundayEmpDetailSecondWk.setEnabled(false); jCheckBoxMondayEmpDetailSecondWk.setEnabled(false); jCheckBoxTuesdayEmpDetailSecondWk.setEnabled(false); jCheckBoxWednesdayEmpDetailSecondWk.setEnabled(false); jCheckBoxThursdayEmpDetailSecondWk.setEnabled(false); jCheckBoxFridayEmpDetailSecondWk.setEnabled(false); jCheckBoxSaturdayEmpDetailSecondWk.setEnabled(false); } // if employee is a Hourly worker else if (employee.getPayCode() == HOURLY_WORKERS_PAYCODE) { jTextFieldCommissionSalesEmpDetail.setEnabled(false); jTextFieldRatePerHourEmpDetail.setEnabled(true); jTextFieldTotalHoursWorkedEmpDetail.setEnabled(true); jTextFieldCommissionSalesEmpDetail.setEditable(false); jTextFieldRatePerHourEmpDetail.setEditable(true); jTextFieldTotalHoursWorkedEmpDetail.setEditable(true); jCheckBoxSundayEmpDetailFirstWk.setEnabled(true); jCheckBoxMondayEmpDetailFirstWk.setEnabled(true); jCheckBoxTuesdayEmpDetailFirstWk.setEnabled(true); jCheckBoxWednesdayEmpDetailFirstWk.setEnabled(true); jCheckBoxThursdayEmpDetailFirstWk.setEnabled(true); jCheckBoxFridayEmpDetailFirstWk.setEnabled(true); jCheckBoxSaturdayEmpDetailFirstWk.setEnabled(true); jCheckBoxSundayEmpDetailSecondWk.setEnabled(true); jCheckBoxMondayEmpDetailSecondWk.setEnabled(true); jCheckBoxTuesdayEmpDetailSecondWk.setEnabled(true); jCheckBoxWednesdayEmpDetailSecondWk.setEnabled(true); jCheckBoxThursdayEmpDetailSecondWk.setEnabled(true); jCheckBoxFridayEmpDetailSecondWk.setEnabled(true); jCheckBoxSaturdayEmpDetailSecondWk.setEnabled(true); } else if (employee.getPayCode() == COMMISSION_WORKERS_PAYCODE) { jTextFieldCommissionSalesEmpDetail.setEnabled(true); jTextFieldRatePerHourEmpDetail.setEnabled(false); jTextFieldTotalHoursWorkedEmpDetail.setEnabled(false); jTextFieldCommissionSalesEmpDetail.setEditable(true); jTextFieldRatePerHourEmpDetail.setEditable(false); jTextFieldTotalHoursWorkedEmpDetail.setEditable(false); jCheckBoxSundayEmpDetailFirstWk.setEnabled(false); jCheckBoxMondayEmpDetailFirstWk.setEnabled(false); jCheckBoxTuesdayEmpDetailFirstWk.setEnabled(false); jCheckBoxWednesdayEmpDetailFirstWk.setEnabled(false); jCheckBoxThursdayEmpDetailFirstWk.setEnabled(false); jCheckBoxFridayEmpDetailFirstWk.setEnabled(false); jCheckBoxSaturdayEmpDetailFirstWk.setEnabled(false); jCheckBoxSundayEmpDetailSecondWk.setEnabled(false); jCheckBoxMondayEmpDetailSecondWk.setEnabled(false); jCheckBoxTuesdayEmpDetailSecondWk.setEnabled(false); jCheckBoxWednesdayEmpDetailSecondWk.setEnabled(false); jCheckBoxThursdayEmpDetailSecondWk.setEnabled(false); jCheckBoxFridayEmpDetailSecondWk.setEnabled(false); jCheckBoxSaturdayEmpDetailSecondWk.setEnabled(false); } // check for selected row first // if(jTablePayRoll.getSelectedRow() != -1) { // // remove selected row from the model // // model.removeRow(jTablePayRoll.getSelectedRow()); // JOptionPane.showMessageDialog(null, "Selected row deleted successfully"); // } jDialogEmployeeDetails.pack(); jDialogEmployeeDetails.setVisible(true); }//GEN-LAST:event_jTablePayRollMouseClicked private void jComboBoxEmpTypeEmpEntryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxEmpTypeEmpEntryActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBoxEmpTypeEmpEntryActionPerformed private void jTextFieldRatePerHourEmpDetailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldRatePerHourEmpDetailActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldRatePerHourEmpDetailActionPerformed private void jTextFieldDaysWorkedEmpDetailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldDaysWorkedEmpDetailActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldDaysWorkedEmpDetailActionPerformed private void jTextFieldTotalHoursWorkedEmpDetailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldTotalHoursWorkedEmpDetailActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldTotalHoursWorkedEmpDetailActionPerformed private void jTextFieldTaxMonthlyWageEmpDetailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldTaxMonthlyWageEmpDetailActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldTaxMonthlyWageEmpDetailActionPerformed private void jCheckBoxSaturdayEmpDetailFirstWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxSaturdayEmpDetailFirstWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxSaturdayEmpDetailFirstWk.isSelected()) { daysWorked++; grossSalary += 1.5 * hourlyRate * 8; } else { daysWorked--; grossSalary -= 1.5 * hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxSaturdayEmpDetailFirstWkActionPerformed private void jCheckBoxMondayEmpDetailFirstWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMondayEmpDetailFirstWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxMondayEmpDetailFirstWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxMondayEmpDetailFirstWkActionPerformed private void jCheckBoxThursdayEmpDetailFirstWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxThursdayEmpDetailFirstWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxThursdayEmpDetailFirstWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxThursdayEmpDetailFirstWkActionPerformed private void jCheckBoxSaturdayEmpDetailSecondWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxSaturdayEmpDetailSecondWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxSaturdayEmpDetailSecondWk.isSelected()) { daysWorked++; grossSalary += 1.5 * hourlyRate * 8; } else { daysWorked--; grossSalary -= 1.5 * hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxSaturdayEmpDetailSecondWkActionPerformed private void jCheckBoxWednesdayEmpDetailFirstWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxWednesdayEmpDetailFirstWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxWednesdayEmpDetailFirstWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxWednesdayEmpDetailFirstWkActionPerformed private void jCheckBoxWednesdayEmpDetailSecondWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxWednesdayEmpDetailSecondWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxWednesdayEmpDetailSecondWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxWednesdayEmpDetailSecondWkActionPerformed private void jCheckBoxFridayEmpDetailFirstWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxFridayEmpDetailFirstWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxFridayEmpDetailFirstWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxFridayEmpDetailFirstWkActionPerformed private void jCheckBoxTuesdayEmpDetailFirstWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxTuesdayEmpDetailFirstWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxTuesdayEmpDetailFirstWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxTuesdayEmpDetailFirstWkActionPerformed private void jCheckBoxTuesdayEmpDetailSecondWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxTuesdayEmpDetailSecondWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxTuesdayEmpDetailSecondWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxTuesdayEmpDetailSecondWkActionPerformed private void jCheckBoxSundayEmpDetailFirstWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxSundayEmpDetailFirstWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxSundayEmpDetailFirstWk.isSelected()) { daysWorked++; grossSalary += 2 * hourlyRate * 8; } else { daysWorked--; grossSalary -= 2 * hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxSundayEmpDetailFirstWkActionPerformed private void jCheckBoxMondayEmpDetailSecondWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMondayEmpDetailSecondWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxMondayEmpDetailSecondWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxMondayEmpDetailSecondWkActionPerformed private void jCheckBoxFridayEmpDetailSecondWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxFridayEmpDetailSecondWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxFridayEmpDetailSecondWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxFridayEmpDetailSecondWkActionPerformed private void jCheckBoxSundayEmpDetailSecondWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxSundayEmpDetailSecondWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxSundayEmpDetailSecondWk.isSelected()) { daysWorked++; grossSalary += 2 * hourlyRate * 8; } else { daysWorked--; grossSalary -= 2 * hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxSundayEmpDetailSecondWkActionPerformed private void jCheckBoxThursdayEmpDetailSecondWkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxThursdayEmpDetailSecondWkActionPerformed // TODO add your handling code here: double hourlyRate = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); if (hourlyRate > 0) { if (jCheckBoxThursdayEmpDetailSecondWk.isSelected()) { daysWorked++; grossSalary += hourlyRate * 8; } else { daysWorked--; grossSalary -= hourlyRate * 8; } hoursWorked = daysWorked * 8; jTextFieldTotalHoursWorkedEmpDetail.setText(String.format("%d", hoursWorked)); jTextFieldDaysWorkedEmpDetail.setText(String.format("%d", daysWorked)); } else { JOptionPane.showMessageDialog(null, "No hourly rate", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jCheckBoxThursdayEmpDetailSecondWkActionPerformed private void jTextFieldCommissionSalesEmpDetailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCommissionSalesEmpDetailActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldCommissionSalesEmpDetailActionPerformed private void jTextFieldEmpDetailGrossSalaryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldEmpDetailGrossSalaryActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldEmpDetailGrossSalaryActionPerformed private void jButtonViewPayCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonViewPayCheckActionPerformed // TODO add your handling code here: double tax = Double.parseDouble(jTextFieldTaxMonthlyWageEmpDetail.getText()); if (employee.getPayCode() == MANAGERS_PAYCODE) { jTextFieldRatePerHourEmpDetail.setText(String.format("%.2f", 11.38)); double ratePerHour = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); grossSalary = ratePerHour * 8 * 14; double deduc = (tax/(double)100) * grossSalary; double salary = 250 + (5.7/(double)100) * grossSalary; double netSalary = salary - deduc; jTextFieldEmpDetailGrossSalary.setText(String.format("%.2f", salary)); jTextFieldEmpDetailDeduction.setText(String.format("%.2f", deduc)); jTextFieldEmpDetailNetSalary.setText(String.format("%.2f", netSalary)); } // if employee is a Hourly worker else if (employee.getPayCode() == HOURLY_WORKERS_PAYCODE) { double ratePerHour = Double.parseDouble(jTextFieldRatePerHourEmpDetail.getText()); // double hoursWorked = Double.parseDouble(jTextFieldTotalHoursWorkedEmpDetail.getText()); // grossSalary += ratePerHour * hoursWorked; double deduc = (tax/(double)100) * grossSalary; double netSalary = grossSalary - deduc; jTextFieldEmpDetailGrossSalary.setText(String.format("%.2f", grossSalary)); jTextFieldEmpDetailDeduction.setText(String.format("%.2f", deduc)); jTextFieldEmpDetailNetSalary.setText(String.format("%.2f", netSalary)); } else if (employee.getPayCode() == COMMISSION_WORKERS_PAYCODE) { double sales = Double.parseDouble(jTextFieldCommissionSalesEmpDetail.getText()); double deduc = (tax/(double)100) * sales; double salary = 250 + (5.7/(double)100) * sales; double netSalary = salary - deduc; jTextFieldEmpDetailGrossSalary.setText(String.format("%.2f", salary)); jTextFieldEmpDetailDeduction.setText(String.format("%.2f", deduc)); jTextFieldEmpDetailNetSalary.setText(String.format("%.2f", netSalary)); } }//GEN-LAST:event_jButtonViewPayCheckActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PayrollSystemGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PayrollSystemGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PayrollSystemGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PayrollSystemGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new PayrollSystemGUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAddEmployee; private javax.swing.JButton jButtonSaveEmployee; private javax.swing.JButton jButtonViewPayCheck; private javax.swing.JCheckBox jCheckBoxFridayEmpDetailFirstWk; private javax.swing.JCheckBox jCheckBoxFridayEmpDetailSecondWk; private javax.swing.JCheckBox jCheckBoxMondayEmpDetailFirstWk; private javax.swing.JCheckBox jCheckBoxMondayEmpDetailSecondWk; private javax.swing.JCheckBox jCheckBoxSaturdayEmpDetailFirstWk; private javax.swing.JCheckBox jCheckBoxSaturdayEmpDetailSecondWk; private javax.swing.JCheckBox jCheckBoxSundayEmpDetailFirstWk; private javax.swing.JCheckBox jCheckBoxSundayEmpDetailSecondWk; private javax.swing.JCheckBox jCheckBoxThursdayEmpDetailFirstWk; private javax.swing.JCheckBox jCheckBoxThursdayEmpDetailSecondWk; private javax.swing.JCheckBox jCheckBoxTuesdayEmpDetailFirstWk; private javax.swing.JCheckBox jCheckBoxTuesdayEmpDetailSecondWk; private javax.swing.JCheckBox jCheckBoxWednesdayEmpDetailFirstWk; private javax.swing.JCheckBox jCheckBoxWednesdayEmpDetailSecondWk; private javax.swing.JComboBox jComboBoxEmpTypeEmpEntry; private javax.swing.JDialog jDialogEmployeeDetails; private javax.swing.JDialog jDialogEmployeeEntry; private javax.swing.JDialog jDialogPayCheck; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTablePayRoll; private javax.swing.JTextField jTextFieldCommissionSalesEmpDetail; private javax.swing.JTextField jTextFieldDaysWorkedEmpDetail; private javax.swing.JTextField jTextFieldEmpDetailDeduction; private javax.swing.JTextField jTextFieldEmpDetailGrossSalary; private javax.swing.JTextField jTextFieldEmpDetailNetSalary; private javax.swing.JTextField jTextFieldEmpDetailPayCode; private javax.swing.JTextField jTextFieldEmpNameEmpDetail; private javax.swing.JTextField jTextFieldEmpNameEmpEntry; private javax.swing.JTextField jTextFieldRatePerHourEmpDetail; private javax.swing.JTextField jTextFieldTaxMonthlyWageEmpDetail; private javax.swing.JTextField jTextFieldTotalHoursWorkedEmpDetail; // End of variables declaration//GEN-END:variables }
8a8fb3f61f0ddb44e7f84309ec0436f24dd984d5
[ "Java" ]
1
Java
chrisaugu/MajorProject-PayrollSystem
f3ff8b138a64653a765f86cf2407b914d2276886
4829e433aa89cba913490f57c637483757bd5630
refs/heads/master
<repo_name>Bubba74/RandomThings<file_sep>/Objects/ObjectMain.java package Objects; public class ObjectMain { // private static Operation math = new Operation(); public static void main (String Args[]){ //Possible operations: add, sub, mult, div // System.out.printf("Answer: %s", math.polynomial("1,3,2","*","1,4,6,4,1")); // int[] polyA = {2,0}; // int[] polyB = {1,2}; // System.out.printf("Answer: %s", math.polynomial(polyA, "*", polyB)); System.out.println("he"); Rectangle rect = new Rectangle(); rect.setX(50); Rectangle rect2 = new Rectangle(); rect2.setX(150); System.out.println(rect.getX()); System.out.println(rect2.getX()); rect.setX(49); rect2.setX(149); System.out.println(rect.getX()); System.out.println(rect2.getX()); }//main method }//ObjectMain class<file_sep>/VIM.java import javax.swing.JFrame; import javax.swing.JPanel; //import javax.swing.J public class VIM { JFrame frame = new JFrame ("Workspace"); JPanel panel = new JPanel (); public static void main (String Args[]){ print("Welcome to your workspace!"); print("Here you are able to create and edit files."); doNow(); }//main method public static void doNow (){ }//doNow method public static void print (String text){ System.out.println(text); }//print method public static void space (int num){ String lines = ""; for (int i = 1; i < num; i++){ lines += "\n"; } print(lines); }//space method public static void exit (){ System.exit(0); } }//VIM class <file_sep>/Objects/Calc.java package Objects; import java.awt.Color; import java.awt.ComponentOrientation; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; public class Calc { public static JFrame frame = new JFrame (); public static JPanel bg = new JPanel (); public static JButton numButts[] = new JButton[10]; public static JButton operButts[] = new JButton[4]; public static JButton plus, minus; public static JButton clear, eql; public static JTextArea screen; public static double oldNum = 0; public static double newNum = 0; public static double ans; public static boolean add = false; public static boolean sub = false; public static boolean mul = false; public static boolean div = false; public static boolean firstTime = true; public static void main (String Args[]){ frame = new JFrame (); frame.setTitle("TI-82"); JStuff.JFrame(frame,"applet"); bg = new JPanel(); JStuff.JPanel(bg, "applet"); frame.add(bg); screen = new JTextArea (); screen.setSize(230,50); screen.setLocation(10,10); Font font = new Font("Verdana", Font.PLAIN, 40); screen.setFont(font); screen.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); screen.setBackground(Color.green.brighter()); screen.setText("0"); bg.add(screen); loadCalc(); clear(); frame.pack(); frame.setSize(300,400); }//main method public static void loadCalc(){ int width = 50; int height = 30; int x[] = new int[4]; int y[] = new int[4]; x[0]=10; x[1]=x[0]+width+10; x[2]=x[1]+width+10; x[3]=x[2]+width+10; y[0]=70+10; y[1]=y[0]+height+10; y[2]=y[1]+height+10; y[3]=y[2]+height+10; /* plus = new JButton (); JStuff.JButton(plus, "calcButt"); plus.setLocation(x[3],y[0]); plus.setText("+"); plus.addActionListener(new operAction()); bg.add(plus); minus = new JButton (); JStuff.JButton(minus, "calcButt"); minus.setLocation(x[3],y[1]); minus.setText("-"); minus.addActionListener(new operAction()); bg.add(minus); */ for (int i=0;i<operButts.length;i++){ operButts[i] = new JButton (); JStuff.JButton(operButts[i], "calcButt"); operButts[i].setLocation(x[3],y[i]); operButts[i].addActionListener(new operAction()); bg.add(operButts[i]); } operButts[0].setText("+"); operButts[1].setText("-"); operButts[2].setText("*"); operButts[3].setText("/"); eql = new JButton (); JStuff.JButton(eql, "calcButt"); eql.setLocation(x[2],y[3]); eql.setText("="); eql.addActionListener(new eql()); bg.add(eql); clear = new JButton (); JStuff.JButton(clear,"calcButt"); clear.setLocation(x[0],y[3]); clear.setText("C"); clear.addActionListener(new clear()); bg.add(clear); for (int i=0;i<numButts.length;i++){ numButts[i] = new JButton (); JStuff.JButton(numButts[i], "calcButt"); numButts[i].setText(""+i); numButts[i].addActionListener(new numAction()); bg.add(numButts[i]); } numButts[0].setLocation(x[1],y[3]); numButts[1].setLocation(x[0],y[0]); numButts[2].setLocation(x[1],y[0]); numButts[3].setLocation(x[2],y[0]); numButts[4].setLocation(x[0],y[1]); numButts[5].setLocation(x[1],y[1]); numButts[6].setLocation(x[2],y[1]); numButts[7].setLocation(x[0],y[2]); numButts[8].setLocation(x[1],y[2]); numButts[9].setLocation(x[2],y[2]); } public static void clear(){ oldNum = 0; newNum = 0; ans = 0; add = false; sub = false; mul = false; div = false; firstTime = false; screen.setText("0"); }//clear method public static void eql(){ System.out.println("Nums: " + oldNum + " " + newNum); System.out.printf("Eql: Sub is %s, add is %s, mul is %s, div is %s\n",sub,add,mul,div); if (sub){ oldNum -= newNum; } else if (add){ oldNum += newNum; } else if (mul){ oldNum *= newNum; } else if (div){ oldNum /= newNum; } else { System.out.println("no oper match"); } newNum=0; // oldNum = oldNum + newNum; screen.setText(""+oldNum); System.out.println("Nums: " + oldNum + " " + newNum); }//eql method public static void num(String i){ int x=0; boolean s=true; // System.out.println("eActionCommand" + i); switch (i){ case "0": x = 0; break; case "1": x = 1; break; case "2": x = 2; break; case "3": x = 3; break; case "4": x = 4; break; case "5": x = 5; break; case "6": x = 6; break; case "7": x = 7; break; case "8": x = 8; break; case "9": x = 9; break; default: s = false; break; } System.out.println("x: " + x + " " + s); if (s){ if (!firstTime){ oldNum = oldNum*10 + x; screen.setText(""+oldNum); System.out.println("oldnum: " + oldNum); } else { newNum = newNum*10 + x; screen.setText(""+newNum); System.out.println("newnum: " + newNum); } } firstTime = true; }//num method }//TI82 class ////////////////////////////////////////////////////////////////////////////////////////////////////// class clear implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ Calc.clear(); } }//clear method class eql implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ Calc.eql(); } }//eql method class operAction implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ // Calc.firstTime = true; String i = e.getActionCommand(); Calc.add=false; Calc.sub=false; Calc.mul=false; Calc.div=false; switch (i){ case "+": Calc.add=true; break; case "-": Calc.sub=true; break; case "*": Calc.mul=true; break; case "/": Calc.div=true; break; default: System.out.println("ERROR"); } System.out.printf("operAction: Sub is %s, add is %s, mul is %s, div is %s\n",Calc.sub,Calc.add,Calc.mul,Calc.div); Calc.eql.doClick(); Calc.num(e.getActionCommand()); } }//operAction class class numAction implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ Calc.num(e.getActionCommand()); // System.out.println(e.getActionCommand()); }//actionPerformed method }//numAction class<file_sep>/Fight.java import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.TimeUnit; import java.util.Scanner; import javax.swing.*; public class Fight { private static Scanner input = new Scanner(System.in); private static String Name1; private static double Hp1Total = 20; private static double Hp1; private static int Hp1Width; private static double Attack1 = 3; private static double Defense1 = 3; private static int Speed1 = 3; private static String Name2 = "Enemy"; private static double Hp2Total = 12; private static double Hp2; private static int Hp2Width; private static double Attack2 = 4; private static double Defense2 = 3; private static int Speed2 = 3; public static boolean mobDead = false; public static boolean youDead = false; private static JFrame frame1 = new JFrame ("!Battle!"); private static int width; private static int height; private static JButton button1 = new JButton ("--EXIT--"); private static JButton button2 = new JButton ("--Attack--"); //private static JButton button3 = new JButton (""); private static JTextArea txtArea1 = new JTextArea (); private static JTextArea txtArea2 = new JTextArea (); private static JPanel Health1 = new JPanel(); private static JPanel Health2 = new JPanel(); public static void main (String Args[]){ print("What is your name?"); Name1 = input.nextLine().toString(); Hp1 = Hp1Total; Hp2 = Hp2Total; frame1.setLayout(null); frame1.setSize(800, 500); frame1.setLocation(400, 250); frame1.setResizable(false); frame1.setAlwaysOnTop(true); frame1.setEnabled(true); frame1.setVisible(true); frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.getContentPane().setBackground(Color.lightGray); width = frame1.getWidth(); height = frame1.getHeight(); button1.setBounds(width/8*5,height/8*5,width/4,height/4); button1.setToolTipText("Save and Quit?"); button1.setBackground(Color.orange); button1.setForeground(Color.magenta); button1.setEnabled(true); button1.setVisible(true); button1.addActionListener(new actionExit()); frame1.add(button1); txtArea1.setBounds(30,30,120,120); update("txtArea1"); txtArea1.setBackground(Color.pink); txtArea1.setVisible(true); txtArea1.setEnabled(true); frame1.add(txtArea1); txtArea2.setBounds(frame1.getWidth()-135 , 30 , 120 , 120); update("txtArea2"); txtArea2.setBackground(Color.pink); txtArea2.setVisible(true); txtArea2.setEnabled(true); frame1.add(txtArea2); button2.setBounds(width/8,height/8*5,width/4,height/4); button2.setToolTipText("Attack?"); button2.setBackground(Color.orange); button2.setForeground(Color.magenta); button2.setEnabled(true); button2.setVisible(true); button2.addActionListener(new actionAttack()); frame1.add(button2); Health1.setLocation(txtArea1.getX(), txtArea1.getY()+txtArea1.getHeight()+10); Health1.setSize(txtArea1.getWidth(), 30); Hp1Width = Health1.getWidth(); updateHealth("Health1"); Health1.setBackground(Color.green); Health1.setEnabled(true); Health1.setVisible(true); Health1.setToolTipText("Health"); frame1.add(Health1); Health2.setLocation(txtArea2.getX(), txtArea2.getY()+txtArea2.getHeight()+10); Health2.setSize(txtArea2.getWidth(), 30); Hp2Width = Health2.getWidth(); updateHealth("Health2"); Health2.setBackground(Color.green); Health2.setEnabled(true); Health2.setVisible(true); Health2.setToolTipText("Health"); frame1.add(Health2); }//main method public static void updateHealth(String bar){ if (bar.equals("Health1")){ //frame1.setVisible(false); //frame1.setEnabled(false); Health1.setEnabled(false); Health1.setVisible(false); double percent; Color bgColor; percent = Hp1/Hp1Total; if (percent <= .1){ bgColor = Color.red; } else if (percent <= .5){ bgColor = Color.orange; } else {bgColor = Color.green;} Health1.setBackground(bgColor); Health1.setSize((int) (Hp1Width*percent), 30); Health1.setEnabled(true); Health1.setVisible(true); //frame1.setVisible(true); //frame1.setEnabled(true); } if (bar.equals("Health2")){ frame1.setVisible(false); frame1.setEnabled(false); Health2.setEnabled(false); Health2.setVisible(false); double percent; Color bgColor; percent = Hp2/Hp2Total; if (percent <= .1){ bgColor = Color.red; } else if (percent <= .5){ bgColor = Color.orange; } else {bgColor = Color.green;} Health2.setBackground(bgColor); Health2.setSize((int) (Hp2Width*percent), 30); Health2.setEnabled(true); Health2.setVisible(true); frame1.setVisible(true); frame1.setEnabled(true); } } public static void update (String text){ if (text.equals("txtArea1")){ disable(txtArea1); txtArea1.setText( Name1 + "\nHealth = " + Hp1 + "\nAttack = " + Attack1 + "\nDefense = " + Defense1 + "\nSpeed = " + Speed1); enable(txtArea1); } if (text.equals("txtArea2")){ disable(txtArea2); txtArea2.setText(Name2 + "\nHealth = " + Hp2 + "\nAttack = " + Attack2 + "\nDefense = " + Defense2 + "\nSpeed = " + Speed2); enable(txtArea2); } } public static void DamageDealt (){ double damage1, damage2; damage1 = Attack2/Defense1; damage2 = Attack1/Defense2; Hp1 -= damage1; Hp2 -= damage2; if (Hp1 <= 0){ youDead = true; } if (Hp2 <= 0){ mobDead = true; } Hp1 = Math.floor(Hp1*100)/100; Hp2 = Math.floor(Hp2*100)/100; update("txtArea1"); update("txtArea2"); updateHealth("Health1"); updateHealth("Health2"); } public static void enable (JTextArea txtArea){ txtArea.setEnabled(true); txtArea.setVisible(true); } public static void disable (JTextArea txtArea){ txtArea.setEnabled(false); txtArea.setVisible(false); } public static void wait(int time){ try { TimeUnit.SECONDS.sleep(time); } catch(InterruptedException e){} } public static void exit (){ frame1.setEnabled(false); frame1.setVisible(false); System.exit(0); }//exit method public static void print (String text){ System.out.println(text); } public static void print (int text){ System.out.println("" + text); }//print method(s) }//Fight Class class actionExit implements ActionListener { @Override public void actionPerformed (ActionEvent e){ Fight.exit(); }//actionPerformed method }//actionExit class class actionAttack implements ActionListener { @Override public void actionPerformed (ActionEvent e){ Fight.DamageDealt(); if (Fight.mobDead){ System.out.println("YOU WIN!!!"); Fight.exit(); } if (Fight.youDead){ System.out.println("YOU LOSE!!!"); Fight.exit(); } }//actionPerformed method }//actionAction class
d5b928f55ab4f9db40ae97f0b1e573fc1ebaeefc
[ "Java" ]
4
Java
Bubba74/RandomThings
1430046d8d4a4690f8792254420d28452a75861c
35956e24d8072b80b9e188e3f9d9ec336338bd1b
refs/heads/main
<repo_name>shimopino/itddd-typescript<file_sep>/test/environment.ts import type { Circus } from "@jest/types"; import type { JestEnvironmentConfig, EnvironmentContext, } from "@jest/environment"; import { TestEnvironment } from "jest-environment-node"; class CustomEnvironment extends TestEnvironment { constructor(config: JestEnvironmentConfig, context: EnvironmentContext) { super(config, context); // console.log(config.globalConfig); // console.log(config.projectConfig); // @ts-expect-error this.testPath = context.testPath; // @ts-expect-error this.docblockPragmas = context.docblockPragmas; console.log(context.testPath); console.log(context.docblockPragmas); this.global.sampleHello = "hi"; } async setup() { console.log("setup"); await super.setup(); } async teardown() { console.log("teardown"); await super.teardown(); } getVmContext() { console.log("getVmContext"); return super.getVmContext(); } async handleTestEvent(event: Circus.Event) { // https://github.com/facebook/jest/blob/main/packages/jest-types/src/Circus.ts console.log(event.name); } } export default CustomEnvironment; <file_sep>/test/sample.test.ts import { PrismaClient } from "@prisma/client"; import { appDataSource } from "../src/database/typeorm"; import { User } from "../src/entity/User"; const client = new PrismaClient({ log: [{ level: "query", emit: "event" }], }); client.$on("query", (event) => { console.log(event); }); beforeEach(() => { console.log("hi"); }); afterEach(() => { console.log("hi"); // @ts-expect-error console.log({ sampleHello }); }); it("sample 1", () => { expect(1 + 1).toBe(2); }); it("sample 2", () => { expect(1 + 1).toBe(2); }); it("typeorm sample", async () => { await appDataSource.initialize(); await appDataSource.manager.getRepository(User).save({ id: "sample", name: "shimokawa", age: 20, }); }); <file_sep>/src/database/typeorm.ts import { DataSource } from "typeorm"; import { User } from "../entity/User"; export const appDataSource = new DataSource({ type: "sqlite", database: "./dev-typeorm.db", entities: [User], }); appDataSource .initialize() .then(() => { console.log("Data Source has been initialized!"); }) .catch((err) => { console.error("Error during Data Source initialization", err); }); <file_sep>/jest.config.mjs /** @type {import('@jest/types').Config.InitialOptions} */ const config = { preset: "ts-jest", testEnvironment: "./test/environment.ts", }; export default config;
8f3cb5ed8047a9831d30ad0d15670340feb0b383
[ "JavaScript", "TypeScript" ]
4
TypeScript
shimopino/itddd-typescript
30c42209efa562cb7c9a795b3f5e2225ebedde8d
557e4ac11b221f3051d44f94c4bad56281169ec8
refs/heads/master
<repo_name>ywuwgij/Alan.Log<file_sep>/Alan.Log/Core/ILogContainer.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Alan.Log.Core { /// <summary> /// ILog Container /// </summary> public interface ILogContainer { /// <summary> /// 写日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者(比如system, admin)</param> /// <param name="category">分类(比如order, pay, comment)</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> ILogContainer Log( string id = null, DateTime date = default(DateTime), string level = null, string logger = null, string category = null, string message = null, string note = null, string position = null, string request = null, string response = null); /// <summary> /// 注入日志级别模块 /// </summary> /// <param name="levels">日志级别(同时订阅多个级别日志可以以空格分隔)</param> /// <param name="log">日志模块</param> ILogContainer InjectLogModule(string levels, ILog log); /// <summary> /// 注入日志模块 /// </summary> /// <param name="log">日志模块</param> ILogContainer InjectLogModule(ILog log); /// <summary> /// 获取日志级别 /// </summary> /// <param name="level">{critical: 危险, error: 错误/异常, warning: 警告, info: 信息, debug: 调试, trace: 捕获跟踪}</param> /// <returns></returns> string GetLogLevel(string level); } } <file_sep>/Alan.Log/LogContainerImplement/LogUtils.cs using Alan.Log.Core; namespace Alan.Log.LogContainerImplement { /// <summary> /// 日志模块配置实用类 /// </summary> public sealed class LogUtils : LogContainer, ILogContainer { static LogUtils() { _current = new LogUtils(); } /// <summary> /// 当前LogUtils实例 /// </summary> private static LogUtils _current; /// <summary> /// 获取当前LogUtils实例 /// </summary> public static LogUtils Current { get { return _current; } } private LogUtils() : base() { } } } <file_sep>/Alan.Log/Core/ILog.ExMethods.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Alan.Log.LogContainerImplement; namespace Alan.Log.Core { /// <summary> /// 日志模块扩展方法 /// </summary> public static class ILogExMethods { /// <summary> /// 写日志 /// </summary> /// <param name="self">Alan.Log.Core.ILog</param> /// <param name="log"></param> public static ILog Log(this ILog self, Models.Log log) { var level = (log.Level.ToString() ?? "").ToLower(); return self.Log(id: log.Id, level: level, logger: log.Logger, category: log.Category, message: log.Message, note: log.Note, position: log.Position, request: log.Request, response: log.Response); } /// <summary> /// 写日志 /// </summary> /// <param name="self">Alan.Log.Core.ILog</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static ILog Log(this ILog self, string id = null, DateTime date = default(DateTime), string level = null, string logger = null, string category = null, string message = null, string note = null, string position = null, string request = null, string response = null) { self.Write(id: id, date: date, level: level, logger: logger, category: category, message: message, note: note, request: request, response: response, position: position); return self; } /// <summary> /// 记录危险日志 /// </summary> /// <param name="self">Alan.Log.Core.ILog</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static ILog Critical(this ILog self, string message, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string note = null, string position = null, string request = null, string response = null) { return self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("critical"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); } /// <summary> /// 记录错误日志 /// </summary> /// <param name="self">Alan.Log.Core.ILog</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static ILog Error(this ILog self, string message, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string note = null, string position = null, string request = null, string response = null) { return self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("error"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); } /// <summary> /// 记录警告日志 /// </summary> /// <param name="self">Alan.Log.Core.ILog</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static ILog Warning(this ILog self, string message, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string note = null, string position = null, string request = null, string response = null) { return self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("warning"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); } /// <summary> /// 记录信息日志 /// </summary> /// <param name="self">Alan.Log.Core.ILog</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static ILog Info(this ILog self, string message, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string note = null, string position = null, string request = null, string response = null) { return self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("info"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); } /// <summary> /// 记录调试日志 /// </summary> /// <param name="self">Alan.Log.Core.ILog</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static ILog Debug(this ILog self, string message, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string note = null, string position = null, string request = null, string response = null) { return self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("debug"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); } /// <summary> /// 记录跟踪日志 /// </summary> /// <param name="self">Alan.Log.Core.ILog</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static ILog Trace(this ILog self, string message, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string note = null, string position = null, string request = null, string response = null) { return self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("trace"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); } } } <file_sep>/Alan.Log/Core/ILog.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Alan.Log.Core { /// <summary> /// 日志接口 /// </summary> public interface ILog { /// <summary> /// 写日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者</param> /// <param name="category">分类(比如 注册/订单/支付/添加好友)</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="request">请求内容</param> /// <param name="response">响应内容</param> /// <param name="position">输出位置</param> void Write(string id, DateTime date, string level, string logger, string category, string message, string note, string request, string response, string position); } } <file_sep>/README.md  # Alan.Log 核心模块(Alan.Log)内置了单文件日志(日志写进单个文件), 多文件日志(日志根据大小写进多个文件)和邮件日志(将日志发送到指定邮箱)三个实现. 你可以注册多个日志模块, 如果你执行一次写日志操作可能会有多个日志模块接收到日志. Alan.Log 提供 Fluent 风格的调用. ## Alan.Log.RabbitMQ 这个是利用RabbitMQ消息队列实现的日志模块. ## Alan.Log.Bmob 这个是 Bmob 网络数据库的日志模块. ## Install Install-Package Alan.Log 如果需要使用RabbitMQ来扩展日志系统, 可以 Alan.Log.RabbitMQ 模块: Install-Package Alan.Log.RabbitMQ ## Example 下面是使用示例, 使用起来很简单: //导入命名空间 using Alan.Log.Core; using Alan.Log.ILogImplement; using Alan.Log.LogContainerImplement; //配置日志模块 //捕获所有级别日志, 记录到单个日志文件里 LogUtils.Current.InjectLogModule<LogSingleFile>() //捕获所有级别日志, 发送到<EMAIL>邮箱 .InjectLogModule(new LogEmail("<EMAIL>", "<EMAIL> password", "<EMAIL>", "smtp.qq.com", 587, true)) //捕获error级别日志, 同时发送到<EMAIL>和<EMAIL>两个邮箱 .InjectLogModule("error", new LogEmail("<EMAIL>", "alan-overt", "<EMAIL> <EMAIL>", "smtp.163.com", 25, false)) //捕获所有级别日志, 记录到文件, 如果文件大于100KB自动分割文件. .InjectLogModule(new LogAutoSeperateFiles(fileMaxSizeBytes: 100 * 1024, fileDirectoryPath: @"E:\Temporary", fileNamePrefix: "multi-log-all")) //捕获所有info级别日志, 记录到文件, 如果文件大于100KB自动分割文件. .InjectLogModule("info", new LogAutoSeperateFiles(100 * 1024, @"E:\Temporary", "multi-log-info")) //这个需要 Alan.Log.RabbitMQ 模块 .InjectLogModule(new Alan.Log.RabbitMQ.LogRabbitMQ("host address", "user name", "password", "exchange name")); //写日志, 级别 error LogUtils.Current.Log(new Models.Log { Id = Guid.NewGuid().ToString(), Level = Models.Log.LogLevel.Error, Date = DateTime.Now, Category = "order", Message = "order error", Note = "I'm note", Logger = "Alan Wei @ error" }); //写日志, 级别 info LogUtils.Current.Log(id: Guid.NewGuid().ToString(), date: DateTime.Now, level: "info", logger: "Alan @ info", message: "info level log message"); 日志的级别主要分为以下几种: critical: 危险 error: 错误/异常 warning: 警告 info: 信息 debug: 调试 trace: 捕获 大致的使用, 上述的几个InjectLogModule已经演示了, 主要分类两种类型的日志模块, 一种是捕获某级别的日志, 另一种是捕获所有级别的日志. 下面是 `LogSingleFile` 单文件日志配置示例: //方法1: LogUtils.Current.InjectLogModule<LogSingleFile>(); //方法2 LogUtils.Current.InjectLogModule(new LogSingleFile()); //方法3 LogUtils.Current.InjectLogModule(new LogSingleFile(@"E:\Temporary\log.txt")); //方法4 LogUtils.Current.InjectLogModuleAppendConfig<LogSingleFile>().Config(@"E:\Temporary\log.txt"); //方法5 LogUtils.Current.InjectLogModule("error", new LogSingleFile()); //方法6 LogUtils.Current.InjectLogModule("error info", new LogSingleFile(@"E:\Temporary\.log.txt")); 方法1, 2会把日志写到 `Path.Combine(Environment.CurrentDirectory, "LogSingleFile.txt")` 里. 方法3, 4会把日志写到 `E:\Temporary\log.txt` 里. 方法5只捕获error级别日志, 而方法6则会捕获error和info级别的日志. 下面是 `LogEmail` 邮件日志的配置示例: //方法1 LogUtils.Current.InjectLogModule(new LogEmail("<EMAIL>", "password", "<EMAIL> <EMAIL>", "smtp.163.com", 25, false)); //方法2 LogUtils.Current.InjectLogModule(new LogEmail("<EMAIL>", "<PASSWORD>", "<EMAIL> <EMAIL>", "smtp.163.com", 25, false, "<EMAIL>", "sender name")); //方法3 LogUtils.Current.InjectLogModule("error", new LogEmail("<EMAIL>", "password", "<EMAIL> <EMAIL>", "smtp.163.com", 25, false)); //方法4 LogUtils.Current.InjectLogModule("error debug", new LogEmail("<EMAIL>", "password", "<EMAIL> <EMAIL>", "smtp.163.com", 25, false)); 邮件日志模块使用的微软提供的SmtpClient库, 网易邮箱 SSL: false, Port: 25 测试通过, QQ邮箱 SSL: true, Port: 587 测试通过. 其中方法1,2会把所有级别日志使用邮箱<EMAIL>发送到<EMAIL>和<EMAIL>两个邮箱地址. 方法3,4会捕获指定级别的日志发送到指定邮箱。 其他日志模块实现的使用方法类似, 就不一一列举, 你直接实例化对象时, 构造函数就会有参数提示. ## Custom Implement 扩展很简单, 你需要实现 `Alan.Log.Core.ILog` 接口就可以了. 你可以参考源码里的几个实现: * [单文件日志](https://github.com/Allen-Wei/Alan.Log/blob/master/Alan.Log/ILogImplement/LogSingleFile.cs) * [自动分割多个文件日志](https://github.com/Allen-Wei/Alan.Log/blob/master/Alan.Log/ILogImplement/LogAutoSeperateFiles.cs) * [Trace.Write输出](https://github.com/Allen-Wei/Alan.Log/blob/master/Alan.Log/ILogImplement/LogTraceWrite.cs) * [发送邮件日志](https://github.com/Allen-Wei/Alan.Log/blob/master/Alan.Log/ILogImplement/LogEmail.cs) * [RabbitMQ实现](https://github.com/Allen-Wei/Alan.Log/blob/master/Alan.Log.RabbitMQ/LogRabbitMQ.cs) 上述是日志模块的实现. 你还需要有一个日志容器(ILogContainer)来容纳多个日志模块, 然后提供写日志的接口, 写日志的时候遍历注册的日志模块, 并调用日志模块的Write方法写日志. `Alan.Log` 里已经有了一个实现 `Alan.Log.LogContainerImplement.LogContainer.cs`, 然后利用单例模式, 实现了全局的一个唯一日志容器 `LogUtils.Current` . `LogContainer.cs` 和 `LogUtils.cs` 是我自己的实现, 你也可以实现接口 `ILogContainer.cs` 来根据自己的业务需求实现日志容器. 这个日志模块耦合度还是很低的. <file_sep>/Alan.Log/ILogImplement/LogAutoSeperateFiles.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Alan.Log.Core; namespace Alan.Log.ILogImplement { /// <summary> /// 根据文件大小自动将日志记录到不同的文件里 /// </summary> public class LogAutoSeperateFiles : ILog { private static object _lock = new object(); /// <summary> /// 文件最大尺寸 /// </summary> private int _fileMaxSizeBytes; /// <summary> /// 文件目录 /// </summary> private string _fileDirectory; /// <summary> /// 文件名前缀 /// </summary> private string _fileNamePrefix; /// <summary> /// 日志文件后缀名 /// </summary> private string _fileExtentionName; /// <summary> /// 获取文件绝对路径 /// (directory, fileNamePrefix, maxSize) /// </summary> private Func<string, string, int, string> _getFileFullPath; public bool AppendCommentName { get; set; } /// <summary> /// 实例化 默认大小 100*1024, 默认执行环境目录, 文件名LogAutoSeperateFiles /// </summary> public LogAutoSeperateFiles() { this.Config(100 * 1024, Environment.CurrentDirectory, "LogAutoSeperateFiles", "txt"); } /// <summary> /// 自动将日志记录到不同的文件里 /// </summary> /// <param name="fileMaxSizeBytes">单个文件最大尺寸</param> /// <param name="fileFullPath">日志文件绝对路径(比如 E:\SitePath\LogName.log, 目录是 E:\SitePath, 日志名前缀 LogName, 日志扩展名 log)</param> public LogAutoSeperateFiles(int fileMaxSizeBytes, string fileFullPath) { if (String.IsNullOrWhiteSpace(fileFullPath)) throw new ArgumentNullException("fileFullPath"); var directory = Path.GetDirectoryName(fileFullPath); var prefixName = Path.GetFileNameWithoutExtension(fileFullPath); var extName = (Path.GetExtension(fileFullPath) ?? "").Replace(".", ""); this.Config(fileMaxSizeBytes, directory, prefixName, extName); } /// <summary> /// 自动将日志记录到不同的文件里 /// </summary> /// <param name="fileMaxSizeBytes">单个文件最大尺寸</param> /// <param name="fileDirectoryPath">文件所在目录</param> /// <param name="fileNamePrefix">文件名前缀</param> public LogAutoSeperateFiles(int fileMaxSizeBytes, string fileDirectoryPath, string fileNamePrefix) { this.Config(fileMaxSizeBytes, fileDirectoryPath, fileNamePrefix, "txt"); } /// <summary> /// 自动将日志记录到不同的文件里 /// </summary> /// <param name="fileMaxSizeBytes">单个文件最大尺寸</param> /// <param name="fileDirectoryPath">文件所在目录</param> /// <param name="fileNamePrefix">文件名前缀</param> /// <param name="getFileFullPath">(directory, fileNamePrefix, maxSize) => fileFullpath</param> public LogAutoSeperateFiles(int fileMaxSizeBytes, string fileDirectoryPath, string fileNamePrefix, Func<string, string, int, string> getFileFullPath) { this.Config(fileMaxSizeBytes, fileDirectoryPath, fileNamePrefix, "txt", getFileFullPath); } /// <summary> /// 配置 /// </summary> /// <param name="fileMaxSizeBytes">单个文件最大尺寸</param> /// <param name="fileDirectoryPath">文件所在目录</param> /// <param name="fileNamePrefix">文件名前缀</param> /// <param name="fileExtName">日志文件后缀名</param> /// <returns></returns> public LogAutoSeperateFiles Config(int fileMaxSizeBytes, string fileDirectoryPath, string fileNamePrefix, string fileExtName) { if (fileMaxSizeBytes < 1) throw new ArgumentOutOfRangeException(message: "fileMaxSizeBytes 文件尺寸不能小于1", innerException: null); if (String.IsNullOrWhiteSpace(fileDirectoryPath)) throw new ArgumentNullException("fileDirectoryPath"); if (String.IsNullOrWhiteSpace(fileNamePrefix)) throw new ArgumentNullException("fileNamePrefix"); this._fileMaxSizeBytes = fileMaxSizeBytes; this._fileDirectory = fileDirectoryPath; this._fileNamePrefix = fileNamePrefix; this._fileExtentionName = fileExtName; this._getFileFullPath = (direc, fnPrefix, maxSize) => { var directory = new DirectoryInfo(direc); if (!directory.Exists) { directory.Create(); } var files = directory.GetFiles(String.Format("{0}*.{1}", fnPrefix, this._fileExtentionName)).OrderByDescending(f => f.CreationTime); var number = 0; var firstFile = files.FirstOrDefault(); if (firstFile != null) { if (firstFile.Length < maxSize) return firstFile.FullName; var firstFileName = firstFile.Name; number = int.Parse(firstFileName.Split('.')[0].Split('-').Last()); ++number; } var fileFullPath = Path.Combine(direc, String.Format("{0}-{1}-{2}.{3}", fnPrefix, DateTime.Now.ToString("yyyyMMdd"), number, this._fileExtentionName)); return fileFullPath; }; this.AppendCommentName = true; return this; } /// <summary> /// 配置 /// </summary> /// <param name="fileMaxSizeBytes">单个文件最大尺寸</param> /// <param name="fileDirectoryPath">文件所在目录</param> /// <param name="fileNamePrefix">文件名前缀</param> /// <param name="extName">日志文件扩展名</param> /// <param name="getFileFullPath">(directory, fileNamePrefix, maxSize) => fileFullpath</param> /// <returns></returns> public LogAutoSeperateFiles Config(int fileMaxSizeBytes, string fileDirectoryPath, string fileNamePrefix, string extName, Func<string, string, int, string> getFileFullPath) { this.Config(fileMaxSizeBytes, fileDirectoryPath, fileNamePrefix, extName); if (getFileFullPath == null) throw new ArgumentNullException("getFileFullPath"); this._getFileFullPath = getFileFullPath; return this; } /// <summary> /// 写日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者</param> /// <param name="category">分类(比如 注册/订单/支付/添加好友)</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="request">请求内容</param> /// <param name="response">响应内容</param> /// <param name="position">输出位置</param> public void Write(string id, DateTime date, string level, string logger, string category, string message, string note, string request, string response, string position) { var lines = new List<string>(); if (this.AppendCommentName) { if (!String.IsNullOrWhiteSpace(id)) lines.Add(String.Format("{0,10}: {1}", "Id", id)); if (date != default(DateTime)) lines.Add(String.Format("{0,10}: {1}", "Date", date.ToString("yyyy-MM-dd HH:mm:ss"))); if (!String.IsNullOrWhiteSpace(level)) lines.Add(String.Format("{0,10}: {1}", "Level", level)); if (!String.IsNullOrWhiteSpace(logger)) lines.Add(String.Format("{0,10}: {1}", "Logger", logger)); if (!String.IsNullOrWhiteSpace(category)) lines.Add(String.Format("{0,10}: {1}", "Category", category)); if (!String.IsNullOrWhiteSpace(message)) lines.Add(String.Format("{0,10}: {1}", "Message", message)); if (!String.IsNullOrWhiteSpace(note)) lines.Add(String.Format("{0,10}: {1}", "Note", note)); if (!String.IsNullOrWhiteSpace(request)) lines.Add(String.Format("{0,10}: {1}", "Request", request)); if (!String.IsNullOrWhiteSpace(response)) lines.Add(String.Format("{0,10}: {1}", "Response", response)); if (!String.IsNullOrWhiteSpace(position)) lines.Add(String.Format("{0,10}: {1}", "Position", position)); } else { if (!String.IsNullOrWhiteSpace(id)) lines.Add(id); if (date != default(DateTime)) lines.Add(date.ToString("yyyy-MM-dd HH:mm:ss")); if (!String.IsNullOrWhiteSpace(level)) lines.Add(level); if (!String.IsNullOrWhiteSpace(logger)) lines.Add(logger); if (!String.IsNullOrWhiteSpace(category)) lines.Add(category); if (!String.IsNullOrWhiteSpace(message)) lines.Add(message); if (!String.IsNullOrWhiteSpace(note)) lines.Add(note); if (!String.IsNullOrWhiteSpace(request)) lines.Add(request); if (!String.IsNullOrWhiteSpace(response)) lines.Add(response); if (!String.IsNullOrWhiteSpace(position)) lines.Add(position); } var text = String.Join(Environment.NewLine, lines) + Environment.NewLine; var fileFullPath = this._getFileFullPath(this._fileDirectory, this._fileNamePrefix, this._fileMaxSizeBytes); lock (_lock) { System.IO.File.AppendAllText(fileFullPath, text, System.Text.Encoding.UTF8); } } } } <file_sep>/Alan.Log/Core/ILogContainer.ExMethods.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Alan.Log.LogContainerImplement; namespace Alan.Log.Core { /// <summary> /// Alan.Log.Core.LogUtils 扩展方法 /// </summary> public static class LogContainerExMethods { /// <summary> /// 写日志 /// </summary> /// <param name="utils">Alan.Log.Core.LogUtils</param> /// <param name="log"></param> public static TLogContainer Log<TLogContainer>(this TLogContainer utils, Models.Log log) where TLogContainer : ILogContainer { var level = (log.Level.ToString() ?? "").ToLower(); utils.Log( id: log.Id, date: log.Date, level: level, logger: log.Logger, category: log.Category, message: log.Message, note: log.Note, position: log.Position, request: log.Request, response: log.Response); return utils; } /// <summary> /// 危险日志 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static TLogContainer LogCritical<TLogContainer>(this TLogContainer self, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string message = null, string note = null, string position = null, string request = null, string response = null) where TLogContainer : ILogContainer { self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("critical"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); return self; } /// <summary> /// 错误日志 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static TLogContainer LogError<TLogContainer>(this TLogContainer self, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string message = null, string note = null, string position = null, string request = null, string response = null) where TLogContainer : ILogContainer { self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("error"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); return self; } /// <summary> /// 警告日志 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static TLogContainer LogWarning<TLogContainer>(this TLogContainer self, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string message = null, string note = null, string position = null, string request = null, string response = null) where TLogContainer : ILogContainer { self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("warning"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); return self; } /// <summary> /// 信息日志 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static TLogContainer LogInfo<TLogContainer>(this TLogContainer self, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string message = null, string note = null, string position = null, string request = null, string response = null) where TLogContainer : ILogContainer { self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("info"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); return self; } /// <summary> /// 调试日志 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static TLogContainer LogDebug<TLogContainer>(this TLogContainer self, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string message = null, string note = null, string position = null, string request = null, string response = null) where TLogContainer : ILogContainer { self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("debug"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); return self; } /// <summary> /// 捕获日志 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public static TLogContainer LogTrace<TLogContainer>(this TLogContainer self, string id = null, DateTime date = default(DateTime), string logger = null, string category = null, string message = null, string note = null, string position = null, string request = null, string response = null) where TLogContainer : ILogContainer { self.Log(id: id, date: date, level: LogUtils.Current.GetLogLevel("trace"), logger: logger, category: category, message: message, note: note, position: position, request: request, response: response); return self; } #region utils methods /// <summary> /// 注入指定级别的日志模块 /// </summary> /// <param name="self">LogUtils</param> /// <param name="levels">日志级别(同时订阅多个级别日志可以以空格分隔)</param> /// <returns></returns> public static TLogContainer InjectLogModule<TLogContainer, TLog>(this TLogContainer self, string levels) where TLog : ILog, new() where TLogContainer : ILogContainer { self.InjectLogModuleAppendConfig<TLogContainer, TLog>(levels); return self; } /// <summary> /// 注入指定级别的日志模块 /// </summary> /// <param name="self">LogUtils</param> /// <param name="levels">日志级别(同时订阅多个级别日志可以以空格分隔)</param> /// <returns></returns> public static TLog InjectLogModuleAppendConfig<TLogContainer, TLog>(this TLogContainer self, string levels) where TLog : ILog, new() where TLogContainer : ILogContainer { var log = new TLog(); self.InjectLogModule(levels, log); return log; } /// <summary> /// 注入日志模块 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> public static TLogContainer InjectLogModule<TLogContainer, TLog>(this TLogContainer self) where TLog : ILog, new() where TLogContainer : ILogContainer { self.InjectLogModuleAppendConfig<TLogContainer, TLog>(); return self; } /// <summary> /// 注入日志模块 并返回日志模块实例 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> public static TLog InjectLogModuleAppendConfig<TLogContainer, TLog>(this TLogContainer self) where TLog : ILog, new() where TLogContainer : ILogContainer { var log = new TLog(); self.InjectLogModule(log); return log; } #endregion } } <file_sep>/Alan.Log.RabbitMQ.Example/Alan.Log.RabbitMQ.Example/Global.asax.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; using System.Web.Http; using Alan.Log.Core; using Alan.Log.ILogImplement; using Alan.Log.LogContainerImplement; namespace Alan.Log.RabbitMQ.Example { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); Alan.Log.LogContainerImplement.LogUtils.Current.InjectLogModule(new Alan.Log.ILogImplement.LogSingleFile(HostingEnvironment.MapPath("~/App_Data/debug.log"))); Alan.Log.LogContainerImplement.LogUtils.Current.InjectLogModule(new Alan.Log.RabbitMQ.LogRabbitMQ(host: "192.168.121.129", userName: "test", passWord: "<PASSWORD>", exchange: "topic-log-test")); } } }<file_sep>/Alan.Log.RabbitMQ.Example/Alan.Log.RabbitMQ.Example/Library/LogModule.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Alan.Log.Core; using Alan.Log.LogContainerImplement; namespace Alan.Log.RabbitMQ.Example.Library { public class LogModule : IHttpModule { public void Dispose() { } public void Init(HttpApplication context) { context.Error += Context_Error; context.BeginRequest += Context_BeginRequest; } private void Context_BeginRequest(object sender, EventArgs e) { var app = sender as HttpApplication; var req = app.Request; Alan.Log.LogContainerImplement.LogUtils.Current.LogDebug(id: Guid.NewGuid().ToString(), date: DateTime.Now, category: "request", message: String.Format("{0} {1}", req.HttpMethod, req.RawUrl)); } private void Context_Error(object sender, EventArgs e) { var app = sender as HttpApplication; var ex = app.Server.GetLastError(); Alan.Log.LogContainerImplement.LogUtils.Current.Log( id: Guid.NewGuid().ToString(), date: DateTime.Now, level: "error", category: "application", message: ex.Message, note: ex.StackTrace, position: ex.Source); } } }<file_sep>/Alan.Log/LogContainerImplement/LogContainer.cs using System; using System.Collections.Generic; using System.Linq; using Alan.Log.Core; namespace Alan.Log.LogContainerImplement { /// <summary> /// 日记模块的封装 /// </summary> public class LogContainer : ILogContainer { /// <summary> /// 日记模块的封装 /// </summary> protected LogContainer() { this._logModules = new List<ILog>(); this._logLevelModules = new Dictionary<string, List<ILog>>(); //初始化日志Level this._logLevles = new Dictionary<string, string> { { "critical", "critical"} , { "error", "error"} , { "warning", "warning"} , { "info", "info"} , { "debug", "debug"} , { "trace", "trace"} }; } /// <summary> /// 日志级别 /// </summary> protected readonly Dictionary<string, string> _logLevles; #region level log /// <summary> /// 不同级别的日志模块 /// </summary> protected IDictionary<string, List<ILog>> _logLevelModules; /// <summary> /// 注入日志级别模块 /// </summary> /// <param name="levels">日志级别(同时订阅多个级别日志可以以空格分隔)</param> /// <param name="log">日志模块</param> public ILogContainer InjectLogModule(string levels, ILog log) { if (String.IsNullOrWhiteSpace(levels)) throw new ArgumentNullException("levels"); if (log == null) throw new ArgumentNullException("log"); levels.Split(' ').ToList().ForEach(level => { List<ILog> logModules; if (this._logLevelModules.ContainsKey(level)) { logModules = this._logLevelModules[level]; if (logModules == null) { logModules = new List<ILog>(); this._logLevelModules[level] = logModules; } } else { logModules = new List<ILog>(); this._logLevelModules.Add(level, logModules); } logModules.Add(log); }); return this; } /// <summary> /// 迭代日志模块 /// </summary> /// <param name="level"></param> /// <param name="iteral"></param> /// <returns></returns> private ILogContainer IteralLogModules(string level, Action<ILog> iteral) { if (!this._logLevelModules.ContainsKey(level)) return this; var logModules = this._logLevelModules[level]; if (logModules == null) return this; logModules.ForEach(iteral); return this; } #endregion #region global log /// <summary> /// 日志模块 /// </summary> protected readonly List<ILog> _logModules; /// <summary> /// 注入日志模块 /// </summary> /// <param name="log">日志模块</param> public ILogContainer InjectLogModule(ILog log) { if (log == null) throw new ArgumentNullException("log"); this._logModules.Add(log); return this; } /// <summary> /// 遍历所有日志模块 /// </summary> /// <param name="iteral">迭代函数</param> private ILogContainer IteralLogModules(Action<ILog> iteral) { this._logModules.ForEach(iteral); return this; } #endregion /// <summary> /// 写日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者</param> /// <param name="category">分类</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="position">输出位置</param> /// <param name="request">请求内容</param> /// <param name="response">输出内容</param> public ILogContainer Log( string id = null, DateTime date = default(DateTime), string level = null, string logger = null, string category = null, string message = null, string note = null, string position = null, string request = null, string response = null) { //global log modules this.IteralLogModules(log => log.Log( id: id, date: date, level: level, logger: logger, category: category, message: message, note: note, position: position, request: request, response: response)); //level log modules if (!String.IsNullOrWhiteSpace(level)) this.IteralLogModules(level, log => log.Log( id: id, date: date, level: level, logger: logger, category: category, message: message, note: note, position: position, request: request, response: response)); return this; } /// <summary> /// 清空已注入的日志模块 /// </summary> public LogContainer ClearLogModules() { this._logModules.Clear(); this._logLevelModules = new Dictionary<string, List<ILog>>(); return this; } /// <summary> /// 获取日志级别 /// </summary> /// <param name="level">{critical: 危险, error: 错误/异常, warning: 警告, info: 信息, debug: 调试, trace: 捕获跟踪}</param> /// <returns></returns> public string GetLogLevel(string level) { if (this._logLevles.ContainsKey(level)) return this._logLevles[level]; return level; } } } <file_sep>/Alan.Log.Bmob/LogBmob.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Alan.Log.Bmob.Utils; using Alan.Log.Core; namespace Alan.Log.Bmob { /// <summary> /// Bmob日志实现 /// </summary> public class LogBmob : ILog { private string _tableName; private readonly cn.bmob.api.BmobWindows _bmob; /// <summary> /// 实例化 LogBmob /// </summary> /// <param name="tableName">表明</param> /// <param name="appKey">Application Key</param> /// <param name="restKey">REST Key</param> public LogBmob(string tableName, string appKey, string restKey) { this._tableName = tableName; _bmob = new cn.bmob.api.BmobWindows(); _bmob.initialize(appKey, restKey); } /// <summary> /// 写日志 /// </summary> /// <param name="id"></param> /// <param name="date"></param> /// <param name="level"></param> /// <param name="logger"></param> /// <param name="category"></param> /// <param name="message"></param> /// <param name="note"></param> /// <param name="request"></param> /// <param name="response"></param> /// <param name="position"></param> public void Write(string id, DateTime date, string level, string logger, string category, string message, string note, string request, string response, string position) { if (date == default(DateTime)) date = DateTime.Now; var model = new LogModel(this._tableName) { Id = id, Date = new cn.bmob.io.BmobDate() { iso = date.ToString("yyyy-MM-dd HH:mm:ss") }, Level = level, Logger = logger, Category = category, Message = message, Note = note, Request = request, Response = response, Position = position }; _bmob.CreateTaskAsync(model); } } } <file_sep>/Alan.Log/ILogImplement/LogAutoSeperateFilesByDate.cs using Alan.Log.Core; using Alan.Log.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Alan.Log.Models.Ex; namespace Alan.Log.ILogImplement { /// <summary> /// 根据日期自动分割文件 /// </summary> public class LogAutoSeperateFilesByDate : ILog { private static object _lock = new object(); /// <summary> /// 日志存放目录 /// </summary> private string Directory { get; set; } /// <summary> /// 日志文件名前缀 /// </summary> private string PrefixName { get; set; } /// <summary> /// 日志文件扩展名 /// </summary> private string ExtName { get; set; } /// <summary> /// 序列化日志 /// </summary> public Func<Alan.Log.Models.Log, string> Generate { get; set; } /// <summary> /// 在默认的生成日志内容方法里(Generate)是否将属性名写入 /// </summary> public bool AppendPropertyNameInDefaultGenerate { get; set; } /// <summary> /// 实例化 /// </summary> public LogAutoSeperateFilesByDate() { this.Directory = Environment.CurrentDirectory; this.PrefixName = "LogAutoSeperateFilesByDate"; this.ExtName = ".txt"; this.AppendPropertyNameInDefaultGenerate = true; this.Generate = l => { List<string> lines = new List<string>(); if (this.AppendPropertyNameInDefaultGenerate) { if (!String.IsNullOrWhiteSpace(l.Id)) lines.Add(String.Format("{0,-10}: {1}", "Id", l.Id)); if (l.Date != default(DateTime)) lines.Add(String.Format("{0,-10}: {1}", "Date", l.Date.ToString("yyyy-MM-dd HH:mm:ss"))); if (l.Level != Models.Log.LogLevel.None) lines.Add(String.Format("{0,-10}: {1}", "Level", l.Level)); if (!String.IsNullOrWhiteSpace(l.Logger)) lines.Add(String.Format("{0,-10}: {1}", "Logger", l.Logger)); if (!String.IsNullOrWhiteSpace(l.Category)) lines.Add(String.Format("{0,-10}: {1}", "Category", l.Category)); if (!String.IsNullOrWhiteSpace(l.Message)) lines.Add(String.Format("{0,-10}: {1}", "Message", l.Message)); if (!String.IsNullOrWhiteSpace(l.Note)) lines.Add(String.Format("{0,-10}: {1}", "Note", l.Note)); if (!String.IsNullOrWhiteSpace(l.Request)) lines.Add(String.Format("{0,-10}: {1}", "Request", l.Request)); if (!String.IsNullOrWhiteSpace(l.Response)) lines.Add(String.Format("{0,-10}: {1}", "Response", l.Response)); if (!String.IsNullOrWhiteSpace(l.Position)) lines.Add(String.Format("{0,-10}: {1}", "Position", l.Position)); } else { if (!String.IsNullOrWhiteSpace(l.Id)) lines.Add(l.Id); if (l.Date != default(DateTime)) lines.Add(l.Date.ToString("yyyy-MM-dd HH:mm:ss")); if (l.Level != Models.Log.LogLevel.None) lines.Add(l.Level.ToString()); if (!String.IsNullOrWhiteSpace(l.Logger)) lines.Add(l.Logger); if (!String.IsNullOrWhiteSpace(l.Category)) lines.Add(l.Category); if (!String.IsNullOrWhiteSpace(l.Message)) lines.Add(l.Message); if (!String.IsNullOrWhiteSpace(l.Note)) lines.Add(l.Note); if (!String.IsNullOrWhiteSpace(l.Request)) lines.Add(l.Request); if (!String.IsNullOrWhiteSpace(l.Response)) lines.Add(l.Response); if (!String.IsNullOrWhiteSpace(l.Position)) lines.Add(l.Position); } return String.Join(Environment.NewLine, lines) + Environment.NewLine; }; } /// <summary> /// 实例化 /// </summary> /// <param name="fileFullPath">日志文件绝对路径, 从这个路径里获取日志目录, 日志名前缀, 日志扩展名. 比如 E:\path1\filename.ext, 目录为 E:\path1, 日志文件名前缀为 filename, 日志文件扩展名为.ext</param> public LogAutoSeperateFilesByDate(string fileFullPath) : this() { this.Directory = System.IO.Path.GetDirectoryName(fileFullPath); this.PrefixName = System.IO.Path.GetFileNameWithoutExtension(fileFullPath); this.ExtName = System.IO.Path.GetExtension(fileFullPath); } /// <summary> /// 实例化 /// </summary> /// <param name="fileFullPath">日志文件绝对路径, 从这个路径里获取日志目录, 日志名前缀, 日志扩展名. 比如 E:\path1\filename.ext, 目录为 E:\path1, 日志文件名前缀为 filename, 日志文件扩展名为.ext</param> /// <param name="generate">序列化字符串</param> public LogAutoSeperateFilesByDate(string fileFullPath, Func<Alan.Log.Models.Log, string> generate) : this() { this.Directory = System.IO.Path.GetDirectoryName(fileFullPath); this.PrefixName = System.IO.Path.GetFileNameWithoutExtension(fileFullPath); this.ExtName = System.IO.Path.GetExtension(fileFullPath); this.Generate = generate; } /// <summary> /// 实例化 /// </summary> /// <param name="directory">日志目录</param> /// <param name="fileName">日志文件名(包含扩展名)</param> public LogAutoSeperateFilesByDate(string directory, string fileName) : this() { this.PrefixName = System.IO.Path.GetFileNameWithoutExtension(fileName); this.ExtName = System.IO.Path.GetExtension(fileName); this.Directory = directory; } /// <summary> /// 实例化 /// </summary> /// <param name="directory">日志目录</param> /// <param name="fileName">日志文件名(包含扩展名)</param> /// <param name="generate">序列化日志字符串</param> public LogAutoSeperateFilesByDate(string directory, string fileName, Func<Alan.Log.Models.Log, string> generate) { this.PrefixName = System.IO.Path.GetFileNameWithoutExtension(fileName); this.ExtName = System.IO.Path.GetExtension(fileName); this.Directory = directory; this.Generate = generate; } /// <summary> /// 写日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者</param> /// <param name="category">分类(比如 注册/订单/支付/添加好友)</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="request">请求内容</param> /// <param name="response">响应内容</param> /// <param name="position">输出位置</param> public void Write(string id, DateTime date, string level, string logger, string category, string message, string note, string request, string response, string position) { var fileName = String.Format("{0}-{1}-{2}{3}", this.PrefixName, level ?? "none", DateTime.Now.ToString("yyyyMMdd"), this.ExtName); var filePath = System.IO.Path.Combine(this.Directory, fileName); var logTxt = this.Generate(new Alan.Log.Models.Log { Id = id, Level = level.ToLogLevel(), Logger = logger, Category = category, Date = date, Message = message, Note = note, Position = position, Request = request, Response = response }); lock (_lock) { if (!System.IO.Directory.Exists(this.Directory)) System.IO.Directory.CreateDirectory(this.Directory); System.IO.File.AppendAllText(filePath, logTxt, Encoding.UTF8); } } } } <file_sep>/Alan.Log.RabbitMQ.Example/README.md # Alan.Log.RabbitMQ 下面以日志模块作为例子介绍一下如何利用RabbitMQ来分发日志. 传统的日志模块都是把日志写到网站所在的服务器上的文件里或者数据库里, 利用RabbitMQ可以开发一个低耦合的分布式日志系统, 可以很简单高效地将日志分发到其他服务器上. ## Install & Introduction 你可以直接把 [ALan.Log](https://github.com/Allen-Wei/Alan.Log) 下载到本地, 然后切换到 [Alan.Log.RabbitMQ.Example](https://github.com/Allen-Wei/Alan.Log/tree/master/Alan.Log.RabbitMQ.Example) 目录. 目录里有一个 Visual Studio的Web项目文件 **Alan.Log.RabbitMQ.Example.sln**, 这个就是你的网站了, 网站注册了一个 `IHttpModule`类 `LogModule`, 在 `LogModule` 里把每次Web请求和网站异常发布到日志. 在 **Global.asax** 应用启动时注册了两个日志模块, 单文件日志模块和RabbitMQ日志分发模块. 目录NodeJsExample里有一个nodejs项目, 利用socket.io将VS(Visual Studio)的Web网站分发的日志实时显示在网页上. VS项目, 你可以直接F5运行测试, 或者发布测试. NodeJsExample 你需要先运行 `npm install` 把所需模块安装了。 ## Configuration 这里主要配置RabbitMQ Server的服务器地址, 认证信息和交换器名字. VS项目里的 **Global.asax** 注册RabbitMQ日志模块时, 通过参数指定这些信息. NodeJS项目里, 在 **app.js** 里 `amqp.connect("amqp://username:password@IpAddress:port", callback)` 里指定. ## Test 配置完成就可以测试了. 为了安全你最好先启动VS项目, 因为交换器声明是在VS项目里. 如果你先启动NodeJS项目, 而交换器未声明的话会抛异常. 启动好VS项目之后, 就可以启动NodeJS项目了, NodeJS项目你直接访问首页(默认监听的是8080端口). 两个项目启动完成后, 你就可以打开VS项目启动后的网站了, 你访问VS网站 */Home/Index*, NodeJS网站就会立即打印出日志消息, 显示你访问了 */Home/Index*. 如果你访问 */Home/ThrowException?msg=exmsg*, NodeJS网站会立即打印出一个错误日志. ## End 这里图解一下职责规划. 截图里有两个虚拟机,第一个是RabbitMQ服务器(`192.168.121.129`),第二个运行的是NodeJS站点(`192.168.121.128`),NodeJS站点订阅RabbitMQ队列,接收日志消息,利用socket.io将日志消息实时显示在网页上。 `http://localhost:60679`是一个ASP.Net网站,在Http Module是捕获了网站异常,并发布到日志,在`Begin_Request`里发布是每次请求日志。其中访问 `/Home/ThrowException` 会手动抛出一个异常消息。 而访问`192.168.121.128:8080`就可以反问NodeJS搭建的网站,然后实时显示 `http:localhost:60679` 发布的日志消息。 你可以通过routingKey来过滤不同级别的日志. ![illustrator](https://raw.githubusercontent.com/Allen-Wei/Alan.Log/master/Alan.Log.RabbitMQ.Example/rabbitmq-log.png) <file_sep>/Alan.Log/Models/LogModelEx.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Alan.Log.Models.Ex { /// <summary> /// LogModel的扩展方法 /// </summary> public static class LogModelEx { /// <summary> /// 字符串转换成枚举LogLevel /// </summary> /// <param name="level"></param> /// <returns></returns> public static Log.LogLevel ToLogLevel(this string level) { if (String.IsNullOrWhiteSpace(level)) return Log.LogLevel.None; level = level.ToLower(); switch (level) { case "critical": return Log.LogLevel.Critical; case "error": return Log.LogLevel.Error; case "warning": return Log.LogLevel.Warning; case "info": return Log.LogLevel.Info; case "debug": return Log.LogLevel.Debug; case "trace": return Log.LogLevel.Trace; default: return Log.LogLevel.None; } } } } <file_sep>/Alan.Log/ILogImplement/LogEmpty.cs using System; using Alan.Log.Core; namespace Alan.Log.ILogImplement { /// <summary> /// 空日志模块 /// </summary> public class LogEmpty :ILog { /// <summary> /// 写日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者</param> /// <param name="category">分类(比如 注册/订单/支付/添加好友)</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="request">请求内容</param> /// <param name="response">响应内容</param> /// <param name="position">输出位置</param> public void Write(string id, DateTime date, string level, string logger, string category, string message, string note, string request, string response, string position) { return; } } } <file_sep>/Alan.Log/ILogImplement/LogTraceWrite.cs using System; using System.Diagnostics; using Alan.Log.Core; using Alan.Log.LogContainerImplement; namespace Alan.Log.ILogImplement { /// <summary> /// System.Diagnostics.Trace 实现 /// </summary> public class LogTraceWrite : ILog { /// <summary> /// 写日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者</param> /// <param name="category">分类(比如 注册/订单/支付/添加好友)</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="request">请求内容</param> /// <param name="response">响应内容</param> /// <param name="position">输出位置</param> public void Write(string id, DateTime date, string level, string logger, string category, string message, string note, string request, string response, string position) { var output = String.Format("Id: {0}, Date: {1}, Level: {2}, Logger: {3}, Category: {4}, Message: {5}, Note: {6}, Request: {7}, Response: {8}, Position: {9}", id, date, level, logger, category, message, note, request, response, position); if (level == LogUtils.Current.GetLogLevel("error") || level == LogUtils.Current.GetLogLevel("critical")) { Trace.TraceError(output); } else if (level == LogUtils.Current.GetLogLevel("info")) { Trace.TraceWarning(output); } else if (level == LogUtils.Current.GetLogLevel("info") || level == LogUtils.Current.GetLogLevel("debug")) { Trace.TraceInformation(output); } else { Trace.WriteLine(output); } } } } <file_sep>/Alan.Log/LogContainerImplement/LogUtils.ExMethods.cs using Alan.Log.Core; namespace Alan.Log.LogContainerImplement { /// <summary> /// Alan.Log.Core.LogUtils 扩展方法 /// </summary> public static class LogUtilsExMethods { /// <summary> /// 注入指定级别的日志模块 /// </summary> /// <param name="self">LogUtils</param> /// <param name="levels">日志级别(同时订阅多个级别日志可以以空格分隔)</param> /// <returns></returns> public static LogUtils InjectLogModule<TLog>(this LogUtils self, string levels) where TLog : ILog, new() { self.InjectLogModuleAppendConfig<LogUtils, TLog>(levels); return self; } /// <summary> /// 注入指定级别的日志模块 /// </summary> /// <param name="self">LogUtils</param> /// <param name="levels">日志级别(同时订阅多个级别日志可以以空格分隔)</param> /// <returns></returns> public static TLog InjectLogModuleAppendConfig<TLog>(this LogUtils self, string levels) where TLog : ILog, new() { var log = new TLog(); self.InjectLogModule(levels, log); return log; } /// <summary> /// 注入日志模块 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> public static LogUtils InjectLogModule< TLog>(this LogUtils self) where TLog : ILog, new() { self.InjectLogModuleAppendConfig<LogUtils, TLog>(); return self; } /// <summary> /// 注入日志模块 并返回日志模块实例 /// </summary> /// <param name="self">Alan.Log.Core.LogUtils</param> public static TLog InjectLogModuleAppendConfig< TLog>(this LogUtils self) where TLog : ILog, new() { var log = new TLog(); self.InjectLogModule(log); return log; } } } <file_sep>/Alan.Log.RabbitMQ.Example/Alan.Log.RabbitMQ.Example/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Alan.Log.RabbitMQ.Example.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } public ActionResult ThrowException(string msg) { throw new Exception(msg); } } }<file_sep>/Alan.Log.Bmob/Utils/LogQuery.cs using System; using System.Threading.Tasks; using cn.bmob.api; using cn.bmob.exception; using cn.bmob.io; using cn.bmob.response; namespace Alan.Log.Bmob.Utils { /// <summary> /// 日志查询 /// </summary> public class LogQuery { private BmobWindows _bmob; private string _tableName; /// <summary> /// 实例化日志查询 /// </summary> /// <param name="tableName">表名</param> /// <param name="appKey">Application Key</param> /// <param name="restKey">REST Key</param> public LogQuery(string tableName, string appKey, string restKey) { this._tableName = tableName; this._bmob = new BmobWindows(); this._bmob.initialize(appKey, restKey); } /// <summary> /// 执行查询 /// </summary> /// <param name="query"></param> /// <param name="callback"></param> public void Query(BmobQuery query, Action<QueryCallbackData<LogModel>, BmobException> callback) { this._bmob.Find<LogModel>(this._tableName, query, (response, ex) => { callback(response, ex); }); } /// <summary> /// 执行异步查询 /// </summary> /// <param name="query"></param> /// <returns></returns> public async Task<QueryCallbackData<LogModel>> QueryAsync(BmobQuery query) { var res = await this._bmob.FindTaskAsync<LogModel>(this._tableName, query); return res; } /// <summary> /// 分页查询记录 /// </summary> /// <param name="skip"></param> /// <param name="limit"></param> /// <param name="callback"></param> public void Query(int skip, int limit, Action<QueryCallbackData<LogModel>, BmobException> callback) { BmobQuery query = new BmobQuery(); query.Skip(skip).Limit(limit); this.Query(query, callback); } } } <file_sep>/Alan.Log.Example/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Alan.Log.Core; using Alan.Log.ILogImplement; using Alan.Log.LogContainerImplement; namespace Alan.Log.Example { class Program { static void Main(string[] args) { SeperateFileLogByDate(); SingleFileLog(); WriteLog(); } static void WriteLog() { //写日志, 级别 error LogUtils.Current.Log(new Models.Log { Id = Guid.NewGuid().ToString(), Level = Models.Log.LogLevel.Error, Date = DateTime.Now, Category = "order", Message = "order error", Note = "I'm note", Logger = "Alan Wei @ error" }); //写日志, 级别 info LogUtils.Current.Log(id: Guid.NewGuid().ToString(), date: DateTime.Now, level: "info", category: "two", logger: "Alan @ info", message: "info level log message"); } static void InjectEmailLog() { //捕获所有级别日志, 发送到<EMAIL>邮箱 LogUtils.Current.InjectLogModule(new LogEmail("<EMAIL>", "<EMAIL> password", "<EMAIL>", "smtp.qq.com", 587, true)) //捕获error级别日志, 发送到<EMAIL>邮箱 .InjectLogModule("error", new LogEmail("<EMAIL>", "alan.overt", "<EMAIL>", "smtp.163.com", 25, false)); } static void SingleFileLog() { LogUtils.Current.InjectLogModule<LogSingleFile>(); LogUtils.Current.InjectLogModule(new LogSingleFile()); LogUtils.Current.InjectLogModule(new LogSingleFile(@"D:\Temporary\logs\log.txt")); LogUtils.Current.InjectLogModuleAppendConfig<LogSingleFile>().Config(@"D:\Temporary\logs\log.txt"); LogUtils.Current.InjectLogModule("error", new LogSingleFile()); } static void SeperateFileLogBySize() { LogUtils.Current //捕获所有级别日志, 记录到文件, 如果文件大于100KB自动分割文件. .InjectLogModule(new LogAutoSeperateFiles(fileMaxSizeBytes: 100 * 1024, fileDirectoryPath: @"E:\Temporary", fileNamePrefix: "multi-log-all")) //捕获所有info级别日志, 记录到文件, 如果文件大于100KB自动分割文件. .InjectLogModule("info", new LogAutoSeperateFiles(100 * 1024, @"E:\Temporary", "multi-log-info")); } static void SeperateFileLogByDate() { LogUtils.Current.InjectLogModule(new LogAutoSeperateFilesByDate(@"D:\Temporary\logs\date.log")); } } } <file_sep>/Alan.Log.RabbitMQ.Example/NodeJsExample/app.js var app = require("express")(), server = require("http").Server(app), io = require("socket.io")(server), amqp = require("amqplib/callback_api"); server.listen(8080); app.get("/" , function(req, res){ res.sendfile(__dirname + "/index.html"); }); var sockets = []; io.on("connection", function(socket){ socket.on("client", function(data){ //client sent message }); console.log("in connection."); var key = Date.now; sockets[key] = socket; socket.on("disconnect", function(){ delete sockets[key]; }); }); amqp.connect("amqp://test:test@192.168.121.129", function(connerr, connection){ connection.createChannel(function(channelerr, channel){ var queueName = "node-log-rabbitmq"; channel.assertQueue(queueName, {durable:false}); channel.bindQueue(queueName, "topic-log-test", "#"); channel.consume(queueName, function(msg){ if(msg!= null){ var logMsg = msg.content.toString(); channel.ack(msg); console.log("log message: ", logMsg); io.emit("logs", logMsg); } }); }); }); <file_sep>/Alan.Log/ILogImplement/LogSingleFile.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Alan.Log.Core; namespace Alan.Log.ILogImplement { /// <summary> /// 单文件日志 /// </summary> public class LogSingleFile : ILog { private static object _lock = new object(); /// <summary> /// 是否在写日志的时候添加注释 /// </summary> public bool AppendCommentName { get; set; } /// <summary> /// 日志文件路径 /// </summary> public string LogFileFullPath { get; set; } /// <summary> /// 实例化日志模块 /// </summary> public LogSingleFile() { this.LogFileFullPath = Path.Combine(Environment.CurrentDirectory, "LogSingleFileClear.txt"); this.AppendCommentName = true; } /// <summary> /// 实例化日志模块 /// </summary> /// <param name="logFileFullPath">日志绝对路径</param> public LogSingleFile(string logFileFullPath) { this.LogFileFullPath = logFileFullPath; } /// <summary> /// 实例化日志模块 /// </summary> /// <param name="logFileFullPath">日志绝对路径</param> /// <param name="appenComment">是否添加注释前缀</param> public LogSingleFile(string logFileFullPath, bool appenComment) { this.LogFileFullPath = logFileFullPath; this.AppendCommentName = appenComment; } public LogSingleFile Config(string fullPath) { this.LogFileFullPath = fullPath; return this; } /// <summary> /// 写日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者</param> /// <param name="category">分类(比如 注册/订单/支付/添加好友)</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="request">请求内容</param> /// <param name="response">响应内容</param> /// <param name="position">输出位置</param> public void Write(string id, DateTime date, string level, string logger, string category, string message, string note, string request, string response, string position) { var lines = new List<string>(); if (this.AppendCommentName) { if (!String.IsNullOrWhiteSpace(id)) lines.Add(String.Format("{0,-10}: {1}", "Id", id)); if (date != default(DateTime)) lines.Add(String.Format("{0,-10}: {1}", "Date", date.ToString("yyyy-MM-dd HH:mm:ss"))); if (!String.IsNullOrWhiteSpace(level)) lines.Add(String.Format("{0,-10}: {1}", "Level", level)); if (!String.IsNullOrWhiteSpace(logger)) lines.Add(String.Format("{0,-10}: {1}", "Logger", logger)); if (!String.IsNullOrWhiteSpace(category)) lines.Add(String.Format("{0,-10}: {1}", "Category", category)); if (!String.IsNullOrWhiteSpace(message)) lines.Add(String.Format("{0,-10}: {1}", "Message", message)); if (!String.IsNullOrWhiteSpace(note)) lines.Add(String.Format("{0,-10}: {1}", "Note", note)); if (!String.IsNullOrWhiteSpace(request)) lines.Add(String.Format("{0,-10}: {1}", "Request", request)); if (!String.IsNullOrWhiteSpace(response)) lines.Add(String.Format("{0,-10}: {1}", "Response", response)); if (!String.IsNullOrWhiteSpace(position)) lines.Add(String.Format("{0,-10}: {1}", "Position", position)); } else { if (!String.IsNullOrWhiteSpace(id)) lines.Add(id); if (date != default(DateTime)) lines.Add(date.ToString("yyyy-MM-dd HH:mm:ss")); if (!String.IsNullOrWhiteSpace(level)) lines.Add(level); if (!String.IsNullOrWhiteSpace(logger)) lines.Add(logger); if (!String.IsNullOrWhiteSpace(category)) lines.Add(category); if (!String.IsNullOrWhiteSpace(message)) lines.Add(message); if (!String.IsNullOrWhiteSpace(note)) lines.Add(note); if (!String.IsNullOrWhiteSpace(request)) lines.Add(request); if (!String.IsNullOrWhiteSpace(response)) lines.Add(response); if (!String.IsNullOrWhiteSpace(position)) lines.Add(position); } var text = String.Join(Environment.NewLine, lines) + Environment.NewLine; var dir = System.IO.Path.GetDirectoryName(this.LogFileFullPath); lock (_lock) { if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir); System.IO.File.AppendAllText(this.LogFileFullPath, text, System.Text.Encoding.UTF8); } } } } <file_sep>/Alan.Log.RabbitMQ/LogRabbitMQ.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Alan.Log.Core; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace Alan.Log.RabbitMQ { public class LogRabbitMQ : ILog { /// <summary> /// RabbitMQ Broker 服务地址 /// </summary> private string _rabbitMqHost; /// <summary> /// RabbitMQ Broker 端口号 /// </summary> private int _rabbitMqPort; /// <summary> /// RabbitMQ 用户名 /// </summary> private string _rabbitMqUserName; /// <summary> /// RabbitMQ 密码 /// </summary> private string _rabbitMqPassword; /// <summary> /// RabbitMQ 交换器名称 /// </summary> private string _rabbitMqExchange; /// <summary> /// RabbitMQ 虚机主机名 /// </summary> private string _rabbitMqVirtualHost; /// <summary> /// 创建实例 /// </summary> /// <param name="host">RabbitMQ Broker 地址</param> /// <param name="userName">用户名</param> /// <param name="passWord">密码</param> /// <param name="exchange">交换器名</param> public LogRabbitMQ(string host, string userName, string passWord, string exchange) : this(host, userName, passWord, exchange, "/", 5672) { } /// <summary> /// 创建实例 /// </summary> /// <param name="host">RabbitMQ Broker 地址</param> /// <param name="userName">用户名</param> /// <param name="passWord">密码</param> /// <param name="exchange">交换器名</param> /// <param name="vhost">虚拟主机名</param> public LogRabbitMQ(string host, string userName, string passWord, string exchange, string vhost) : this(host, userName, passWord, exchange, vhost, 5672) { } /// <summary> /// 创建实例 /// </summary> /// <param name="host">RabbitMQ Broker 地址</param> /// <param name="userName">用户名</param> /// <param name="passWord">密码</param> /// <param name="exchange">交换器名</param> /// <param name="vhost">虚拟主机名</param> /// <param name="port">RabbitMQ Broker端口号</param> public LogRabbitMQ(string host, string userName, string passWord, string exchange, string vhost, int port) { this._rabbitMqHost = host; this._rabbitMqUserName = userName; this._rabbitMqPassword = <PASSWORD>; this._rabbitMqExchange = exchange; this._rabbitMqVirtualHost = vhost; this._rabbitMqPort = port; var channel = Channel; channel.ExchangeDeclare(exchange: this._rabbitMqExchange, type: "topic", durable: false, autoDelete: false, arguments: null); } private IModel _internalChannel; private IModel Channel { get { if (this._internalChannel != null && this._internalChannel.IsOpen) return this._internalChannel; var factory = new ConnectionFactory() { HostName = this._rabbitMqHost, UserName = this._rabbitMqUserName, Password = <PASSWORD>, VirtualHost = this._rabbitMqVirtualHost }; var connection = factory.CreateConnection(); this._internalChannel = connection.CreateModel(); return this._internalChannel; } } /// <summary> /// 输入日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">发布者</param> /// <param name="category">分类(分类必须为字母, 且不能为空)</param> /// <param name="message">消息内容</param> /// <param name="note">备注</param> /// <param name="request">请求内容</param> /// <param name="response">响应内容</param> /// <param name="position">位置</param> public void Write(string id, DateTime date, string level, string logger, string category, string message, string note, string request, string response, string position) { if (String.IsNullOrWhiteSpace(category) || !Regex.IsMatch(category, @"(\w|\-)+")) category = "all"; if (date == default(DateTime)) date = DateTime.Now; var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { Id = id, Date = date, Level = level, Logger = logger, Category = category, Message = message, Note = note, Request = request, Response = response, Position = position }); this.Channel.BasicPublish(exchange: this._rabbitMqExchange, routingKey: String.Format("{0}.{1}", category, level), basicProperties: null, body: Encoding.UTF8.GetBytes(json)); } } } <file_sep>/Alan.Log.Bmob/Utils/LogModel.cs using cn.bmob.io; namespace Alan.Log.Bmob.Utils { /// <summary> /// 日志模型 /// </summary> public class LogModel : BmobTable { /// <summary> /// 编号/标识 /// </summary> public string Id { get; set; } /// <summary> /// 日期 /// </summary> public BmobDate Date { get; set; } /// <summary> /// 级别 /// </summary> public string Level { get; set; } /// <summary> /// 记录者 /// </summary> public string Logger { get; set; } /// <summary> /// 分类(比如: 注册日志, 订单日志, 支付日志) /// </summary> public string Category { get; set; } /// <summary> /// 消息 /// </summary> public string Message { get; set; } /// <summary> /// 备注 /// </summary> public string Note { get; set; } /// <summary> /// 请求内容 /// </summary> public string Request { get; set; } /// <summary> /// 输出内容 /// </summary> public string Response { get; set; } /// <summary> /// 位置 /// </summary> public string Position { get; set; } private string _tableName; /// <summary> /// 实例化 LogModel 表名默认为 BmobLogs /// </summary> public LogModel() : this("BmobLogs") { } /// <summary> /// 实例化 LogModel /// </summary> /// <param name="tableName">表名</param> public LogModel(string tableName) { this._tableName = tableName; } public override string table { get { return this._tableName; } } //读字段信息 public override void readFields(BmobInput input) { base.readFields(input); this.Id = input.getString(nameof(this.Id)); this.Date = input.getDate(nameof(this.Date)); this.Level = input.getString(nameof(this.Level)); this.Logger = input.getString(nameof(this.Logger)); this.Category = input.getString(nameof(this.Category)); this.Message = input.getString(nameof(this.Message)); this.Note = input.getString(nameof(this.Note)); this.Request = input.getString(nameof(this.Request)); this.Response = input.getString(nameof(this.Response)); this.Position = input.getString(nameof(this.Position)); } //写字段信息 public override void write(BmobOutput output, bool all) { base.write(output, all); output.Put(nameof(this.Id), this.Id); output.Put(nameof(this.Date), this.Date); output.Put(nameof(this.Level), this.Level); output.Put(nameof(this.Logger), this.Logger); output.Put(nameof(this.Category), this.Category); output.Put(nameof(this.Message), this.Message); output.Put(nameof(this.Note), this.Note); output.Put(nameof(this.Request), this.Request); output.Put(nameof(this.Response), this.Response); output.Put(nameof(this.Position), this.Position); } } } <file_sep>/Alan.Log/ILogImplement/LogEmail.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using Alan.Log.Core; namespace Alan.Log.ILogImplement { /// <summary> /// 发送E-mail日志 /// 网易邮箱 SSL: false, Port: 25 测试通过 /// QQ邮箱 SSL: true, Port: 587 测试通过 /// </summary> public class LogEmail : ILog { /// <summary> /// Sender UserName /// </summary> public string UserName { get; set; } /// <summary> /// Sender Password /// </summary> public string PassWord { get; set; } /// <summary> /// SMTP Server Address /// </summary> public string SmtpHost { get; set; } /// <summary> /// SMTP Server Port /// </summary> public int SmtpPort { get; set; } /// <summary> /// SMTP enabled SSL /// </summary> public bool EnableSsl { get; set; } /// <summary> /// Sender e-mail address /// </summary> public string Sender { get; set; } /// <summary> /// Receiver e-mail address /// </summary> public string Receivers { get; set; } /// <summary> /// 发送者姓名 /// </summary> public string SenderName { get; set; } public LogEmail() { this.SmtpPort = 587; this.EnableSsl = true; } /// <summary> /// 创建实例 /// </summary> /// <param name="userName">sender用户名</param> /// <param name="passWord">sender密码</param> /// <param name="smtpServer">SMTP Server Address</param> /// <param name="receivers">接收人邮箱地址(多个接收人用空格分隔)</param> public LogEmail(string userName, string passWord, string receivers, string smtpServer) : this(userName, passWord, smtpServer, receivers, 587, true, userName, null) { } /// <summary> /// 创建实例 /// </summary> /// <param name="userName">sender用户名</param> /// <param name="passWord">sender密码</param> /// <param name="smtpServer">SMTP Server Address</param> /// <param name="port">SMTP Port</param> /// <param name="receivers">接收人邮箱地址(多个接收人用空格分隔)</param> public LogEmail(string userName, string passWord, string receivers, string smtpServer, int port) : this(userName, <PASSWORD>Word, receivers, smtpServer, port, true, userName, null) { } /// <summary> /// 创建实例 /// </summary> /// <param name="userName">sender用户名</param> /// <param name="passWord">sender密码</param> /// <param name="smtpServer">SMTP Server Address</param> /// <param name="port">SMTP Port</param> /// <param name="enableSsl">SMTP是否开启SSL</param> /// <param name="receivers">接收人邮箱地址(多个接收人用空格分隔)</param> public LogEmail(string userName, string passWord, string receivers, string smtpServer, int port, bool enableSsl) : this(userName, passWord, receivers, smtpServer, port, enableSsl, userName, null) { } /// <summary> /// 创建实例 /// </summary> /// <param name="userName">sender用户名</param> /// <param name="passWord">sender密码</param> /// <param name="smtpServer">SMTP Server Address</param> /// <param name="port">SMTP Port</param> /// <param name="enableSsl">SMTP是否开启SSL</param> /// <param name="sender">发送人邮箱地址</param> /// <param name="receivers">接收人邮箱地址(多个接收人用空格分隔)</param> /// <param name="senderName">发送人姓名</param> public LogEmail(string userName, string passWord, string receivers, string smtpServer, int port, bool enableSsl, string sender, string senderName) { this.UserName = userName; this.PassWord = <PASSWORD>; this.SmtpHost = smtpServer; this.SmtpPort = port; this.EnableSsl = enableSsl; this.Sender = sender; this.Receivers = receivers; this.SenderName = senderName; } /// <summary> /// 写日志 /// </summary> /// <param name="id">编号</param> /// <param name="date">日期</param> /// <param name="level">级别</param> /// <param name="logger">标识者</param> /// <param name="category">分类(比如 注册/订单/支付/添加好友)</param> /// <param name="message">消息</param> /// <param name="note">备注</param> /// <param name="request">请求内容</param> /// <param name="response">响应内容</param> /// <param name="position">输出位置</param> public void Write(string id, DateTime date, string level, string logger, string category, string message, string note, string request, string response, string position) { if (String.IsNullOrWhiteSpace(this.UserName)) throw new NullReferenceException("UserName can't be empty"); if (String.IsNullOrWhiteSpace(this.PassWord)) throw new NullReferenceException("PassWord can't be empty"); if (String.IsNullOrWhiteSpace(this.SmtpHost)) throw new NullReferenceException("Host can't be empty"); if (String.IsNullOrWhiteSpace(this.Receivers)) throw new NullReferenceException("Receives can't be empty"); if (String.IsNullOrWhiteSpace(this.Sender)) this.Sender = this.UserName; NetworkCredential credential = new NetworkCredential(this.UserName, this.PassWord); SmtpClient smtp = new SmtpClient() { EnableSsl = this.EnableSsl, Port = this.SmtpPort, Host = this.SmtpHost, UseDefaultCredentials = true, Credentials = credential }; var logs = new List<string>(); logs.Add(Environment.NewLine); logs.Add(String.Format("{0} Id: {1}, Date: {2}, Level: {3} {0}", String.Join("", Enumerable.Repeat("=", 10)), id, date.ToString("yyyy-MM-dd HH:mm:ss"), level)); if (!String.IsNullOrWhiteSpace(logger)) logs.Add(String.Format("Logger: {0}", logger)); if (!String.IsNullOrWhiteSpace(category)) logs.Add(String.Format("Category: {0}", category)); if (!String.IsNullOrWhiteSpace(message)) logs.Add(String.Format("Message: {0}", message)); if (!String.IsNullOrWhiteSpace(note)) logs.Add(String.Format("Note: {0}", note)); if (!String.IsNullOrWhiteSpace(request)) logs.Add(String.Format("Request: {0}", request)); if (!String.IsNullOrWhiteSpace(response)) logs.Add(String.Format("Response: {0}", response)); if (!String.IsNullOrWhiteSpace(position)) logs.Add(String.Format("Position: {0}", position)); logs.Add(String.Format("{0} End {1} {0}", String.Join("", Enumerable.Repeat("=", 10)), id)); logs.Add(Environment.NewLine); var mail = new MailMessage(); mail.From = new MailAddress(this.Sender, this.SenderName ?? logger); this.Receivers.Split(' ').ToList().ForEach(mail.To.Add); mail.Subject = String.Format("Id: {0} Date: {1} Level: {2}", id, date.ToString("yyyy-MM-dd HH:mm:ss"), level); mail.SubjectEncoding = System.Text.Encoding.UTF8; mail.Body = String.Join(Environment.NewLine, logs); mail.BodyEncoding = System.Text.Encoding.UTF8; smtp.Send(mail); } } } <file_sep>/Alan.Log/Models/Log.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Alan.Log.Models { /// <summary> /// 日志模型 /// </summary> public class Log { /// <summary> /// 编号/标识 /// </summary> public string Id { get; set; } /// <summary> /// 日期 /// </summary> public DateTime Date { get; set; } /// <summary> /// 级别 /// </summary> public LogLevel Level { get; set; } /// <summary> /// 记录者 /// </summary> public string Logger { get; set; } /// <summary> /// 分类(比如: 注册日志, 订单日志, 支付日志) /// </summary> public string Category { get; set; } /// <summary> /// 消息 /// </summary> public string Message { get; set; } /// <summary> /// 备注 /// </summary> public string Note { get; set; } /// <summary> /// 请求内容 /// </summary> public string Request { get; set; } /// <summary> /// 输出内容 /// </summary> public string Response { get; set; } /// <summary> /// 位置 /// </summary> public string Position { get; set; } /// <summary> /// 日志级别 /// </summary> public enum LogLevel { /// <summary> /// 危险 /// </summary> Critical, /// <summary> /// 错误/异常 /// </summary> Error, /// <summary> /// 警告 /// </summary> Warning, /// <summary> /// 信息 /// </summary> Info, /// <summary> /// 调试 /// </summary> Debug, /// <summary> /// 捕获/跟踪 /// </summary> Trace, /// <summary> /// 无 /// </summary> None } } }
f40efd2ae99759348b06148656d154a90a3ad064
[ "Markdown", "C#", "JavaScript" ]
26
C#
ywuwgij/Alan.Log
45c4c71e084f9cde826d94d8caa92b44c1eae490
84f3144a85e11493320675877089ac72309e2623
refs/heads/master
<file_sep>#!/usr/bin/env ruby require_relative "../lib/api_communicator.rb" require_relative "../lib/command_line_interface.rb" welcome character = get_character_from_user # character = "<NAME>" show_character_movies(character)
334559356db2d8387486a92e714b95ea3813b1ad
[ "Ruby" ]
1
Ruby
UnglazedPottery/apis-and-iteration-houston-web-080519
610da320e741f4e4dc252df662e4bf998887314b
22fa07e0bc8b864a24b7bcc629fa66eadab9a8b8
refs/heads/master
<file_sep>$(function(){ window.sr = ScrollReveal(); if ($(window).width() < 768) { if ($('.timeline-content').hasClass('js--fadeInLeft')) { $('.timeline-content').removeClass('js--fadeInLeft').addClass('js--fadeInRight'); } sr.reveal('.js--fadeInRight', { origin: 'right', distance: '300px', easing: 'ease-in-out', duration: 800, }); } else { sr.reveal('.js--fadeInLeft', { origin: 'left', distance: '300px', easing: 'ease-in-out', duration: 800, }); sr.reveal('.js--fadeInRight', { origin: 'right', distance: '300px', easing: 'ease-in-out', duration: 800, }); } sr.reveal('.js--fadeInLeft', { origin: 'left', distance: '300px', easing: 'ease-in-out', duration: 800, }); sr.reveal('.js--fadeInRight', { origin: 'right', distance: '300px', easing: 'ease-in-out', duration: 800, }); }); $(document).ready(function() { const navbar = document.getElementById("navbar"); const navbarToggle = navbar.querySelector(".navbar-toggle"); function openMobileNavbar() { navbar.classList.add("opened"); navbarToggle.setAttribute("aria-label", "Close navigation menu."); } function closeMobileNavbar() { navbar.classList.remove("opened"); navbarToggle.setAttribute("aria-label", "Open navigation menu."); } navbarToggle.addEventListener("click", () => { if (navbar.classList.contains("opened")) { closeMobileNavbar(); } else { openMobileNavbar(); } }); const navbarMenu = navbar.querySelector(".navbar-menu"); const navbarLinksContainer = navbar.querySelector(".navbar-links"); navbarLinksContainer.addEventListener("click", (clickEvent) => { clickEvent.stopPropagation(); }); navbarMenu.addEventListener("click", closeMobileNavbar); document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); document.querySelector(this.getAttribute('href')).scrollIntoView({ behavior: 'smooth' }); }); }); }); <file_sep># My Resume I made this resume to learn and improve my skills in CSS and HTML5. I took this as a personal challenge to see what could I do using CSS only (without a framework like bootstrap). Maybe you have some recomendations and improvements to do in the code. I'll be happy to hear about it.
018afa11714ebadbad65643842dc9a285476a981
[ "JavaScript", "Markdown" ]
2
JavaScript
lucaspichi06/my-resume
4c0676e967331f3a880551be35b09ed4a74a6880
2b294bed73f6ac7a66d589c2e5c5a54a85771e68
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LGRentalMgntSystem { class DatabaseAccess { #region "Constructor & Distructor" private bool disposed = false; public DatabaseAccess() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~DatabaseAccess() { Dispose(false); } #endregion SqlConnection _con; Boolean _WithTrn = false; SqlTransaction _Trn; #region "Connection" public void OpenConnection(bool WithTrn) { string _conStr = ""; _conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString; _con = new SqlConnection(_conStr); _con.Open(); _WithTrn = WithTrn; if (WithTrn) { _Trn = _con.BeginTransaction(); } } public void RollBack() { if (_Trn != null && _WithTrn == true) { if (_Trn.Connection != null) { _Trn.Rollback(); } } } public void Commit() { if (_Trn != null && _WithTrn == true) { _Trn.Commit(); } } public void CloseConnection(bool WithTrn) { if (_con != null) { if (WithTrn == true) { if (_Trn != null) { _Trn.Commit(); } } if (_con.State != ConnectionState.Closed) { _con.Close(); } } } #endregion #region "Insert Update Delete - Stored Procedure" public int Execute(string StoredProcedureName, DatabaseParameters Parameters) { int _result = 0; int _counter = 0; SqlCommand _sqlcommand = new SqlCommand(); SqlParameter osqlParameter; try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } for (_counter = 0; _counter <= Parameters.Count - 1; _counter++) { osqlParameter = new SqlParameter(); osqlParameter.ParameterName = Parameters[_counter].ParameterName; osqlParameter.SqlDbType = Parameters[_counter].DataType; osqlParameter.Direction = Parameters[_counter].ParameterDirection; osqlParameter.Value = Parameters[_counter].Value; if (Parameters[_counter].Size != null) { if (Parameters[_counter].Size != 0) { osqlParameter.Size = Parameters[_counter].Size; } } _sqlcommand.Parameters.Add(osqlParameter); osqlParameter = null; } _result = _sqlcommand.ExecuteNonQuery(); } catch (Exception ex) { if (_WithTrn == true) { _Trn.Rollback(); } throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } return _result; } public int Execute(string StoredProcedureName) { int _result = 0; SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } _result = _sqlcommand.ExecuteNonQuery(); } catch (Exception ex) { if (_WithTrn == true) { _Trn.Rollback(); } throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } return _result; } public int Execute(string StoredProcedureName, DatabaseParameters Parameters, out object ParameterValue) { int _result = 0; int _counter = 0; SqlCommand _sqlcommand = new SqlCommand(); int _outputCounter = 0; SqlParameter osqlParameter; try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } for (_counter = 0; _counter <= Parameters.Count - 1; _counter++) { if (Parameters[_counter].ParameterDirection == ParameterDirection.Output || Parameters[_counter].ParameterDirection == ParameterDirection.InputOutput) { _outputCounter = _counter; } osqlParameter = new SqlParameter(); osqlParameter.ParameterName = Parameters[_counter].ParameterName; osqlParameter.SqlDbType = Parameters[_counter].DataType; osqlParameter.Direction = Parameters[_counter].ParameterDirection; osqlParameter.Value = Parameters[_counter].Value; if (Parameters[_counter].Size != null) { if (Parameters[_counter].Size != 0) { osqlParameter.Size = Parameters[_counter].Size; } } _sqlcommand.Parameters.Add(osqlParameter); osqlParameter = null; } _result = _sqlcommand.ExecuteNonQuery(); if (_sqlcommand.Parameters[_outputCounter].Value != null) { ParameterValue = _sqlcommand.Parameters[_outputCounter].Value; } else { ParameterValue = 0; } } catch (Exception ex) { if (_WithTrn == true) { _Trn.Rollback(); } throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } return _result; } public int Execute(string StoredProcedureName, DatabaseParameters Parameters, out object ParameterValue1, out object ParameterValue2) { int _result = 0; int _counter = 0; SqlCommand _sqlcommand = new SqlCommand(); int _outputCounter1 = -1; int _outputCounter2 = -1; SqlParameter osqlParameter; try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; for (_counter = 0; _counter <= Parameters.Count - 1; _counter++) { if (Parameters[_counter].ParameterDirection == ParameterDirection.Output || Parameters[_counter].ParameterDirection == ParameterDirection.InputOutput) { if (_outputCounter1 < 0) { _outputCounter1 = _counter; } else if (_outputCounter2 < 0) { _outputCounter2 = _counter; } } osqlParameter = new SqlParameter(); osqlParameter.ParameterName = Parameters[_counter].ParameterName; osqlParameter.SqlDbType = Parameters[_counter].DataType; osqlParameter.Direction = Parameters[_counter].ParameterDirection; osqlParameter.Value = Parameters[_counter].Value; if (Parameters[_counter].Size != null) { if (Parameters[_counter].Size != 0) { osqlParameter.Size = Parameters[_counter].Size; } } _sqlcommand.Parameters.Add(osqlParameter); osqlParameter = null; } _result = _sqlcommand.ExecuteNonQuery(); if (_sqlcommand.Parameters[_outputCounter1].Value != null) { ParameterValue1 = _sqlcommand.Parameters[_outputCounter1].Value; } else { ParameterValue1 = 0; } if (_sqlcommand.Parameters[_outputCounter2].Value != null) { ParameterValue2 = _sqlcommand.Parameters[_outputCounter2].Value; } else { ParameterValue2 = 0; } } catch (Exception ex) { if (_WithTrn == true) { _Trn.Rollback(); } throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } return _result; } public object ExecuteScalar(string StoredProcedureName, DatabaseParameters Parameters) { object _result = null; int _counter = 0; SqlCommand _sqlcommand = new SqlCommand(); SqlParameter osqlParameter; try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } for (_counter = 0; _counter <= Parameters.Count - 1; _counter++) { osqlParameter = new SqlParameter(); osqlParameter.ParameterName = Parameters[_counter].ParameterName; osqlParameter.SqlDbType = Parameters[_counter].DataType; osqlParameter.Direction = Parameters[_counter].ParameterDirection; osqlParameter.Value = Parameters[_counter].Value; if (Parameters[_counter].Size != null) { if (Parameters[_counter].Size != 0) { osqlParameter.Size = Parameters[_counter].Size; } } _sqlcommand.Parameters.Add(osqlParameter); osqlParameter = null; } _result = _sqlcommand.ExecuteScalar(); if (_result == null) { _result = ""; } } catch (Exception ex) { if (_WithTrn == true) { _Trn.Rollback(); } throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } return _result; } public object ExecuteScalar(string StoredProcedureName) { object _result = null; SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } _result = _sqlcommand.ExecuteScalar(); if (_result == null) { _result = ""; } } catch (Exception ex) { if (_WithTrn == true) { _Trn.Rollback(); } throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } return _result; } #endregion #region "Insert Update Delete - SQL Query" public int Execute_Query(string SQLQuery) { int _result = 0; SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.Text; _sqlcommand.CommandText = SQLQuery; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } _result = _sqlcommand.ExecuteNonQuery(); } catch (Exception ex) { if (_WithTrn == true) { _Trn.Rollback(); } throw ex; //throw new DBException("Error in database execution"); } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } return _result; } public object ExecuteScalar_Query(string SQLQuery) { object _result = null; SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.Text; _sqlcommand.CommandText = SQLQuery; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } _result = _sqlcommand.ExecuteScalar(); if (_result == null) { _result = ""; } } catch (Exception ex) { if (_WithTrn == true) { _Trn.Rollback(); } throw ex; //throw new DBException("Error in database execution"); } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } return _result; } public object ExecuteScalar_Query(string SQLQuery, out string ErrorMessage) { object _result = null; SqlCommand _sqlcommand = new SqlCommand(); ErrorMessage = ""; try { _sqlcommand.CommandType = CommandType.Text; _sqlcommand.CommandText = SQLQuery; _sqlcommand.Connection = _con; _result = _sqlcommand.ExecuteScalar(); if (_result == null) { _result = ""; } } catch (Exception ex) { if (_WithTrn == true) { _Trn.Rollback(); } ErrorMessage = ex.ToString(); //throw ex; //throw new DBException("Error in database execution"); } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } return _result; } #endregion #region "Retrive Data - Stored Procedure" public void Retrive(string StoredProcedureName, DatabaseParameters Parameters, out SqlDataReader _result) { //SqlDataReader _result; int _counter = 0; SqlCommand _sqlcommand = new SqlCommand(); SqlParameter osqlParameter; try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } for (_counter = 0; _counter <= Parameters.Count - 1; _counter++) { osqlParameter = new SqlParameter(); osqlParameter.ParameterName = Parameters[_counter].ParameterName; osqlParameter.SqlDbType = Parameters[_counter].DataType; osqlParameter.Direction = Parameters[_counter].ParameterDirection; osqlParameter.Value = Parameters[_counter].Value; if (Parameters[_counter].Size != null) { if (Parameters[_counter].Size != 0) { osqlParameter.Size = Parameters[_counter].Size; } } _sqlcommand.Parameters.Add(osqlParameter); osqlParameter = null; } _result = _sqlcommand.ExecuteReader(); } catch (Exception ex) { throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } //return _result; } public void Retrive(string StoredProcedureName, DatabaseParameters Parameters, out DataSet _result) { //DataSet _result = new DataSet(); int _counter = 0; SqlCommand _sqlcommand = new SqlCommand(); SqlParameter osqlParameter; try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } for (_counter = 0; _counter <= Parameters.Count - 1; _counter++) { osqlParameter = new SqlParameter(); osqlParameter.ParameterName = Parameters[_counter].ParameterName; osqlParameter.SqlDbType = Parameters[_counter].DataType; osqlParameter.Direction = Parameters[_counter].ParameterDirection; osqlParameter.Value = Parameters[_counter].Value; if (Parameters[_counter].Size != null) { if (Parameters[_counter].Size != 0) { osqlParameter.Size = Parameters[_counter].Size; } } _sqlcommand.Parameters.Add(osqlParameter); osqlParameter = null; } SqlDataAdapter _dataAdapter = new SqlDataAdapter(_sqlcommand); DataSet _resultinternal = new DataSet(); //_dataAdapter.Fill(_result); _dataAdapter.Fill(_resultinternal); _dataAdapter.Dispose(); _result = _resultinternal; } catch (Exception ex) { throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } //return _result; } public void Retrive(string StoredProcedureName, DatabaseParameters Parameters, out DataTable _result) { //DataTable _result = new DataTable(); int _counter = 0; SqlCommand _sqlcommand = new SqlCommand(); SqlParameter osqlParameter; try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } for (_counter = 0; _counter <= Parameters.Count - 1; _counter++) { osqlParameter = new SqlParameter(); osqlParameter.ParameterName = Parameters[_counter].ParameterName; osqlParameter.SqlDbType = Parameters[_counter].DataType; osqlParameter.Direction = Parameters[_counter].ParameterDirection; osqlParameter.Value = Parameters[_counter].Value; if (Parameters[_counter].Size != null) { if (Parameters[_counter].Size != 0) { osqlParameter.Size = Parameters[_counter].Size; } } _sqlcommand.Parameters.Add(osqlParameter); osqlParameter = null; } SqlDataAdapter _dataAdapter = new SqlDataAdapter(_sqlcommand); DataSet _dataset = new DataSet(); DataTable _resultinternal = new DataTable(); _dataAdapter.Fill(_dataset); if (_dataset.Tables[0] != null) { _resultinternal = _dataset.Tables[0]; } _result = _resultinternal; _resultinternal.Dispose(); _dataset.Dispose(); _dataAdapter.Dispose(); } catch (Exception ex) { throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } //return _result; } // Without Parameters // public void Retrive(string StoredProcedureName, out SqlDataReader _result) { //SqlDataReader _result; SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } _result = _sqlcommand.ExecuteReader(); } catch (Exception ex) { throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } //return _result; } public void Retrive(string StoredProcedureName, out DataSet _result) { //DataSet _result = new DataSet(); SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } SqlDataAdapter _dataAdapter = new SqlDataAdapter(_sqlcommand); DataSet _resultinternal = new DataSet(); //_dataAdapter.Fill(_result); _dataAdapter.Fill(_resultinternal); _dataAdapter.Dispose(); _result = _resultinternal; } catch (Exception ex) { throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } //return _result; } public void Retrive(string StoredProcedureName, out DataTable _result) { //DataTable _result = new DataTable(); SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.StoredProcedure; _sqlcommand.CommandText = StoredProcedureName; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } SqlDataAdapter _dataAdapter = new SqlDataAdapter(_sqlcommand); DataSet _dataset = new DataSet(); DataTable _resultinternal = new DataTable(); _dataAdapter.Fill(_dataset); if (_dataset.Tables[0] != null) { _resultinternal = _dataset.Tables[0]; } _result = _resultinternal; _resultinternal.Dispose(); _dataset.Dispose(); _dataAdapter.Dispose(); } catch (Exception ex) { throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } //return _result; } #endregion #region "Retrive Data - SQL Query" public void Retrive_Query(string SQLQuery, out SqlDataReader _result) { //SqlDataReader _result; SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.Text; _sqlcommand.CommandText = SQLQuery; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } _result = _sqlcommand.ExecuteReader(); } catch (Exception ex) { throw ex; //throw new DBException("Error in database execution"); } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } //return _result; } public void Retrive_Query(string SQLQuery, out DataSet _result) { //DataSet _result = new DataSet(); SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.Text; _sqlcommand.CommandText = SQLQuery; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } SqlDataAdapter _dataAdapter = new SqlDataAdapter(_sqlcommand); DataSet _resultinternal = new DataSet(); //_dataAdapter.Fill(_result); _dataAdapter.Fill(_resultinternal); _dataAdapter.Dispose(); _result = _resultinternal; } catch (Exception ex) { throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } //return _result; } public void Retrive_Query(string SQLQuery, out DataTable _result) { //DataTable _result = new DataTable(); SqlCommand _sqlcommand = new SqlCommand(); try { _sqlcommand.CommandType = CommandType.Text; _sqlcommand.CommandText = SQLQuery; _sqlcommand.Connection = _con; if (_WithTrn == true) { _sqlcommand.Transaction = _Trn; } SqlDataAdapter _dataAdapter = new SqlDataAdapter(_sqlcommand); DataSet _dataset = new DataSet(); DataTable _resultinternal = new DataTable(); _dataAdapter.Fill(_dataset); if (_dataset.Tables[0] != null) { _resultinternal = _dataset.Tables[0]; } _result = _resultinternal; _resultinternal.Dispose(); _dataset.Dispose(); _dataAdapter.Dispose(); } catch (Exception ex) { throw ex; } finally { if (_sqlcommand != null) { _sqlcommand.Dispose(); } } //return _result; } #endregion } } public class DatabaseParameter : IDisposable { private string _parametername; private ParameterDirection _parameterdirection; private SqlDbType _datatype; private object _value; private int _size = 0; #region "Constructor & Distructor" private bool disposed = false; public DatabaseParameter() { } public DatabaseParameter(string parametername, object value, ParameterDirection parameterdirection, SqlDbType datatype, int fieldsize) { _parametername = parametername; _parameterdirection = parameterdirection; _datatype = datatype; _value = value; _size = fieldsize; } public DatabaseParameter(string parametername, object value, ParameterDirection parameterdirection, SqlDbType datatype) { _parametername = parametername; _parameterdirection = parameterdirection; _datatype = datatype; _value = value; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~DatabaseParameter() { Dispose(false); } #endregion #region "Properties" public string ParameterName { get { return _parametername; } set { _parametername = value; } } public ParameterDirection ParameterDirection { get { return _parameterdirection; } set { _parameterdirection = value; } } public SqlDbType DataType { get { return _datatype; } set { _datatype = value; } } public object Value { get { return _value; } set { _value = value; } } public int Size { get { return _size; } set { _size = value; } } #endregion } public class DatabaseParameters : IDisposable { protected ArrayList _innerList; #region "Constructor & Distructor" private bool disposed = false; public DatabaseParameters() { _innerList = new ArrayList(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~DatabaseParameters() { Dispose(false); } #endregion public int Count { get { return _innerList.Count; } } public void Add(DatabaseParameter item) { _innerList.Add(item); } public int Add(string parametername, object value, ParameterDirection parameterdirection, SqlDbType datatype, int fieldsize) { DatabaseParameter item = new DatabaseParameter(parametername, value, parameterdirection, datatype, fieldsize); return _innerList.Add(item); } public int Add(string parametername, object value, ParameterDirection parameterdirection, SqlDbType datatype) { DatabaseParameter item = new DatabaseParameter(parametername, value, parameterdirection, datatype); return _innerList.Add(item); } public bool Remove(DatabaseParameter item) { bool result = false; DatabaseParameter obj; for (int i = 0; i < _innerList.Count; i++) { obj = new DatabaseParameter(); obj = (DatabaseParameter)_innerList[i]; if (obj.ParameterName == item.ParameterName && obj.DataType == item.DataType) { _innerList.RemoveAt(i); result = true; break; } obj = null; } return result; } public bool RemoveAt(int index) { bool result = false; _innerList.RemoveAt(index); result = true; return result; } public void clear() { _innerList.Clear(); } public DatabaseParameter this[int index] { get { return (DatabaseParameter)_innerList[index]; } } public bool Contains(DatabaseParameter item) { return _innerList.Contains(item); } public int IndexOf(DatabaseParameter item) { return _innerList.IndexOf(item); } public void copyTo(DatabaseParameter[] array, int index) { _innerList.CopyTo(array, index); } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMainKitAssetList : DevExpress.XtraEditors.XtraForm { public frmMainKitAssetList(Int64 KitID) { InitializeComponent(); nKitID = KitID; } public Int64 nKitID { get; set; } private void frmMainKitAssetList_Load(object sender, EventArgs e) { FillAssetKitDetails(nKitID); } private void FillAssetKitDetails(long nKitID) { KitMaster oKitMaster = null; DataTable dtAssetCode = null; try { oKitMaster = new KitMaster(); dtAssetCode = oKitMaster.GetKitAssetList(nKitID); if (dtAssetCode != null) { gvKitAssetList.GridControl.DataSource = dtAssetCode; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void txtSearch_EditValueChanged(object sender, EventArgs e) { try { DataView dv = (DataView)gvKitAssetList.DataSource; //Company Code, Company Name, Country, State, City, Warehouse Supervisor, Company Type, Abbreviation string sSearchText = txtSearch.Text; string fileter = ""; if (sSearchText != "") { fileter = dv.Table.Columns["sUniqueCode"].Caption + " Like '%" + sSearchText + "%'"; dv.RowFilter = fileter; } else { dv.RowFilter = fileter; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } <file_sep>using LGRentalMgntSystem.Class; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmAssetMaster : DevExpress.XtraEditors.XtraForm { public string sMessageboxCaption = string.Empty; public frmAssetMaster() { InitializeComponent(); sMessageboxCaption = System.Configuration.ConfigurationManager.AppSettings["MessageboxCaption"]; } public MasterType MasterType { get; set; } public bool IsMasterSave { get; set; } public Int64 nTypeID { get; set; } public string sTypeName { get; set; } public string sTypeCode { get; set; } public bool bIsAllowAccess { get; set; } public bool bIsAllowSignatory { get; set; } public Int64 nMainTypeID { get; set; } private void frmAssetMaster_Load(object sender, EventArgs e) { try { pnlAssetMainType.Visible = false; switch (MasterType) { case MasterType.CompanyType: { this.Height = 170; lblFormHeader.Text = "Company Type"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; cmbAssetMainType.SelectedValue = nMainTypeID; break; } case MasterType.MaterialType: { this.Height = 170; lblFormHeader.Text = "Material Type"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; cmbAssetMainType.SelectedValue = nMainTypeID; break; } case MasterType.Designation: { this.Height = 216; lblFormHeader.Text = "Designation"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; cmbAssetMainType.SelectedValue = nMainTypeID; if (bIsAllowAccess) { rdAllowAccessYes.Checked=true; rdAllowAccessNo.Checked = false; } else if (bIsAllowAccess==false) { rdAllowAccessYes.Checked=false; rdAllowAccessNo.Checked = true; } if (bIsAllowSignatory) { rdAllowSignatoryYes.Checked = true; rdAllowSignatoryNo.Checked = false; } else if (bIsAllowSignatory == false) { rdAllowSignatoryYes.Checked = false; rdAllowSignatoryNo.Checked = true; } pnlAllowSettings.Visible = true; break; } case MasterType.AssetType: { this.Height = 200; lblFormHeader.Text = "Asset Type"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; FillAssetMaintype(); cmbAssetMainType.SelectedValue = nMainTypeID; pnlAssetMainType.Visible = true; break; } case MasterType.AssetType1: { this.Height = 200; lblFormHeader.Text = "Asset Type1"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; FillAssetMaintype(); cmbAssetMainType.SelectedValue = nMainTypeID; pnlAssetMainType.Visible = true; break; } case MasterType.PartyType: { this.Height = 170; lblFormHeader.Text = "Party Type"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; cmbAssetMainType.SelectedValue = nMainTypeID; break; } case MasterType.VehicleType: { this.Height = 170; lblFormHeader.Text = "Vehicle Type"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; cmbAssetMainType.SelectedValue = nMainTypeID; break; } case MasterType.ColourType: { this.Height = 170; lblFormHeader.Text = "Colour Type"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; cmbAssetMainType.SelectedValue = nMainTypeID; break; } case MasterType.DensityType: { this.Height = 170; lblFormHeader.Text = "Density Type"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; cmbAssetMainType.SelectedValue = nMainTypeID; break; } case MasterType.AssetMainType: { this.Height = 170; lblFormHeader.Text = "Asset Main Type"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; cmbAssetMainType.SelectedValue = nMainTypeID; break; } case MasterType.Make: { this.Height = 170; lblFormHeader.Text = "Make"; lblTypeID.Text = Convert.ToString(nTypeID); txtMainTypeName.Text = sTypeName; txtMasterCode.Text = sTypeCode; cmbAssetMainType.SelectedValue = nMainTypeID; break; } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void FillAssetMaintype() { clsMasters clsMaster = null; DataTable dtAssetMainMaster = null; try { clsMaster = new clsMasters(); dtAssetMainMaster = clsMaster.GetAssetMainMasterType(1); DataRow dr = dtAssetMainMaster.NewRow(); dr["nAssetMainTypeID"]=0; dr["sAssetType"] = ""; dtAssetMainMaster.Rows.InsertAt(dr, 0); cmbAssetMainType.DataSource = dtAssetMainMaster; cmbAssetMainType.DisplayMember = "sAssetType"; cmbAssetMainType.ValueMember = "nAssetMainTypeID"; } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (clsMaster != null) { clsMaster = null; } } } private void btnSave_Click(object sender, EventArgs e) { if (txtMainTypeName.Text.Trim()=="") { MessageBox.Show("Please Enter " + lblFormHeader.Text + ".", sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); txtMainTypeName.Focus(); return; } if (txtMasterCode.Text.Trim() == "") { MessageBox.Show("Please Enter Code for " + lblFormHeader.Text + ".", sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); txtMasterCode.Focus(); return; } switch (MasterType) { case MasterType.AssetType: case MasterType.AssetType1: { if (Convert.ToInt64(cmbAssetMainType.SelectedValue) == 0) { MessageBox.Show("Please Select Main Asset Type.", sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning); txtMainTypeName.Focus(); return; } break; } } clsMasters clsMaster = null; try { bool bIsAllowAccess = false; bool bIsAllowSignatory = false; if (rdAllowAccessYes.Checked) { bIsAllowAccess = true; } else if(rdAllowAccessNo.Checked) { bIsAllowAccess = false; } if (rdAllowSignatoryYes.Checked) { bIsAllowSignatory = true; } else if (rdAllowSignatoryNo.Checked) { bIsAllowSignatory = false; } clsMaster = new clsMasters(); clsMaster.MasterType = this.MasterType; clsMaster.nMasterID = Convert.ToInt64(lblTypeID.Text); clsMaster.nMasterMainID = Convert.ToInt64(cmbAssetMainType.SelectedValue); clsMaster.sMasterName = txtMainTypeName.Text.Trim(); clsMaster.sMasterCode = txtMasterCode.Text.Trim(); clsMaster.IsAllowAccess = bIsAllowAccess; clsMaster.IsAllowSignatory = bIsAllowSignatory; Int64 nResult=clsMaster.InsertUpdateMaster(); if(nResult==-1) { MessageBox.Show("Error while saving " + lblFormHeader.Text + ".", sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (nResult == 2) { MessageBox.Show(lblFormHeader.Text + " is already exists.", sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(lblFormHeader.Text + " is saved successfully.", sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); ClearForm(); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (clsMaster!=null) { clsMaster = null; } } } private void ClearForm() { txtMainTypeName.Text = string.Empty; txtMasterCode.Text = string.Empty; cmbAssetMainType.SelectedValue = 0; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMainAssetList : DevExpress.XtraEditors.XtraForm { public frmMainAssetList() { InitializeComponent(); } private void frmMainAssetList_Load(object sender, EventArgs e) { FillAssetList(); } private void FillAssetList() { AssetMaster oAssetMaster = null; DataTable dt = null; try { oAssetMaster = new AssetMaster(); dt = oAssetMaster.GetAssetList(0); if (dt!=null) { gvAssetList.GridControl.DataSource = dt; gvAssetList.Columns[1].Visible = false; gvAssetList.Columns[8].Visible = false; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void txtSearch_EditValueChanged(object sender, EventArgs e) { try { DataView dv = (DataView)gvAssetList.DataSource; //Company Code, Company Name, Country, State, City, Warehouse Supervisor, Company Type, Abbreviation string sSearchText = txtSearch.Text; string fileter = ""; if (sSearchText != "") { fileter = dv.Table.Columns["sAssetName"].Caption + " Like '%" + sSearchText + "%' OR " + dv.Table.Columns["sAssetAbbrivation"].Caption + " Like '%" + sSearchText + "%'"; dv.RowFilter = fileter; } else { dv.RowFilter = fileter; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void gvAssetList_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e) { try { if (e.Column.Caption == "Delete") { int nVal = Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; bool val = Convert.ToBoolean(nVal); if (val) { DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; ritem.ReadOnly = false; ritem.Buttons[0].Enabled = false; ritem.Buttons[0].Visible = false; e.RepositoryItem = ritem; } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void gvAssetList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e) { try { if (e.Column.Caption == "Edit") { Int64 nAssetID = 0; var row = gvAssetList.GetFocusedDataRow(); nAssetID = Convert.ToInt64(row[1]); frmAddAsset frmAsset = new frmAddAsset(nAssetID); frmAsset.ShowDialog(); FillAssetList(); } if (e.Column.Caption == "Delete") { var row = gvAssetList.GetFocusedDataRow(); int n = Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; if (n == 1) { return; } if (MessageBox.Show("Do you want to delete?", clsGlobal._sMessageboxCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } AssetMaster oAssetMaster = new AssetMaster(); oAssetMaster.nAssetID=Convert.ToInt64(row[1]); if (oAssetMaster.DeleteAsset() > 0) { MessageBox.Show("Asset details deleted successfully.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } if (oAssetMaster != null) { oAssetMaster.Dispose(); oAssetMaster = null; } //clsMasters oclsMaster = new clsMasters(); //oclsMaster.nMasterID = Convert.ToInt64(row[1]); //oclsMaster.MasterType = this.MasterType; //oclsMaster.DeleteMaster(); FillAssetList(); } if (e.Column.Caption == "Show Asset") { Int64 nAssetID = 0; var row = gvAssetList.GetFocusedDataRow(); nAssetID = Convert.ToInt64(row[1]); frmMainAssetCodeList oFrmAssetCodeList = new frmMainAssetCodeList(nAssetID); oFrmAssetCodeList.ShowDialog(); FillAssetList(); } } catch (Exception ex) { MessageBox.Show("Error : " + ex, clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmAddKit : DevExpress.XtraEditors.XtraForm { public frmAddKit() { InitializeComponent(); lblKitID.Text = "0"; GetAndSetSequence(); FillAllAsset(); txtKitName.Focus(); } public frmAddKit(Int64 nKitID) { InitializeComponent(); lblKitID.Text = Convert.ToString(nKitID); GetAndSetSequence(); FillAllAsset(); txtKitName.Focus(); } DataTable dtAssetCode = new DataTable(); private void GetAndSetSequence() { clsGeneral oclsGeneral = null; try { oclsGeneral = new clsGeneral(); txtKitCode.Text = "KIT/" + Convert.ToString(oclsGeneral.GetSequenceNumber_Transaction(TransactionType.Kit)); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } } } private void FillAllAsset() { AssetCode oAsset = null; DataTable dtAssetList = null; try { oAsset = new AssetCode(); dtAssetList = oAsset.GetAssetCode(); if (dtAssetList != null) { DataRow drAsset = dtAssetList.NewRow(); drAsset["nAssetCodeID"] = 0; drAsset["sAssetCodeName"] = ""; dtAssetList.Rows.InsertAt(drAsset, 0); cmbAssetList.DataSource = dtAssetList; cmbAssetList.DisplayMember = "sAssetCodeName"; cmbAssetList.ValueMember = "nAssetCodeID"; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void frmAddKit_Load(object sender, EventArgs e) { FillAssetCode(); if (Convert.ToInt64(lblKitID.Text)>0) { pnlSave.Visible = false; FillKitInformation(Convert.ToInt64(lblKitID.Text)); } } private void FillAssetCode(Int64 nKitID = 0) { KitMaster oKit = null; try { oKit = new KitMaster(); dtAssetCode = oKit.GetKitAssetAssociation(nKitID); if (dtAssetCode != null) { gvAssetList.GridControl.DataSource = dtAssetCode; gvAssetList.Columns[1].Visible = false; gvAssetList.Columns[2].Visible = false; gvAssetList.Columns[5].Visible = false; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void FillKitInformation(long nKitID) { KitMaster oKitMaster = null; DataSet ds = null; try { oKitMaster = new KitMaster(); ds = oKitMaster.GetKitDetails(nKitID); if (ds!=null&&ds.Tables.Count>0) { DataTable dtKitDetails = ds.Tables[0]; DataTable dtKitAssetDetails = ds.Tables[1]; if (dtKitDetails!=null&&dtKitDetails.Rows.Count>0) { lblKitID.Text = Convert.ToString(dtKitDetails.Rows[0]["nKitID"]); txtKitName.Text = Convert.ToString(dtKitDetails.Rows[0]["sKitName"]); txtKitCode.Text = Convert.ToString(dtKitDetails.Rows[0]["sKitCode"]); txtAbbrivation.Text = Convert.ToString(dtKitDetails.Rows[0]["sKitAbbrivation"]); txtKitDescription.Text = Convert.ToString(dtKitDetails.Rows[0]["sKitDescription"]); byte[] barcodeImage = (byte[])dtKitDetails.Rows[0]["Barcode"]; if (barcodeImage.Length > 0) { barcodeImage = (byte[])dtKitDetails.Rows[0]["Barcode"]; MemoryStream msHeaderImage = new MemoryStream(barcodeImage); picBarcodeImage.Image = Image.FromStream(msHeaderImage); } } if (dtKitAssetDetails!=null) { gvAssetList.GridControl.DataSource = dtKitAssetDetails; gvAssetList.Columns[1].Visible = false; gvAssetList.Columns[2].Visible = false; gvAssetList.Columns[5].Visible = false; } btnUpdateKit.Visible = true; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void txtKitName_EditValueChanged(object sender, EventArgs e) { txtAbbrivation.Text = clsGlobal.GenerateAbbrivation(txtKitName.Text.Trim()); } private void btnAddAsset_Click(object sender, EventArgs e) { try { if (ValidateAssetCode()) { int num = 0; string sValue = string.Empty; num = dtAssetCode.Rows.Count; num++; sValue = num.ToString(); if (num < 1000) { sValue = num.ToString("000"); } if (Convert.ToInt64(lblKitID.Text) > 0) { KitAsset oKitAsset = null; if (btnAddAsset.Text.ToLower() == "add") { string[] sKitAssetName = cmbAssetList.Text.Trim().Split('-'); oKitAsset = new KitAsset(); oKitAsset.nAssetID = 0; oKitAsset.nAssetCodeID = Convert.ToInt64(cmbAssetList.SelectedValue); oKitAsset.nKitAssetID = 0; oKitAsset.nKitID = Convert.ToInt64(lblKitID.Text); oKitAsset.sAssetName = Convert.ToString(sKitAssetName[0]); oKitAsset.sUniqueCode = Convert.ToString(sKitAssetName[1]); oKitAsset.sAssetNameWithCode = Convert.ToString(cmbAssetList.Text); } else if (btnAddAsset.Text.ToLower() == "edit") { string[] sKitAssetName = cmbAssetList.Text.Trim().Split('-'); oKitAsset = new KitAsset(); oKitAsset.nAssetID = Convert.ToInt64(lblAssetID.Text); oKitAsset.nAssetCodeID = Convert.ToInt64(lblAssetCodeID.Text); oKitAsset.nKitAssetID = Convert.ToInt64(lblKitAssetID.Text); oKitAsset.nKitID = Convert.ToInt64(lblKitID.Text); oKitAsset.sAssetName = Convert.ToString(sKitAssetName[0]); oKitAsset.sUniqueCode = Convert.ToString(sKitAssetName[1]); oKitAsset.sAssetNameWithCode = Convert.ToString(lblAssetCodeName.Text); } Int64 nStatus = oKitAsset.UpdateAssetCode(); if (nStatus > 0) { FillAssetCode(oKitAsset.nKitID); } } else { string[] sKitAssetName = cmbAssetList.Text.Trim().Split('-'); DataRow drKit = dtAssetCode.NewRow(); drKit["RowNo"] = num; drKit["nKitAssetID"] = 0; drKit["nKitID"] = 0; drKit["nAssetID"] = 0; drKit["nAssetCodeID"] = Convert.ToInt64(cmbAssetList.SelectedValue); drKit["sUniqueCode"] = sKitAssetName[1]; drKit["sAssetName"] = sKitAssetName[0]; drKit["assetNameWithCode"] = cmbAssetList.Text.Trim(); dtAssetCode.Rows.Add(drKit); gvAssetList.GridControl.DataSource = dtAssetCode; gvAssetList.Columns[1].Visible = false; gvAssetList.Columns[2].Visible = false; gvAssetList.Columns[5].Visible = false; } ClearKitDetails(); } } catch (Exception ex) { MessageBox.Show("Error asset code: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool ValidateAssetCode() { bool bIsValid = true; if (cmbAssetList.Text.Trim()=="") { MessageBox.Show("Select Asset Code.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); cmbAssetList.Focus(); return false; } if (Convert.ToInt64(lblKitID.Text)<=0) { Int64 nAssetCodeID = Convert.ToInt64(cmbAssetList.SelectedValue); DataRow[] dr = dtAssetCode.Select("nAssetCodeID=" + Convert.ToString(nAssetCodeID)); if (dr.Length>0) { MessageBox.Show("Asset Code already exist.\nPlease select other asset code.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); cmbAssetList.Focus(); return false; } } return bIsValid; } private void ClearKitDetails() { cmbAssetList.SelectedValue = 0; txtAssetCode.Text = ""; } private void ClearKit() { txtKitName.Text = ""; txtAbbrivation.Text = ""; txtKitDescription.Text = ""; if (picBarcodeImage != null) { picBarcodeImage.Image = null; } GetAndSetSequence(); FillAssetCode(); } private void gvAssetList_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e) { } private void gvAssetList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e) { try { if (e.Column.Caption == "Edit") { Int64 nKitID = 0; var row = gvAssetList.GetFocusedDataRow(); lblKitAssetID.Text = Convert.ToString(row[1]); lblKitID.Text = Convert.ToString(row[2]); lblAssetID.Text = Convert.ToString(row[3]); lblAssetCodeID.Text = Convert.ToString(row[4]); lblAssetCodeName.Text = Convert.ToString(row[7]); DataTable dtAssetList =(DataTable) cmbAssetList.DataSource; DataRow drAsset = dtAssetList.NewRow(); drAsset["nAssetCodeID"] = lblAssetCodeID.Text; drAsset["sAssetCodeName"] = Convert.ToString(row[7]); dtAssetList.Rows.InsertAt(drAsset, 0); cmbAssetList.DataSource = dtAssetList; cmbAssetList.DisplayMember = "sAssetCodeName"; cmbAssetList.ValueMember = "nAssetCodeID"; cmbAssetList.SelectedIndex = 0; btnAddAsset.Text = "Edit"; } if (e.Column.Caption == "Delete") { var row = gvAssetList.GetFocusedDataRow(); int n = Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; if (n == 1) { return; } if (Convert.ToInt64(lblKitID.Text)>0) { Int64 nKitAssetID = Convert.ToInt64(row["nKitAssetID"]); KitAsset oKitAsset = new KitAsset(); oKitAsset.nKitAssetID = nKitAssetID; if(oKitAsset.DeleteKitAsset()>0) { MessageBox.Show("Asset code deleted successfully.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Asset code not deleted.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } FillAssetCode(Convert.ToInt64(lblKitID.Text)); if (oKitAsset!=null) { oKitAsset.Dispose(); oKitAsset = null; } } else { Int64 nAssetCodeID = Convert.ToInt64(row["nAssetCodeID"]); DataRow[] drDelete = dtAssetCode.Select("nAssetCodeID=" + Convert.ToInt64(nAssetCodeID)); foreach (DataRow dr in drDelete) { dr.Delete(); } dtAssetCode.AcceptChanges(); int nRow = 0; foreach (DataRow dr in dtAssetCode.Rows) { nRow++; dr["RowNo"] = nRow; } //gvAssetList.GridControl.DataSource = dtAssetCode; //gvAssetList.RefreshData(); } gvAssetList.GridControl.DataSource = dtAssetCode; gvAssetList.RefreshData(); FillAllAsset(); } } catch (Exception ex) { MessageBox.Show("Error : " + ex, clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnSave_Click(object sender, EventArgs e) { if (ValidateForm()) { SaveKitDetils(); } } private void SaveKitDetils(bool bIsSaveKit_Asset = true) { KitMaster oKitMaster = null; try { oKitMaster = new KitMaster(); oKitMaster.nKitID = Convert.ToInt64(lblKitID.Text); oKitMaster.sKitName = txtKitName.Text.Trim(); oKitMaster.sKitCode = txtKitCode.Text.Trim(); oKitMaster.sKitAbbrivation = txtAbbrivation.Text.Trim(); oKitMaster.sKitDescription = txtKitDescription.Text.Trim(); byte[] BarcodeImage = new byte[] { }; if (picBarcodeImage != null) { if (picBarcodeImage.Image != null) { using (MemoryStream ms = new MemoryStream()) { picBarcodeImage.Image.Save(ms, ImageFormat.Jpeg); BarcodeImage = new byte[ms.Length]; ms.Position = 0; ms.Read(BarcodeImage, 0, BarcodeImage.Length); } } } oKitMaster.kitBarcode = BarcodeImage; List<KitAsset> lstKitAsset = new List<KitAsset>(); foreach (DataRow dr in dtAssetCode.Rows) { using (KitAsset oKitAsset = new KitAsset()) { oKitAsset.nKitID = Convert.ToInt64(dr["nKitID"]); oKitAsset.nKitAssetID = Convert.ToInt64(dr["nKitAssetID"]); oKitAsset.nAssetID = Convert.ToInt64(dr["nAssetID"]); oKitAsset.nAssetCodeID = Convert.ToInt64(dr["nAssetCodeID"]); oKitAsset.sAssetName = Convert.ToString(dr["sAssetName"]); oKitAsset.sUniqueCode = Convert.ToString(dr["sUniqueCode"]); oKitAsset.sAssetNameWithCode = Convert.ToString(dr["assetNameWithCode"]); lstKitAsset.Add(oKitAsset); } } oKitMaster.lstKitDetails = lstKitAsset; Int64 nKitID = oKitMaster.InsertUpdateKitDetails(bIsSaveKit_Asset); if (nKitID == 0) { MessageBox.Show("Kit details not saved.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (nKitID == 2) { MessageBox.Show("Kit code already present. Please change asset code.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Kit details saved successfuly", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); ClearKit(); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private bool ValidateForm() { if (txtKitName.Text.Trim()=="") { MessageBox.Show("Enter kit name.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); txtKitName.Focus(); return false; } return true; } private void btnUpdateKit_Click(object sender, EventArgs e) { if (ValidateForm()) { SaveKitDetils(false); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMainKitList : DevExpress.XtraEditors.XtraForm { public frmMainKitList() { InitializeComponent(); } private void txtSearch_EditValueChanged(object sender, EventArgs e) { try { DataView dv = (DataView)gvKitList.DataSource; //Company Code, Company Name, Country, State, City, Warehouse Supervisor, Company Type, Abbreviation string sSearchText = txtSearch.Text; string fileter = ""; if (sSearchText != "") { fileter = dv.Table.Columns["sKitName"].Caption + " Like '%" + sSearchText + "%' OR " + dv.Table.Columns["sKitCode"].Caption + " Like '%" + sSearchText + "%' OR " + dv.Table.Columns["sKitAbbrivation"].Caption + " Like '%" + sSearchText + "%'"; dv.RowFilter = fileter; } else { dv.RowFilter = fileter; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void frmMainKitList_Load(object sender, EventArgs e) { FillKitList(); } private void FillKitList() { KitMaster oKitMaster = null; DataTable dt = null; try { oKitMaster = new KitMaster(); dt = oKitMaster.GetKitList(0); if (dt != null) { gvKitList.GridControl.DataSource = dt; gvKitList.Columns[1].Visible = false; gvKitList.Columns[8].Visible = false; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void gvKitList_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e) { try { if (e.Column.Caption == "Delete") { int nVal = Convert.ToString(gvKitList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvKitList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; bool val = Convert.ToBoolean(nVal); if (val) { DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; ritem.ReadOnly = false; ritem.Buttons[0].Enabled = false; ritem.Buttons[0].Visible = false; e.RepositoryItem = ritem; } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void gvKitList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e) { try { if (e.Column.Caption == "Edit") { Int64 nKitID = 0; var row = gvKitList.GetFocusedDataRow(); nKitID = Convert.ToInt64(row[1]); frmAddKit frmKit = new frmAddKit(nKitID); frmKit.ShowDialog(); FillKitList(); } if (e.Column.Caption == "Delete") { var row = gvKitList.GetFocusedDataRow(); int n = Convert.ToString(gvKitList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvKitList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; if (n == 1) { return; } if (MessageBox.Show("Do you want to delete?", clsGlobal._sMessageboxCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } KitMaster oKitMaster = new KitMaster(); oKitMaster.nKitID = Convert.ToInt64(row[1]); if (oKitMaster.DeleteKit() > 0) { MessageBox.Show("Kit details deleted successfully.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } if (oKitMaster!=null) { oKitMaster.Dispose(); oKitMaster = null; } //clsMasters oclsMaster = new clsMasters(); //oclsMaster.nMasterID = Convert.ToInt64(row[1]); //oclsMaster.MasterType = this.MasterType; //oclsMaster.DeleteMaster(); FillKitList(); } if (e.Column.Caption == "Show Asset") { Int64 nKitID = 0; var row = gvKitList.GetFocusedDataRow(); nKitID = Convert.ToInt64(row[1]); frmMainKitAssetList oFrmAssetCodeList = new frmMainKitAssetList(nKitID); oFrmAssetCodeList.ShowDialog(); FillKitList(); } } catch (Exception ex) { MessageBox.Show("Error : " + ex, clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMasterAddParty : DevExpress.XtraEditors.XtraForm { public frmMasterAddParty() { InitializeComponent(); fillMasterData(); GetAndSetSequence(); txtPartyName.Focus(); } public frmMasterAddParty(Int64 nPartyID) { InitializeComponent(); lblPartyID.Text = Convert.ToString(nPartyID); fillMasterData(); GetAndSetSequence(); txtPartyName.Focus(); } private void fillMasterData() { txtCountry.Text = "India"; txtCity.Text = "Mumbai"; txtState.Text = "Maharashtra"; clsGeneral oclsGeneral = null; try { oclsGeneral = new clsGeneral(); DataSet dsParty = oclsGeneral.GetPartyMaster(); if (dsParty != null && dsParty.Tables.Count > 0) { DataTable dtPartyType = dsParty.Tables[0]; //DataTable dtStateMaster = dsParty.Tables[1]; //DataTable dtCityMaster = dsParty.Tables[2]; //DataTable dtCountryMaster = dsParty.Tables[3]; DataRow drParty = dtPartyType.NewRow(); drParty["nPartyTypeID"] = 0; drParty["sPartyTypeName"] = ""; dtPartyType.Rows.InsertAt(drParty, 0); cmbPartyType.DataSource = dtPartyType; cmbPartyType.DisplayMember = "sPartyTypeName"; cmbPartyType.ValueMember = "nPartyTypeID"; //cmbStateMaster.DataSource = dtStateMaster; //cmbStateMaster.DisplayMember = "StateName"; //cmbStateMaster.ValueMember = "StateName"; //cmbStateMaster.Text = "Maharashtra"; //cmbCityMaster.DataSource = dtCityMaster; //cmbCityMaster.DisplayMember = "CityName"; //cmbCityMaster.ValueMember = "CityName"; //cmbCityMaster.Text = "Mumbai"; //cmbCountryMaster.DataSource = dtCountryMaster; //cmbCountryMaster.DisplayMember = "sCountryName"; //cmbCountryMaster.ValueMember = "sCountryName"; //cmbCountryMaster.Text = "India"; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } } } private void GetAndSetSequence() { clsGeneral oclsGeneral = null; try { oclsGeneral = new clsGeneral(); txtPartyCode.Text = "PRT/" + Convert.ToString(oclsGeneral.GetSequenceNumber(MainMasterType.Party.GetHashCode())); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } } } private void frmMasterAddParty_Load(object sender, EventArgs e) { try { if (Convert.ToInt64(lblPartyID.Text) > 0) { FillPartyDetails(Convert.ToInt64(lblPartyID.Text)); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void FillPartyDetails(Int64 nPartyID) { PartyMaster clsPartyMaster = null; DataTable dtPartyDetails = null; try { clsPartyMaster = new PartyMaster(); dtPartyDetails = clsPartyMaster.GetPartyInformation(nPartyID); if (dtPartyDetails!=null&&dtPartyDetails.Rows.Count>0) { lblPartyID.Text = Convert.ToString(dtPartyDetails.Rows[0]["nPartyID"]); txtPartyCode.Text = Convert.ToString(dtPartyDetails.Rows[0]["sPartyCode"]); txtPartyAbbrivation.Text = Convert.ToString(dtPartyDetails.Rows[0]["sPartyAbbrivation"]); txtPartyName.Text = Convert.ToString(dtPartyDetails.Rows[0]["sPartyName"]); cmbPartyType.SelectedValue = Convert.ToString(dtPartyDetails.Rows[0]["nPartyType"]); txtAddressLine1.Text = Convert.ToString(dtPartyDetails.Rows[0]["sAddressLine1"]); txtAddressLine2.Text = Convert.ToString(dtPartyDetails.Rows[0]["sAddressLine2"]); txtCity.Text = Convert.ToString(dtPartyDetails.Rows[0]["sCity"]); txtState.Text = Convert.ToString(dtPartyDetails.Rows[0]["sState"]); txtCountry.Text = Convert.ToString(dtPartyDetails.Rows[0]["sCountry"]); txtPincode.Text = Convert.ToString(dtPartyDetails.Rows[0]["sPincode"]); txtEmail.Text = Convert.ToString(dtPartyDetails.Rows[0]["sEmail"]); txtFaxNo.Text = Convert.ToString(dtPartyDetails.Rows[0]["sFax"]); txtBillToAddressLine1.Text = Convert.ToString(dtPartyDetails.Rows[0]["sBillToAddressLine1"]); txtBillToAddressLine2.Text = Convert.ToString(dtPartyDetails.Rows[0]["sBillToAddressLine2"]); txtBillToPincode.Text = Convert.ToString(dtPartyDetails.Rows[0]["sBillToPincode"]); txtShipToAddressLine1.Text = Convert.ToString(dtPartyDetails.Rows[0]["sShipToAddressLine1"]); txtShipToAddressLine1.Text = Convert.ToString(dtPartyDetails.Rows[0]["sShipToAddressLine2"]); txtShipToPincode.Text = Convert.ToString(dtPartyDetails.Rows[0]["sShipToPincode"]); txtGSTNo.Text = Convert.ToString(dtPartyDetails.Rows[0]["sGSTNO"]); txtPANNo.Text = Convert.ToString(dtPartyDetails.Rows[0]["sPANNO"]); txtTANNo.Text = Convert.ToString(dtPartyDetails.Rows[0]["sTANNO"]); string[] sPhoneAll = Convert.ToString(dtPartyDetails.Rows[0]["sPhoneNo"]).Split(','); if (sPhoneAll.Length > 0) { int nCompPanelCount = GetPanelCount(sPhoneAll.Length); for (int i = 0; i < nCompPanelCount; i++) { ShowHidePhonePanel(sPhoneAll[i], i + 1); } } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private int GetPanelCount(int nStringLength) { int nPanelCount = 0; if (nStringLength <= 5) { switch (nStringLength) { case 1: nPanelCount = 1; break; case 2: nPanelCount = 2; break; case 3: nPanelCount = 3; break; case 4: nPanelCount = 4; break; case 5: nPanelCount = 5; break; } } return nPanelCount; } private int CheckPanelVisibility() { int nPanelCount = 0; if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == false && pnlPhoneThree.Visible == false && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 2; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == false && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 3; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 4; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == true && pnlPhoneFive.Visible == false) { nPanelCount = 5; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == true && pnlPhoneFive.Visible == false) { nPanelCount = 6; } return nPanelCount; } private void ShowHidePhonePanel(string sPhoneNo = "", int PhoneCount = 1) { switch (PhoneCount) { case 1: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = false; pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone1.Text = sPhoneNo; break; } case 2: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneTwo.BringToFront(); pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone2.Text = sPhoneNo; break; } case 3: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneThree.BringToFront(); pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone3.Text = sPhoneNo; break; } case 4: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFour.BringToFront(); pnlPhoneFive.Visible = false; txtPhone4.Text = sPhoneNo; break; } case 5: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFive.Visible = true; pnlPhoneFive.BringToFront(); txtPhone5.Text = sPhoneNo; break; } } } private void btnAddPhone_Click(object sender, EventArgs e) { try { int nCompanyPhoneCount = CheckPanelVisibility(); if (nCompanyPhoneCount <= 5) { ShowHidePhonePanel("", nCompanyPhoneCount); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void txtPartyName_EditValueChanged(object sender, EventArgs e) { txtPartyAbbrivation.Text = clsGlobal.GenerateAbbrivation(txtPartyName.Text); } private void btnSave_Click(object sender, EventArgs e) { if (ValidateForm()) { SavePartyMember(); } } public bool ValidateForm() { bool bIsValidForm = true; if (txtPartyName.Text.Trim() == "") { MessageBox.Show("Please enter party name.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtPartyName.Focus(); return bIsValidForm; } if (cmbPartyType.Text=="") { MessageBox.Show("Please select party type.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; cmbPartyType.Focus(); return bIsValidForm; } return bIsValidForm; } private void SavePartyMember() { PartyMaster clsPartyMaster = null; try { string sPhone1 = Convert.ToString(txtPhone1.Text.Trim()); string sPhone2 = Convert.ToString(txtPhone4.Text.Trim()); string sPhone3 = Convert.ToString(txtPhone5.Text.Trim()); string sPhone4 = Convert.ToString(txtPhone3.Text.Trim()); string sPhone5 = Convert.ToString(txtPhone2.Text.Trim()); string sPhoneAll = string.Empty; if (sPhone1 != "") { sPhoneAll += sPhone1; } if (sPhone2 != "") { sPhoneAll += "," + sPhone2; } if (sPhone3 != "") { sPhoneAll += "," + sPhone3; } if (sPhone4 != "") { sPhoneAll += "," + sPhone4; } if (sPhone5 != "") { sPhoneAll += "," + sPhone5; } clsPartyMaster = new PartyMaster(); clsPartyMaster.nPartyID = Convert.ToInt64(lblPartyID.Text); clsPartyMaster.nPartyTypeID = Convert.ToInt64(cmbPartyType.SelectedValue); clsPartyMaster.sPartyName = Convert.ToString(txtPartyName.Text.Trim()); clsPartyMaster.sPartyCode = Convert.ToString(txtPartyCode.Text.Trim()); clsPartyMaster.sPartyAbbrivation = Convert.ToString(txtPartyAbbrivation.Text.Trim()); clsPartyMaster.sAddressLine1 = Convert.ToString(txtAddressLine1.Text.Trim()); clsPartyMaster.sAddressLine2 = Convert.ToString(txtAddressLine2.Text.Trim()); clsPartyMaster.sCity = Convert.ToString(txtCity.Text.Trim()); clsPartyMaster.sState = Convert.ToString(txtState.Text.Trim()); clsPartyMaster.sCountry = Convert.ToString(txtCountry.Text.Trim()); clsPartyMaster.sPincode = Convert.ToString(txtPincode.Text.Trim()); clsPartyMaster.sEmail = Convert.ToString(txtEmail.Text.Trim()); clsPartyMaster.sAllPhoneNo = sPhoneAll; clsPartyMaster.sFax = Convert.ToString (txtFaxNo.Text.ToString()); clsPartyMaster.sGSTNo = Convert.ToString(txtGSTNo.Text.Trim()); clsPartyMaster.sPANNo = Convert.ToString(txtPANNo.Text.Trim()); clsPartyMaster.sTANNo = Convert.ToString(txtTANNo.Text.Trim()); clsPartyMaster.sBillToAddressLine1 = Convert.ToString(txtBillToAddressLine1.Text.Trim()); clsPartyMaster.sBillToAddressLine2 = Convert.ToString(txtBillToAddressLine1.Text.Trim()); clsPartyMaster.sBillToPincode = Convert.ToString(txtBillToPincode.Text.Trim()); clsPartyMaster.sShipToAddressLine1 = Convert.ToString(txtShipToAddressLine1.Text.Trim()); clsPartyMaster.sShipToAddressLine2 = Convert.ToString(txtShipToPincode.Text.Trim()); clsPartyMaster.sShipToPincode = Convert.ToString(txtShipToPincode.Text.Trim()); Int64 nCrewMemberID = clsPartyMaster.InsertUpdatePartyMaster(); if (nCrewMemberID != 0) { MessageBox.Show("Party is saved successfully.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); ClearForm(); } else { MessageBox.Show("Error while saving party.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } public void ClearForm() { txtPartyAbbrivation.Text = string.Empty; txtPartyName.Text = string.Empty; cmbPartyType.SelectedValue = 0; txtAddressLine1.Text = string.Empty; txtAddressLine2.Text = string.Empty; txtCountry.Text = "India"; txtCity.Text = "Mumbai"; txtState.Text = "Maharashtra"; txtPincode.Text = string.Empty; txtEmail.Text = string.Empty; txtFaxNo.Text = string.Empty; txtBillToAddressLine1.Text = string.Empty; txtBillToAddressLine2.Text = string.Empty; txtBillToPincode.Text = string.Empty; txtShipToAddressLine1.Text = string.Empty; txtShipToAddressLine1.Text = string.Empty; txtShipToPincode.Text = string.Empty; txtGSTNo.Text = string.Empty; txtPANNo.Text = string.Empty; txtTANNo.Text = string.Empty; txtPhone1.Text = string.Empty; txtPhone2.Text = string.Empty; txtPhone3.Text = string.Empty; txtPhone4.Text = string.Empty; txtPhone5.Text = string.Empty; GetAndSetSequence(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMainAssetCodeList : DevExpress.XtraEditors.XtraForm { public Int64 nAssetID { get; set; } public frmMainAssetCodeList(Int64 AssetID) { InitializeComponent(); nAssetID = AssetID; } private void frmMainAssetCodeList_Load(object sender, EventArgs e) { FillAssetCodeDetails(); } private void FillAssetCodeDetails() { AssetMaster oAssetMaster = null; DataTable dtAssetCode = null; try { oAssetMaster = new AssetMaster(); dtAssetCode = oAssetMaster.GetAssetCode(nAssetID); if (dtAssetCode!=null) { gvAssetCodeList.GridControl.DataSource = dtAssetCode; gvAssetCodeList.Columns[1].Visible = false; gvAssetCodeList.Columns[2].Visible = false; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { class PartyMaster { #region "Constructor & Distructor" private bool disposed = false; public PartyMaster() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~PartyMaster() { Dispose(false); } #endregion #region "Properties" public Int64 nPartyID { get; set; } public Int64 nPartyTypeID { get; set; } public string sPartyName { get; set; } public string sPartyCode { get; set; } public string sPartyAbbrivation { get; set; } public string sAddressLine1 { get; set; } public string sAddressLine2 { get; set; } public string sCity { get; set; } public string sState { get; set; } public string sCountry { get; set; } public string sPincode { get; set; } public string sEmail { get; set; } public string sFax { get; set; } public string sAllPhoneNo { get; set; } public string sBillToAddressLine1 { get; set; } public string sBillToAddressLine2 { get; set; } public string sBillToPincode { get; set; } public string sShipToAddressLine1 { get; set; } public string sShipToAddressLine2 { get; set; } public string sShipToPincode { get; set; } public string sGSTNo { get; set; } public string sPANNo { get; set; } public string sTANNo { get; set; } #endregion #region "Method" public Int64 InsertUpdatePartyMaster() { Int64 _nPartyID = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objValue = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nPartyID", this.nPartyID, ParameterDirection.InputOutput, SqlDbType.BigInt); oDBParameter.Add("@sPartyCode", this.sPartyCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPartyName", this.sPartyName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPartyAbbrivation", this.sPartyAbbrivation, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@nPartyTypeID", this.nPartyTypeID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sAddressLine1", this.sAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAddressLine2", this.sAddressLine2, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCity", this.sCity, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sState", this.sState, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPincode", this.sPincode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCountry", this.sCountry, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sEmail", this.sEmail, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sFax", this.sFax, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAllPhoneNo", this.sAllPhoneNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sBillToAddressLine1", this.sBillToAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sBillToAddressLine2", this.sBillToAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sBillToPincode", this.sBillToAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sShipToAddressLine1", this.sShipToAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sShipToAddressLine2", this.sShipToAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sShipToPincode", this.sShipToPincode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sGSTNO", this.sGSTNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPANNO", this.sPANNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sTANNO", this.sTANNo, ParameterDirection.Input, SqlDbType.VarChar); oDBAccess.OpenConnection(false); oDBAccess.Execute("lgsp_INUP_PartyMaster", oDBParameter, out objValue); oDBAccess.CloseConnection(false); if (objValue != null) { _nPartyID = Convert.ToInt64(objValue); } } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess!=null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter!=null) { oDBParameter.Dispose(); oDBParameter = null; } } return _nPartyID; } public DataTable GetPartyInformation(Int64 nPartyID) { DataSet ds = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nPartyID", nPartyID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_PartyDetails", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } public DataTable GetPartylist(Int64 nPartyID) { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nPartyID", nPartyID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_PartyListDetails", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { class KitMaster:IDisposable { #region "Constructor & Distructor" private bool disposed = false; public KitMaster() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~KitMaster() { Dispose(false); } #endregion public Int64 nKitID { get; set; } public string sKitName { get; set; } public string sKitCode { get; set; } public string sKitAbbrivation { get; set; } public string sKitDescription { get; set; } public byte[] kitBarcode { get; set; } public List<KitAsset> lstKitDetails { get; set; } public Int64 InsertUpdateKitDetails(bool bIsSaveKit_Asset = true) { Int64 nKitID = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objValue = null; Object objStatus = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nKitID", this.nKitID, ParameterDirection.InputOutput, SqlDbType.BigInt); oDBParameter.Add("@sKitName", this.sKitName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sKitCode", this.sKitCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sKitAbbrivation", this.sKitAbbrivation, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sKitDescription", this.sKitDescription, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@kitBarcode", this.kitBarcode, ParameterDirection.Input, SqlDbType.Image); oDBAccess.OpenConnection(true); oDBAccess.Execute("lgsp_INUP_KitMaster", oDBParameter, out objValue); if (objValue != null) { nKitID = Convert.ToInt64(objValue); } if (nKitID == 0) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nKitID; } if (nKitID != 0 && bIsSaveKit_Asset) { foreach (KitAsset item in lstKitDetails) { oDBParameter.clear(); oDBParameter.Add("@nKitID", nKitID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nKitAssetID", item.nKitAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetCodeID", item.nAssetCodeID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetID", item.nAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nStatus", 0, ParameterDirection.InputOutput, SqlDbType.Int); oDBAccess.Execute("lgsp_INUP_KitAssetAssociation", oDBParameter, out objStatus); int nStatus = 0; if (objValue != null) { nStatus = Convert.ToInt32(objStatus); } if (nStatus <= 0) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nStatus; } if (nStatus == 2) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nStatus; } } } oDBAccess.Commit(); } catch (Exception ex) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nKitID; } public DataTable GetKitAssetAssociation(Int64 nKitID=0) { DataTable dt = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nKitID", nKitID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_KitAssetAssociationDetails", oDBParameter, out dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(true); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return dt; } public DataTable GetKitList(Int64 nKitID) { DataTable dt = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nKitID", nKitID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_KitListDetails", oDBParameter, out dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(true); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return dt; } public DataSet GetKitDetails(Int64 nKitID) { DataSet ds = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nKitID", nKitID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_KitDetails", oDBParameter, out ds); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(true); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return ds; } public DataTable GetKitAssetList(Int64 nKitID = 0) { DataTable dt = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nKitID", nKitID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_KitAssetList", oDBParameter, out dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(true); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return dt; } public Int32 DeleteKit() { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Int32 nDeletedID = 0; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nKitID", this.nKitID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); nDeletedID=oDBAccess.Execute("lgsp_Delete_Kit", oDBParameter); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(true); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nDeletedID; } } public class KitAsset:IDisposable { #region "Constructor & Distructor" private bool disposed = false; public KitAsset() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~KitAsset() { Dispose(false); } #endregion public Int64 nKitID { get; set; } public Int64 nAssetCodeID { get; set; } public Int64 nKitAssetID { get; set; } public Int64 nAssetID { get; set; } public string sUniqueCode { get; set; } public string sAssetName { get; set; } public string sAssetNameWithCode { get; set; } public Int64 UpdateAssetCode() { Int64 nStatus = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objStatus = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nKitID", this.nKitID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nKitAssetID", this.nKitAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetID", this.nAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetCodeID", this.nAssetCodeID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nStatus", 0, ParameterDirection.InputOutput, SqlDbType.Int); oDBAccess.OpenConnection(false); oDBAccess.Execute("lgsp_INUP_KitAssetAssociation", oDBParameter, out objStatus); oDBAccess.CloseConnection(false); if (objStatus != null) { nStatus = Convert.ToInt32(objStatus); } if (nStatus <= 0) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nStatus; } if (nStatus == 2) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nStatus; } oDBAccess.Commit(); oDBAccess.CloseConnection(true); } catch (Exception ex) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nStatus; } public Int32 DeleteKitAsset() { Int32 nRow = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nKitAssetID", this.nKitAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); nRow= oDBAccess.Execute("lgsp_Delete_KitAsset", oDBParameter); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(true); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nRow; } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { class AssetMaster:IDisposable { #region "Constructor & Distructor" private bool disposed = false; public AssetMaster() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~AssetMaster() { Dispose(false); } #endregion #region "Properties" public Int64 nAssetID { get; set; } public Int64 nCompanyID { get; set; } public Int64 nAssetMainTypeID { get; set; } public Int64 nAssetTypeID { get; set; } public Int64 nAssetTypeOneID { get; set; } public Int64 nAssetMaterialID { get; set; } public Int64 nAssetVendorID { get; set; } public Int64 nDensityID { get; set; } public Int64 nColorID { get; set; } public string sHSNCode { get; set; } public string sAssetName { get; set; } public string sAssetCode { get; set; } public string sAssetAbbrivation { get; set; } public string sAssetDescription { get; set; } public DateTime dtIntroductionDate { get; set; } public DateTime dtReorderDate { get; set; } public string sReorderDays { get; set; } public string sReorderQuntity { get; set; } public string sAssetRate { get; set; } public string sAssetMake { get; set; } public string sAssetSizeOrCapacity { get; set; } public string sAssetQuality { get; set; } public string sAssetDimention { get; set; } public string sAssetWeight { get; set; } public string sWattage { get; set; } public string sSpan { get; set; } public string sAttachment { get; set; } public string sAttachmentName { get; set; } public string sLength { get; set; } public string sCoreOrPole { get; set; } public string sAmps { get; set; } public string sPlug { get; set; } public string sPower { get; set; } public List<AssetCode> lstAssetCode { get; set; } #endregion #region "Methods" public Int64 InsertUpdateAsset(bool bIsSaveAsset_Code=true) { Int64 nAssetID = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objValue=null; Object objStatus=null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetID", this.nAssetID, ParameterDirection.InputOutput, SqlDbType.BigInt); oDBParameter.Add("@nCompanyID", this.nCompanyID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetMainTypeID", this.nAssetMainTypeID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetTypeID", this.nAssetTypeID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetTypeOneID", this.nAssetTypeOneID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetMaterialID", this.nAssetMaterialID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetVendorID", this.nAssetVendorID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nDensityID", this.nDensityID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nColorID", this.nColorID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sHSNCode", this.sHSNCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAssetName", this.sAssetName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAssetAbbrivation", this.sAssetAbbrivation, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sDescription", this.sAssetDescription, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtIntroductionDate", this.dtIntroductionDate, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@dtReorderDate", this.dtReorderDate, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sReorderDays", this.sReorderDays, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sReorderQuntity", this.sReorderQuntity, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sRate", this.sAssetRate, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sMake", this.sAssetMake, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sSizeOrCapacity", this.sAssetSizeOrCapacity, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sQuality", this.sAssetQuality, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sDimention", this.sAssetDimention, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWeight", this.sAssetWeight, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWattage", this.sWattage, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sSpan", this.sSpan, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAttachment", this.sAttachment, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAttachmentName", this.sAttachmentName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sLength", this.sLength, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCoreOrPole", this.sCoreOrPole, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAmps", this.sAmps, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPlug", this.sPlug, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPower", this.sPower, ParameterDirection.Input, SqlDbType.VarChar); oDBAccess.OpenConnection(true); oDBAccess.Execute("lgsp_INUP_AssetMaster", oDBParameter, out objValue); if (objValue!=null) { nAssetID = Convert.ToInt64(objValue); } if(nAssetID==0) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nAssetID; } if (nAssetID!=0) { foreach (AssetCode item in lstAssetCode) { oDBParameter.clear(); oDBParameter.Add("@nAssetID", nAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetCodeID", item.nAssetCodeID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sInitialCode", item.sInitialCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@nSequenceNo", item.nSequenceNo, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sUniqueCode", item.sUniqueCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@barcode", item.barcode, ParameterDirection.Input, SqlDbType.Image); oDBParameter.Add("@dtShelfLife", item.dtShelfLife, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sShelfLifeUnit", item.sShelfLifeUnit, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtRetirementDate", item.dtRetirementDate, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@nStatus", 0, ParameterDirection.InputOutput, SqlDbType.Int); oDBAccess.Execute("lgsp_INUP_AssetCode", oDBParameter, out objStatus); int nStatus=0; if (objValue != null) { nStatus = Convert.ToInt32(objStatus); } if (nStatus<=0) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nStatus; } if (nStatus==2) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nStatus; } } } oDBAccess.Commit(); //oDBAccess.CloseConnection(true); } catch (Exception ex) { oDBAccess.RollBack(); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nAssetID; } public DataSet GetAllMasterData(int nAssetType=0) { DataSet ds = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetType", nAssetType, ParameterDirection.Input, SqlDbType.Int); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_getAssetMasterList",oDBParameter, out ds); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return ds; } public DataTable GetAssetList(Int64 nAssetID) { DataTable dt = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetID", nAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_AssetListDetails", oDBParameter, out dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return dt; } public DataSet GetAssetDetails(Int64 nAssetID) { DataSet ds = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetID", nAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_AssetDetails", oDBParameter, out ds); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return ds; } public DataSet GetAllMasterData_ByMainType(Int64 nAssetMainType) { DataSet ds = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetType", nAssetMainType, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_AssetMasterData_ByMainType",oDBParameter, out ds); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return ds; } public DataTable GetAssetCode(Int64 nAssetID) { DataTable dt = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetID", nAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_AssetCodeDetails", oDBParameter, out dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return dt; } public Int32 DeleteAsset() { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Int32 nDeletedID = 0; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetID", this.nAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); nDeletedID= oDBAccess.Execute("lgsp_Delete_Asset", oDBParameter); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nDeletedID; } #endregion } public class AssetCode:IDisposable { #region "Constructor & Distructor" private bool disposed = false; public AssetCode() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~AssetCode() { Dispose(false); } #endregion public Int64 nAssetCodeID { get; set; } public Int64 nAssetID { get; set; } public string sInitialCode { get; set; } public int nSequenceNo { get; set; } public string sUniqueCode { get; set; } public string sShowStatus { get; set; } public string sAssignStatus { get; set; } public string sCurrentStatus { get; set; } public byte[] barcode { get; set; } public DateTime dtShelfLife { get; set; } public string sShelfLifeUnit { get; set; } public DateTime dtRetirementDate { get; set; } public string sDamageStatus { get; set; } public Int64 UpdateAssetCode() { Int64 nStatus = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objStatus = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetID", this.nAssetID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nAssetCodeID", this.nAssetCodeID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sInitialCode", this.sInitialCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@nSequenceNo", this.nSequenceNo, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sUniqueCode", this.sUniqueCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@barcode", this.barcode, ParameterDirection.Input, SqlDbType.Image); oDBParameter.Add("@dtShelfLife", this.dtShelfLife, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sShelfLifeUnit", this.sShelfLifeUnit, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtRetirementDate", this.dtRetirementDate, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@nStatus", 0, ParameterDirection.InputOutput, SqlDbType.Int); oDBAccess.OpenConnection(false); oDBAccess.Execute("lgsp_INUP_AssetCode", oDBParameter, out objStatus); oDBAccess.CloseConnection(false); if (objStatus != null) { nStatus = Convert.ToInt32(objStatus); } if (nStatus <= 0) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nStatus; } if (nStatus == 2) { oDBAccess.RollBack(); oDBAccess.CloseConnection(true); return nStatus; } oDBAccess.Commit(); //oDBAccess.CloseConnection(true); } catch (Exception ex) { oDBAccess.RollBack(); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nStatus; } public DataTable GetAssetCode() { DatabaseAccess oDBAccess = null; DataTable dtAssetCode=null; //DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); //oDBParameter = new DatabaseParameters(); //oDBParameter.clear(); //oDBParameter.Add("@nAssetID", this.nAssetID, ParameterDirection.Input, SqlDbType.BigInt); //oDBParameter.Add("@nAssetCodeID", this.nAssetCodeID, ParameterDirection.Input, SqlDbType.BigInt); //oDBParameter.Add("@sInitialCode", this.sInitialCode, ParameterDirection.Input, SqlDbType.VarChar); //oDBParameter.Add("@nSequenceNo", this.nSequenceNo, ParameterDirection.Input, SqlDbType.BigInt); //oDBParameter.Add("@sUniqueCode", this.sUniqueCode, ParameterDirection.Input, SqlDbType.VarChar); //oDBParameter.Add("@barcode", this.barcode, ParameterDirection.Input, SqlDbType.Image); //oDBParameter.Add("@dtShelfLife", this.dtShelfLife, ParameterDirection.Input, SqlDbType.DateTime); //oDBParameter.Add("@sShelfLifeUnit", this.sShelfLifeUnit, ParameterDirection.Input, SqlDbType.VarChar); //oDBParameter.Add("@dtRetirementDate", this.dtRetirementDate, ParameterDirection.Input, SqlDbType.DateTime); //oDBParameter.Add("@nStatus", 0, ParameterDirection.InputOutput, SqlDbType.Int); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_AllNotUsedAsset", out dtAssetCode); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } } return dtAssetCode; } public Int32 DeleteAssetCode() { Int32 nRow = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetCodeID", this.nAssetCodeID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); nRow = oDBAccess.Execute("lgsp_Delete_AssetCode", oDBParameter); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nRow; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMasterAddLocation : DevExpress.XtraEditors.XtraForm { public frmMasterAddLocation() { InitializeComponent(); FillMasterData(); GetAndSetSequence(); } private void FillMasterData() { txtCountry.Text = "India"; txtCity.Text = "Mumbai"; txtState.Text = "Maharashtra"; //clsGeneral oclsGeneral = null; //try //{ // oclsGeneral = new clsGeneral(); // DataSet dsGaffer = oclsGeneral.GetGafferMaster(); // if (dsGaffer != null && dsGaffer.Tables.Count > 0) // { // DataTable dtStateMaster = dsGaffer.Tables[0]; // DataTable dtCityMaster = dsGaffer.Tables[1]; // DataTable dtCountryMaster = dsGaffer.Tables[2]; // cmbStateMaster.DataSource = dtStateMaster; // cmbStateMaster.DisplayMember = "StateName"; // cmbStateMaster.ValueMember = "StateName"; // cmbStateMaster.Text = "Maharashtra"; // cmbCityMaster.DataSource = dtCityMaster; // cmbCityMaster.DisplayMember = "CityName"; // cmbCityMaster.ValueMember = "CityName"; // cmbCityMaster.Text = "Mumbai"; // cmbCountryMaster.DataSource = dtCountryMaster; // cmbCountryMaster.DisplayMember = "sCountryName"; // cmbCountryMaster.ValueMember = "sCountryName"; // cmbCountryMaster.Text = "India"; // } //} //catch (Exception ex) //{ // MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); //} //finally //{ // if (oclsGeneral != null) // { // oclsGeneral.Dispose(); // oclsGeneral = null; // } //} } private void GetAndSetSequence() { clsGeneral oclsGeneral = null; try { oclsGeneral = new clsGeneral(); txtCode.Text = "LOC/" + Convert.ToString(oclsGeneral.GetSequenceNumber(MainMasterType.Location.GetHashCode())); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } } } public frmMasterAddLocation(Int64 nLocationID) { InitializeComponent(); lblLocationID.Text = Convert.ToString(nLocationID); FillMasterData(); GetAndSetSequence(); } private void frmMasterAddLocation_Load(object sender, EventArgs e) { try { if (Convert.ToInt64(lblLocationID.Text) > 0) { FillLocatioDetails(Convert.ToInt64(lblLocationID.Text)); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void FillLocatioDetails(long nLocationID) { LocationMaster oLocationMaster = null; DataTable dtLocationDetails = null; try { oLocationMaster = new LocationMaster(); dtLocationDetails = oLocationMaster.GetLocationInformation(nLocationID); if (dtLocationDetails != null && dtLocationDetails.Rows.Count > 0) { lblLocationID.Text = Convert.ToString(dtLocationDetails.Rows[0]["nLocationID"]); txtCode.Text = Convert.ToString(dtLocationDetails.Rows[0]["sLocationCode"]); txtDescription.Text = Convert.ToString(dtLocationDetails.Rows[0]["sDescription"]); txtAddressLine1.Text = Convert.ToString(dtLocationDetails.Rows[0]["sAddressLine1"]); txtAddressLine2.Text = Convert.ToString(dtLocationDetails.Rows[0]["sAddressLine2"]); txtCity.Text = Convert.ToString(dtLocationDetails.Rows[0]["sCity"]); txtState.Text = Convert.ToString(dtLocationDetails.Rows[0]["sState"]); txtCountry.Text = Convert.ToString(dtLocationDetails.Rows[0]["sCountry"]); txtPincode.Text = Convert.ToString(dtLocationDetails.Rows[0]["sPincode"]); txtVilageDistTown.Text = Convert.ToString(dtLocationDetails.Rows[0]["sVlgDstTwn"]); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btnSave_Click(object sender, EventArgs e) { if (ValidateForm()) { SaveLocationMaster(); } } private void SaveLocationMaster() { LocationMaster oclsLocationMaster = null; try { oclsLocationMaster = new LocationMaster(); oclsLocationMaster.nLocationID = Convert.ToInt64(lblLocationID.Text); oclsLocationMaster.sLocationCode = Convert.ToString(txtCode.Text.Trim()); oclsLocationMaster.sDescription = Convert.ToString(txtDescription.Text.Trim()); oclsLocationMaster.sAddressLine1 = Convert.ToString(txtAddressLine1.Text.Trim()); oclsLocationMaster.sAddressLine2 = Convert.ToString(txtAddressLine2.Text.Trim()); oclsLocationMaster.sCity = Convert.ToString(txtCity.Text.Trim()); oclsLocationMaster.sState = Convert.ToString(txtState.Text.Trim()); oclsLocationMaster.sCountry = Convert.ToString(txtCountry.Text.Trim()); oclsLocationMaster.sPincode = Convert.ToString(txtPincode.Text.Trim()); oclsLocationMaster.sVillageDistTown= Convert.ToString(txtVilageDistTown.Text.Trim()); Int64 nLocationID = oclsLocationMaster.InsertUpdateLocationMaster(); if (nLocationID != 0) { MessageBox.Show("Location is saved successfully.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); ClearControl(); } else { MessageBox.Show("Error while saving location.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } public bool ValidateForm() { bool bIsValidForm = true; if (txtDescription.Text.Trim() == "") { MessageBox.Show("Please enter description.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtDescription.Focus(); return bIsValidForm; } return bIsValidForm; } public void ClearControl() { txtDescription.Text = ""; txtAbbrivation.Text = ""; txtAddressLine1.Text = ""; txtAddressLine2.Text = ""; txtVilageDistTown.Text = ""; txtCountry.Text = "India"; txtCity.Text = "Mumbai"; txtState.Text = "Maharashtra"; txtPincode.Text = ""; GetAndSetSequence(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMasterAddGaffer : DevExpress.XtraEditors.XtraForm { public frmMasterAddGaffer() { InitializeComponent(); FillMasterData(); GetAndSetSequence(); txtGafferName.Focus(); } public frmMasterAddGaffer(Int64 nGafferID) { InitializeComponent(); lblGafferID.Text = Convert.ToString(nGafferID); FillMasterData(); GetAndSetSequence(); txtGafferName.Focus(); } private void frmMasterAddGaffer_Load(object sender, EventArgs e) { try { dtGafferBirthdate.EditValue = DateTime.Now; if (Convert.ToInt64(lblGafferID.Text) > 0) { FillGafferMemberDetails(Convert.ToInt64(lblGafferID.Text)); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void FillMasterData() { txtCountry.Text = "India"; txtCity.Text = "Mumbai"; txtState.Text = "Maharashtra"; //clsGeneral oclsGeneral = null; //try //{ // oclsGeneral = new clsGeneral(); // DataSet dsGaffer = oclsGeneral.GetGafferMaster(); // if (dsGaffer != null && dsGaffer.Tables.Count > 0) // { // DataTable dtStateMaster = dsGaffer.Tables[0]; // DataTable dtCityMaster = dsGaffer.Tables[1]; // DataTable dtCountryMaster = dsGaffer.Tables[2]; // cmbStateMaster.DataSource = dtStateMaster; // cmbStateMaster.DisplayMember = "StateName"; // cmbStateMaster.ValueMember = "StateName"; // cmbStateMaster.Text = "Maharashtra"; // cmbCityMaster.DataSource = dtCityMaster; // cmbCityMaster.DisplayMember = "CityName"; // cmbCityMaster.ValueMember = "CityName"; // cmbCityMaster.Text = "Mumbai"; // cmbCountryMaster.DataSource = dtCountryMaster; // cmbCountryMaster.DisplayMember = "sCountryName"; // cmbCountryMaster.ValueMember = "sCountryName"; // cmbCountryMaster.Text = "India"; // } //} //catch (Exception ex) //{ // MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); //} //finally //{ // if (oclsGeneral != null) // { // oclsGeneral.Dispose(); // oclsGeneral = null; // } //} } private void GetAndSetSequence() { clsGeneral oclsGeneral = null; try { oclsGeneral = new clsGeneral(); txtGafferCode.Text = "EMP/GF/" + Convert.ToString(oclsGeneral.GetSequenceNumber(MainMasterType.Gaffer.GetHashCode())); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } } } private void FillGafferMemberDetails(long nGafferID) { GafferMaster oclsGafferMaster = null; DataTable dtGafferDetails = null; try { oclsGafferMaster = new GafferMaster(); dtGafferDetails = oclsGafferMaster.GetGafferInformation(nGafferID); if (dtGafferDetails != null && dtGafferDetails.Rows.Count > 0) { lblGafferID.Text = Convert.ToString(dtGafferDetails.Rows[0]["nGafferID"]); txtGafferCode.Text = Convert.ToString(dtGafferDetails.Rows[0]["sGafferCode"]); txtGafferName.Text = Convert.ToString(dtGafferDetails.Rows[0]["sGafferName"]); txtGafferAbbrivation.Text = Convert.ToString(dtGafferDetails.Rows[0]["sGafferAbbrivation"]); cmbGender.Text = Convert.ToString(dtGafferDetails.Rows[0]["sGender"]); dtGafferBirthdate.EditValue = Convert.ToDateTime(dtGafferDetails.Rows[0]["dtDOB"]); txtGafferAge.Text = Convert.ToString(dtGafferDetails.Rows[0]["sAge"]); txtAddressLine1.Text = Convert.ToString(dtGafferDetails.Rows[0]["sAddressLine1"]); txtAddressLine2.Text = Convert.ToString(dtGafferDetails.Rows[0]["sAddressLine2"]); txtCity.Text = Convert.ToString(dtGafferDetails.Rows[0]["sCity"]); txtState.Text = Convert.ToString(dtGafferDetails.Rows[0]["sState"]); txtCountry.Text = Convert.ToString(dtGafferDetails.Rows[0]["sCountry"]); txtPincode.Text = Convert.ToString(dtGafferDetails.Rows[0]["sPincode"]); txtEmail.Text = Convert.ToString(dtGafferDetails.Rows[0]["sEmail"]); txtGafferUserName.Text = Convert.ToString(dtGafferDetails.Rows[0]["sLoginName"]); txtGafferPin.Text = Convert.ToString(dtGafferDetails.Rows[0]["sLoginPin"]); txtGafferPassword.Text = Convert.ToString(dtGafferDetails.Rows[0]["sPassword"]); txtGafferConfirmPassword.Text = Convert.ToString(dtGafferDetails.Rows[0]["sPassword"]); string[] sPhoneAll = Convert.ToString(dtGafferDetails.Rows[0]["sPhoneNo"]).Split(','); if (sPhoneAll.Length > 0) { int nCompPanelCount = GetPanelCount(sPhoneAll.Length); for (int i = 0; i < nCompPanelCount; i++) { ShowHidePhonePanel(sPhoneAll[i], i + 1); } } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void dtGafferBirthdate_EditValueChanged(object sender, EventArgs e) { try { int num = Convert.ToInt32((DateTime.Now - Convert.ToDateTime(dtGafferBirthdate.Text)).Days) / 365; if (num > 0) { txtGafferAge.Text = num.ToString(); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private int GetPanelCount(int nStringLength) { int nPanelCount = 0; if (nStringLength <= 5) { switch (nStringLength) { case 1: nPanelCount = 1; break; case 2: nPanelCount = 2; break; case 3: nPanelCount = 3; break; case 4: nPanelCount = 4; break; case 5: nPanelCount = 5; break; } } return nPanelCount; } private void ShowHidePhonePanel(string sPhoneNo = "", int PhoneCount = 1) { switch (PhoneCount) { case 1: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = false; pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone1.Text = sPhoneNo; break; } case 2: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneTwo.BringToFront(); pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone2.Text = sPhoneNo; break; } case 3: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneThree.BringToFront(); pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone3.Text = sPhoneNo; break; } case 4: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFour.BringToFront(); pnlPhoneFive.Visible = false; txtPhone4.Text = sPhoneNo; break; } case 5: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFive.Visible = true; pnlPhoneFive.BringToFront(); txtPhone5.Text = sPhoneNo; break; } } } private void btnSave_Click(object sender, EventArgs e) { if (ValidateForm()) { SaveGafferMember(); } } public bool ValidateForm() { bool bIsValidForm = true; if (txtGafferName.Text.Trim() == "") { MessageBox.Show("Please enter gaffer name.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferName.Focus(); return bIsValidForm; } if (txtGafferUserName.Text.Trim() == "") { MessageBox.Show("Please enter username.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferUserName.Focus(); return bIsValidForm; } if (txtGafferPassword.Text.Trim() == "") { MessageBox.Show("Please enter password.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferPassword.Focus(); return bIsValidForm; } if (txtGafferConfirmPassword.Text.Trim() == "") { MessageBox.Show("Please enter confirm password.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferConfirmPassword.Focus(); return bIsValidForm; } if (txtGafferPin.Text.Trim() == "") { MessageBox.Show("Please enter pin.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferPin.Focus(); return bIsValidForm; } if (txtGafferPassword.Text.Length < 8) { MessageBox.Show("Password shold be more than 8 characters.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferPassword.Focus(); return bIsValidForm; } if (txtGafferPassword.Text.Trim() != txtGafferConfirmPassword.Text.Trim()) { MessageBox.Show("Password and confirm password not match.\nPassword & confirm password must be same.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferPassword.Focus(); return bIsValidForm; } return bIsValidForm; } private void SaveGafferMember() { GafferMaster oclsGafferMaster = null; try { string sPhone1 = Convert.ToString(txtPhone1.Text.Trim()); string sPhone2 = Convert.ToString(txtPhone4.Text.Trim()); string sPhone3 = Convert.ToString(txtPhone5.Text.Trim()); string sPhone4 = Convert.ToString(txtPhone3.Text.Trim()); string sPhone5 = Convert.ToString(txtPhone2.Text.Trim()); string sPhoneAll = string.Empty; if (sPhone1 != "") { sPhoneAll += sPhone1; } if (sPhone2 != "") { sPhoneAll += "," + sPhone2; } if (sPhone3 != "") { sPhoneAll += "," + sPhone3; } if (sPhone4 != "") { sPhoneAll += "," + sPhone4; } if (sPhone5 != "") { sPhoneAll += "," + sPhone5; } oclsGafferMaster = new GafferMaster(); oclsGafferMaster.nGafferID = Convert.ToInt64(lblGafferID.Text); oclsGafferMaster.sGafferName = Convert.ToString(txtGafferName.Text.Trim()); oclsGafferMaster.sGafferCode = Convert.ToString(txtGafferCode.Text.Trim()); oclsGafferMaster.sGafferAbbrivation = Convert.ToString(txtGafferAbbrivation.Text.Trim()); oclsGafferMaster.sGafferGender = Convert.ToString(cmbGender.Text.Trim()); oclsGafferMaster.dtGafferDOB = Convert.ToDateTime(dtGafferBirthdate.Text.Trim()); oclsGafferMaster.sGafferAge = Convert.ToString(txtGafferAge.Text.Trim()); oclsGafferMaster.sAddressLine1 = Convert.ToString(txtAddressLine1.Text.Trim()); oclsGafferMaster.sAddressLine2 = Convert.ToString(txtAddressLine2.Text.Trim()); oclsGafferMaster.sCity = Convert.ToString(txtCity.Text.Trim()); oclsGafferMaster.sState = Convert.ToString(txtState.Text.Trim()); oclsGafferMaster.sCountry = Convert.ToString(txtCountry.Text.Trim()); oclsGafferMaster.sPincode = Convert.ToString(txtPincode.Text.Trim()); oclsGafferMaster.sEmail = Convert.ToString(txtEmail.Text.Trim()); oclsGafferMaster.sAllPhoneNo = sPhoneAll; oclsGafferMaster.sUserName = Convert.ToString(txtGafferUserName.Text.Trim()); oclsGafferMaster.sPassword = Convert.ToString(txtGafferConfirmPassword.Text.Trim()); oclsGafferMaster.sPin = Convert.ToString(txtGafferPin.Text.Trim()); Int64 nGafferMemberID = oclsGafferMaster.InsertUpdateGafferMaster(); if (nGafferMemberID != 0) { MessageBox.Show("Gaffer is saved successfully.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); ClearForm(); } else { MessageBox.Show("Error while saving gaffer.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btnAddPhone_Click(object sender, EventArgs e) { try { int nCompanyPhoneCount = CheckPanelVisibility(); if (nCompanyPhoneCount <= 5) { ShowHidePhonePanel("", nCompanyPhoneCount); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private int CheckPanelVisibility() { int nPanelCount = 0; if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == false && pnlPhoneThree.Visible == false && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 2; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == false && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 3; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 4; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == true && pnlPhoneFive.Visible == false) { nPanelCount = 5; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == true && pnlPhoneFive.Visible == false) { nPanelCount = 6; } return nPanelCount; } private void txtGafferName_EditValueChanged(object sender, EventArgs e) { txtGafferAbbrivation.Text = clsGlobal.GenerateAbbrivation(txtGafferName.Text.Trim()); } private void ClearForm() { txtGafferCode.Text = string.Empty; txtGafferName.Text = string.Empty; txtGafferAbbrivation.Text = string.Empty; cmbGender.Text = string.Empty; dtGafferBirthdate.EditValue = DateTime.Now; txtGafferAge.Text = string.Empty; txtAddressLine1.Text = string.Empty; txtAddressLine2.Text = string.Empty; txtCity.Text = string.Empty; txtState.Text = string.Empty; txtCountry.Text = string.Empty; txtPincode.Text = string.Empty; txtEmail.Text = string.Empty; txtGafferUserName.Text = string.Empty; txtGafferPin.Text = string.Empty; txtGafferPassword.Text = string.Empty; txtGafferConfirmPassword.Text = string.Empty; txtPhone1.Text = string.Empty; txtPhone2.Text = string.Empty; txtPhone3.Text = string.Empty; txtPhone4.Text = string.Empty; txtPhone5.Text = string.Empty; GetAndSetSequence(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMasterAddCrew : DevExpress.XtraEditors.XtraForm { public frmMasterAddCrew() { InitializeComponent(); fillMasterData(); GetAndSetSequence(); txtEmployeeName.Focus(); } public frmMasterAddCrew(Int64 nStaffID) { InitializeComponent(); lblEmployeeID.Text = Convert.ToString(nStaffID); fillMasterData(); GetAndSetSequence(); txtEmployeeName.Focus(); } public Int64 nSignatoryID { get; set; } private void GetAndSetSequence() { clsGeneral oclsGeneral = null; try { oclsGeneral = new clsGeneral(); txtEmployeeCode.Text = "EMP/" + Convert.ToString(oclsGeneral.GetSequenceNumber(MainMasterType.Crew.GetHashCode())); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } } } private void fillMasterData() { txtCountry.Text = "India"; txtCity.Text = "Mumbai"; txtState.Text = "Maharashtra"; clsGeneral oclsGeneral = null; try { oclsGeneral = new clsGeneral(); DataSet dsCrew = oclsGeneral.GetCrewMaster(); if (dsCrew != null && dsCrew.Tables.Count > 0) { DataTable dtCompanyType = dsCrew.Tables[0]; //DataTable dtStateMaster = dsCrew.Tables[1]; //DataTable dtCityMaster = dsCrew.Tables[2]; //DataTable dtCountryMaster = dsCrew.Tables[3]; DataTable dtDesignation = dsCrew.Tables[4]; DataRow drComp = dtCompanyType.NewRow(); drComp["nCompanyID"] = 0; drComp["sCompanyName"] = ""; dtCompanyType.Rows.InsertAt(drComp, 0); DataRow drDesg = dtDesignation.NewRow(); drDesg["nDesignationID"] = 0; drDesg["sDesignationName"] = ""; drDesg["SettingStatus"] = 0; dtDesignation.Rows.InsertAt(drDesg, 0); cmbEmpCompany.DataSource = dtCompanyType; cmbEmpCompany.DisplayMember = "sCompanyName"; cmbEmpCompany.ValueMember = "nCompanyID"; //cmbStateMaster.DataSource = dtStateMaster; //cmbStateMaster.DisplayMember = "StateName"; //cmbStateMaster.ValueMember = "StateName"; //cmbStateMaster.Text = "Maharashtra"; //cmbCityMaster.DataSource = dtCityMaster; //cmbCityMaster.DisplayMember = "CityName"; //cmbCityMaster.ValueMember = "CityName"; //cmbCityMaster.Text = "Mumbai"; //cmbCountryMaster.DataSource = dtCountryMaster; //cmbCountryMaster.DisplayMember = "sCountryName"; //cmbCountryMaster.ValueMember = "sCountryName"; //cmbCountryMaster.Text = "India"; cmbEmpDesignation.SelectedIndexChanged -= cmbEmpDesignation_SelectedIndexChanged; cmbEmpDesignation.DataSource = dtDesignation; cmbEmpDesignation.DisplayMember = "sDesignationName"; cmbEmpDesignation.ValueMember = "nDesignationID"; cmbEmpDesignation.SelectedIndexChanged += cmbEmpDesignation_SelectedIndexChanged; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } } } void cmbEmpDesignation_SelectedIndexChanged(object sender, EventArgs e) { try { if (Convert.ToInt64(cmbEmpDesignation.SelectedValue) != 0) { bool bAllowAccess = false; DataTable dtSource = (DataTable)cmbEmpDesignation.DataSource; if (dtSource != null) { DataRow[] dr = dtSource.Select("nDesignationID=" + cmbEmpDesignation.SelectedValue); if (dr != null) { bAllowAccess = Convert.ToBoolean(dr[0]["SettingStatus"]); } } if (bAllowAccess==true) { pnlLoginDetails.Visible = true; } else { pnlLoginDetails.Visible = false; } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private int CheckPanelVisibility() { int nPanelCount = 0; if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == false && pnlPhoneThree.Visible == false && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 2; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == false && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 3; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 4; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == true && pnlPhoneFive.Visible == false) { nPanelCount = 5; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == true && pnlPhoneFive.Visible == false) { nPanelCount = 6; } return nPanelCount; } private void ShowHidePhonePanel(string sPhoneNo = "", int PhoneCount = 1) { switch (PhoneCount) { case 1: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = false; pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone1.Text = sPhoneNo; break; } case 2: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneTwo.BringToFront(); pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone2.Text = sPhoneNo; break; } case 3: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneThree.BringToFront(); pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone3.Text = sPhoneNo; break; } case 4: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFour.BringToFront(); pnlPhoneFive.Visible = false; txtPhone4.Text = sPhoneNo; break; } case 5: { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFive.Visible = true; pnlPhoneFive.BringToFront(); txtPhone5.Text = sPhoneNo; break; } } } private void btnAddPhone_Click(object sender, EventArgs e) { try { int nCompanyPhoneCount = CheckPanelVisibility(); if (nCompanyPhoneCount <= 5) { ShowHidePhonePanel("", nCompanyPhoneCount); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void txtEmployeeName_EditValueChanged(object sender, EventArgs e) { txtEmpAbbrivation.Text = clsGlobal.GenerateAbbrivation(txtEmployeeName.Text); } private void btnSave_Click(object sender, EventArgs e) { if (ValidateForm()) { SaveCrewMember(); } } public bool ValidateForm() { bool bIsValidForm = true; if (txtEmployeeName.Text.Trim() == "") { MessageBox.Show("Please enter employee name.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtEmployeeName.Focus(); return bIsValidForm; } if (cmbEmpDesignation.Text.Trim()=="") { MessageBox.Show("Please select designation.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; cmbEmpDesignation.Focus(); return bIsValidForm; } if (cmbEmpCompany.Text.Trim() == "") { MessageBox.Show("Please select company.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; cmbEmpCompany.Focus(); return bIsValidForm; } if (pnlLoginDetails.Visible==true) { if (txtGafferUserName.Text.Trim() == "") { MessageBox.Show("Please enter username.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferUserName.Focus(); return bIsValidForm; } if (txtGafferPassword.Text.Trim() == "") { MessageBox.Show("Please enter password.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferPassword.Focus(); return bIsValidForm; } if (txtGafferConfirmPassword.Text.Trim() == "") { MessageBox.Show("Please enter confirm password.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferConfirmPassword.Focus(); return bIsValidForm; } if (txtGafferPin.Text.Trim() == "") { MessageBox.Show("Please enter pin.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferPin.Focus(); return bIsValidForm; } if (txtGafferPassword.Text.Length <8) { MessageBox.Show("Password shold be more than 8 characters.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferPassword.Focus(); return bIsValidForm; } if (txtGafferPassword.Text.Trim() != txtGafferConfirmPassword.Text.Trim()) { MessageBox.Show("Password and confirm password not match.\nPassword & confirm password must be same.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtGafferPassword.Focus(); return bIsValidForm; } } return bIsValidForm; } private void SaveCrewMember() { StaffMaster clsStaffMaster = null; try { string sPhone1 = Convert.ToString(txtPhone1.Text.Trim()); string sPhone2 = Convert.ToString(txtPhone4.Text.Trim()); string sPhone3 = Convert.ToString(txtPhone5.Text.Trim()); string sPhone4 = Convert.ToString(txtPhone3.Text.Trim()); string sPhone5 = Convert.ToString(txtPhone2.Text.Trim()); string sPhoneAll = string.Empty; if (sPhone1 != "") { sPhoneAll += sPhone1; } if (sPhone2 != "") { sPhoneAll += "," + sPhone2; } if (sPhone3 != "") { sPhoneAll += "," + sPhone3; } if (sPhone4 != "") { sPhoneAll += "," + sPhone4; } if (sPhone5 != "") { sPhoneAll += "," + sPhone5; } byte[] EmployeeImage = null; if (picEmployeemage.Image != null) { using (MemoryStream ms = new MemoryStream()) { picEmployeemage.Image.Save(ms, ImageFormat.Jpeg); EmployeeImage = new byte[ms.Length]; ms.Position = 0; ms.Read(EmployeeImage, 0, EmployeeImage.Length); } } clsStaffMaster = new StaffMaster(); clsStaffMaster.nStaffID = Convert.ToInt64(lblEmployeeID.Text); clsStaffMaster.nDesignationID = Convert.ToInt64(cmbEmpDesignation.SelectedValue); clsStaffMaster.nCompanyID = Convert.ToInt64(cmbEmpCompany.SelectedValue); clsStaffMaster.sStaffCode = Convert.ToString(txtEmployeeCode.Text.Trim()); clsStaffMaster.sStaffName = Convert.ToString(txtEmployeeName.Text.Trim()); clsStaffMaster.sStaffAbbrivation = Convert.ToString(txtEmpAbbrivation.Text.Trim()); clsStaffMaster.dtDOB = Convert.ToDateTime(dtEmpBirthdate.Text.ToString()); clsStaffMaster.sAge = Convert.ToString(txtEmpAge.Text.Trim()); clsStaffMaster.sGender = Convert.ToString(cmbGender.SelectedValue); clsStaffMaster.sPhoneNo = sPhoneAll; clsStaffMaster.sPermanentAddressLine1 = Convert.ToString(txtPermanentAddressLine1.Text.Trim()); clsStaffMaster.sPermanentAddressLine2 = Convert.ToString(txtPermanentAddressLine2.Text.Trim()); clsStaffMaster.sPermanentPincode = Convert.ToString(txtPermanentPincode.Text.Trim()); clsStaffMaster.sPermanentDistTown = Convert.ToString(txtDistrictTownVillage.Text.Trim()); clsStaffMaster.sAddressLine1 = Convert.ToString(txtAddressLine1.Text.Trim()); clsStaffMaster.sAddressLine2 = Convert.ToString(txtAddressLine2.Text.Trim()); clsStaffMaster.sCity = Convert.ToString(txtCity.Text.Trim()); clsStaffMaster.sState = Convert.ToString(txtState.Text.Trim()); clsStaffMaster.sCountry = Convert.ToString(txtCountry.Text.Trim()); clsStaffMaster.sPincode = Convert.ToString(txtPincode.Text.Trim()); clsStaffMaster.sEmail = Convert.ToString(txtEmail.Text.Trim()); clsStaffMaster.dtDOJ = Convert.ToDateTime(dtEmpBirthdate.Text.ToString()); clsStaffMaster.sGSTNNo = Convert.ToString(txtGSTNNo.Text.Trim()); clsStaffMaster.sPANNo = Convert.ToString(txtPANNo.Text.Trim()); clsStaffMaster.sAadharNo = Convert.ToString(txtAadharNo.Text.Trim()); clsStaffMaster.sReferenceBy = Convert.ToString(txtReferenceBy.Text.Trim()); clsStaffMaster.sAllergies = Convert.ToString(txtAllergies.Text.Trim()); clsStaffMaster.sBloodGroup = Convert.ToString(cmbBloodGroup.Text.Trim()); clsStaffMaster.sWorkingSince = Convert.ToString(txtWorkedSince.Text.Trim()); clsStaffMaster.sSalary = Convert.ToString(txtSalary.Text.Trim()); clsStaffMaster.sDailyWages = Convert.ToString(txtDailyWages.Text.Trim()); clsStaffMaster.sUnionID = Convert.ToString(txtUnionID.Text.Trim()); clsStaffMaster.dtUnionIDRenewalDate = Convert.ToDateTime(dtUnionRenewDate.Text.Trim()); clsStaffMaster.sFirstLicenseNumber = Convert.ToString(txtlic1No.Text.Trim()); clsStaffMaster.dtFirstLicenseRenewalDate = Convert.ToDateTime(dtLic1RenewDate.Text.Trim()); clsStaffMaster.sSecondLicenseNumber = Convert.ToString(txtLic2No.Text.Trim()); clsStaffMaster.dtSecondLicenseRenewalDate = Convert.ToDateTime(dtLic2RenewDate.Text.Trim()); clsStaffMaster.sThirdLicenseNumber = Convert.ToString(txtLic2No.Text.Trim()); clsStaffMaster.dtThirdLicenseRenewalDate = Convert.ToDateTime(dtLic3RenewDate.Text.Trim()); clsStaffMaster.imgPhoto = EmployeeImage; if (pnlLoginDetails.Visible==true) { clsStaffMaster.bIsAllowAccess = true; clsStaffMaster.sUserName = Convert.ToString(txtGafferUserName.Text.Trim()); clsStaffMaster.sPin = Convert.ToString(txtGafferPin.Text.Trim()); clsStaffMaster.sPassword = Convert.ToString(clsEncryption.EncryptToBase64String(txtGafferConfirmPassword.Text.Trim())); } Int64 nCrewMemberID = clsStaffMaster.InsertUpdateStaffMaster(); if (nCrewMemberID != 0) { MessageBox.Show("Crew member is saved successfully.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); ClearForm(); } else { MessageBox.Show("Error while saving crew member.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void frmMasterAddCrew_Load(object sender, EventArgs e) { try { dtEmpBirthdate.EditValueChanged-=dtEmpBirthdate_EditValueChanged; dtEmpBirthdate.EditValue = DateTime.Now; dtEmpBirthdate.EditValueChanged += dtEmpBirthdate_EditValueChanged; dtEmpDOJ.EditValue = DateTime.Now; dtLic1RenewDate.EditValue = DateTime.Now; dtLic2RenewDate.EditValue = DateTime.Now; dtLic3RenewDate.EditValue = DateTime.Now; dtUnionRenewDate.EditValue = DateTime.Now; if (Convert.ToInt64(lblEmployeeID.Text) > 0) { FillCrewMemberDetails(Convert.ToInt64(lblEmployeeID.Text)); } if (nSignatoryID != 0) { cmbEmpDesignation.SelectedValue = nSignatoryID; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void FillCrewMemberDetails(long nStaffID) { StaffMaster clsStaffMaster = null; DataTable dtStaffDetails = null; try { clsStaffMaster = new StaffMaster(); dtStaffDetails = clsStaffMaster.GetStaffInformation(nStaffID); if (dtStaffDetails != null && dtStaffDetails.Rows.Count > 0) { lblEmployeeID.Text = Convert.ToString(dtStaffDetails.Rows[0]["nStaffID"]); txtEmployeeCode.Text = Convert.ToString(dtStaffDetails.Rows[0]["sStaffCode"]); txtEmployeeName.Text = Convert.ToString(dtStaffDetails.Rows[0]["sStaffName"]); cmbEmpDesignation.SelectedValue = Convert.ToString(dtStaffDetails.Rows[0]["nDesignationID"]); cmbEmpCompany.SelectedValue = Convert.ToString(dtStaffDetails.Rows[0]["nCompanyID"]); txtEmpAbbrivation.Text = Convert.ToString(dtStaffDetails.Rows[0]["sStaffAbbrivation"]); cmbGender.SelectedValue = Convert.ToString(dtStaffDetails.Rows[0]["sGender"]); dtEmpBirthdate.EditValue = Convert.ToDateTime(dtStaffDetails.Rows[0]["dtDOB"]); txtEmpAge.Text = Convert.ToString(dtStaffDetails.Rows[0]["sAge"]); txtAddressLine1.Text = Convert.ToString(dtStaffDetails.Rows[0]["sAddressLine1"]); txtAddressLine2.Text = Convert.ToString(dtStaffDetails.Rows[0]["sAddressLine2"]); txtCity.Text = Convert.ToString(dtStaffDetails.Rows[0]["sCity"]); txtState.Text = Convert.ToString(dtStaffDetails.Rows[0]["sState"]); txtCountry.Text = Convert.ToString(dtStaffDetails.Rows[0]["sCountry"]); txtPincode.Text = Convert.ToString(dtStaffDetails.Rows[0]["sPincode"]); txtEmail.Text = Convert.ToString(dtStaffDetails.Rows[0]["sEmail"]); txtPermanentAddressLine1.Text = Convert.ToString(dtStaffDetails.Rows[0]["sPermanentAddressLine1"]); txtPermanentAddressLine2.Text = Convert.ToString(dtStaffDetails.Rows[0]["sPermanentAddressLine2"]); txtPermanentPincode.Text = Convert.ToString(dtStaffDetails.Rows[0]["sPermanentPincode"]); txtDistrictTownVillage.Text = Convert.ToString(dtStaffDetails.Rows[0]["sPermanentDistTown"]); dtEmpDOJ.EditValue = Convert.ToDateTime(dtStaffDetails.Rows[0]["dtDOJ"]); txtGSTNNo.Text = Convert.ToString(dtStaffDetails.Rows[0]["sGSTNNo"]); txtPANNo.Text = Convert.ToString(dtStaffDetails.Rows[0]["sPANNo"]); txtAadharNo.Text = Convert.ToString(dtStaffDetails.Rows[0]["sAadharNo"]); txtReferenceBy.Text = Convert.ToString(dtStaffDetails.Rows[0]["sReferenceBy"]); txtAllergies.Text = Convert.ToString(dtStaffDetails.Rows[0]["sAllergies"]); cmbBloodGroup.Text = Convert.ToString(dtStaffDetails.Rows[0]["sBloodGroup"]); txtWorkedSince.Text = Convert.ToString(dtStaffDetails.Rows[0]["sWorkingSince"]); txtDailyWages.Text = Convert.ToString(dtStaffDetails.Rows[0]["sDailyWages"]); txtSalary.Text = Convert.ToString(dtStaffDetails.Rows[0]["sSalary"]); txtUnionID.Text = Convert.ToString(dtStaffDetails.Rows[0]["sUnionID"]); dtUnionRenewDate.EditValue = Convert.ToDateTime(dtStaffDetails.Rows[0]["dtUnionIDRenewalDate"]); txtlic1No.Text = Convert.ToString(dtStaffDetails.Rows[0]["sFirstLicenseNumber"]); dtLic1RenewDate.EditValue = Convert.ToDateTime(dtStaffDetails.Rows[0]["dtFirstLicenseRenewalDate"]); txtLic2No.Text = Convert.ToString(dtStaffDetails.Rows[0]["sSecondLicenseNumber"]); dtLic2RenewDate.EditValue = Convert.ToDateTime(dtStaffDetails.Rows[0]["dtSecondLicenseRenewalDate"]); txtLic3No.Text = Convert.ToString(dtStaffDetails.Rows[0]["sThirdLicenseNumber"]); dtLic3RenewDate.EditValue = Convert.ToDateTime(dtStaffDetails.Rows[0]["dtThirdLicenseRenewalDate"]); string[] sPhoneAll = Convert.ToString(dtStaffDetails.Rows[0]["sPhoneNo"]).Split(','); if (sPhoneAll.Length > 0) { int nCompPanelCount = GetPanelCount(sPhoneAll.Length); for (int i = 0; i < nCompPanelCount; i++) { ShowHidePhonePanel(sPhoneAll[i], i + 1); } } byte[] empImage = null; if (dtStaffDetails.Rows[0]["sPhoto"] != DBNull.Value) { empImage = (byte[])dtStaffDetails.Rows[0]["sPhoto"]; MemoryStream msHeaderImage = new MemoryStream(empImage); picEmployeemage.Image = Image.FromStream(msHeaderImage); } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private int GetPanelCount(int nStringLength) { int nPanelCount = 0; if (nStringLength <= 5) { switch (nStringLength) { case 1: nPanelCount = 1; break; case 2: nPanelCount = 2; break; case 3: nPanelCount = 3; break; case 4: nPanelCount = 4; break; case 5: nPanelCount = 5; break; } } return nPanelCount; } private void dtEmpBirthdate_EditValueChanged(object sender, EventArgs e) { try { int num = Convert.ToInt32((DateTime.Now - Convert.ToDateTime(dtEmpBirthdate.Text)).Days) / 365; if (num > 0) { txtEmpAge.Text = num.ToString(); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } public void ClearForm() { txtEmployeeName.Text = string.Empty; cmbEmpDesignation.SelectedValue = 0; cmbEmpCompany.SelectedValue = 0; txtEmpAbbrivation.Text = string.Empty; cmbGender.SelectedValue = ""; dtEmpBirthdate.EditValue = DateTime.Now; txtEmpAge.Text = string.Empty; txtAddressLine1.Text = string.Empty; txtAddressLine2.Text = string.Empty; txtCountry.Text = "India"; txtCity.Text = "Mumbai"; txtState.Text = "Maharashtra"; txtPincode.Text = string.Empty; txtEmail.Text = string.Empty; txtPermanentAddressLine1.Text = string.Empty; txtPermanentAddressLine2.Text = string.Empty; txtPermanentPincode.Text = string.Empty; txtDistrictTownVillage.Text = string.Empty; dtEmpDOJ.EditValue = DateTime.Now; txtGSTNNo.Text = string.Empty; txtPANNo.Text = string.Empty; txtAadharNo.Text = string.Empty; txtReferenceBy.Text = string.Empty; txtAllergies.Text = string.Empty; cmbBloodGroup.Text = string.Empty; txtWorkedSince.Text = string.Empty; txtDailyWages.Text = string.Empty; txtSalary.Text = string.Empty; txtUnionID.Text = string.Empty; dtUnionRenewDate.EditValue = DateTime.Now; txtlic1No.Text = string.Empty; dtLic1RenewDate.EditValue = DateTime.Now; txtLic2No.Text = string.Empty; dtLic2RenewDate.EditValue = DateTime.Now; txtLic3No.Text = string.Empty; dtLic3RenewDate.EditValue = DateTime.Now; txtPhone1.Text = string.Empty; txtPhone2.Text = string.Empty; txtPhone3.Text = string.Empty; txtPhone4.Text = string.Empty; txtPhone5.Text = string.Empty; GetAndSetSequence(); if (picEmployeemage != null) { picEmployeemage.Image = null; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LGRentalMgntSystem { public static class clsGlobal { public static string _sMessageboxCaption = string.Empty; public static string MessageboxCaption { get { return _sMessageboxCaption; } //set { _sMessageboxCaption = value; } } private static string _sName = string.Empty; public static string LoginUserName { get { return clsGlobal._sName; } set { clsGlobal._sName = value; } } private static Int64 _nUserID = 0; public static Int64 UserID { get { return clsGlobal._nUserID; } set { clsGlobal._nUserID = value; } } private static string _sUserDesignation = string.Empty; public static string UserDesignation { get { return clsGlobal._sUserDesignation; } set { clsGlobal._sUserDesignation = value; } } public static string GenerateAbbrivation(string stext) { string sAbbrivation = string.Empty; string[] sFullName = stext.Split(' '); foreach (var item in sFullName) { if (item.All(char.IsDigit)) { sAbbrivation = sAbbrivation + item.ToString(); } else { sAbbrivation = sAbbrivation + item[0].ToString().ToUpper(); } } return sAbbrivation; } } } <file_sep>using LGRentalMgntSystem.Class; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public enum MasterType { CompanyType = 0, MaterialType = 1, Designation = 2, AssetType = 3, AssetType1 = 4, PartyType = 5, VehicleType = 6, ColourType = 7, DensityType = 8, AssetMainType=9, Make=10 } public enum MainMasterType { Company=1, Crew=2, Party=3, Gaffer=4, Location=5 } public enum TransactionType { Asset=0, Kit=1, Challan=2, JobCart=3 } public partial class frmDashboard : DevExpress.XtraBars.Ribbon.RibbonForm { public frmDashboard() { InitializeComponent(); } private void btnAddAsset_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmAddAsset frmAsset = new frmAddAsset(); frmAsset.ShowDialog(); } private void btnAssetList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMainAssetList frmAssetList = new frmMainAssetList(); frmAssetList.ShowDialog(); } private void btnExpiredAssetList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { MessageBox.Show("Work is Progrss..."); } private void btnAddKit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmAddKit frmAddKit = new frmAddKit(); frmAddKit.ShowDialog(); //MessageBox.Show("Work is Progrss..."); } private void btnKitList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMainKitList frmMainKitList = new frmMainKitList(); frmMainKitList.ShowDialog(); //MessageBox.Show("Work is Progrss..."); } #region "Type Master" private void btnAddAssetMainType_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.AssetMainType); } private void btnAssetMainTypeList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.AssetMainType); } private void btnAddCompanyType_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.CompanyType); } private void btnCompanyTypeList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.CompanyType); } private void btnAddMaterialType_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.MaterialType); } private void btnMaterialTypeList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.MaterialType); } private void btnAddDesigantion_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.Designation); } private void btnDesignationList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.Designation); } private void btnAssetType_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.AssetType); } private void btnAssetTypeList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.AssetType); } private void btnAddAssetType1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.AssetType1); } private void btnAssetType1List_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.AssetType1); } private void btnAddPartyType_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.PartyType); } private void btnPartyList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.PartyType); } private void btnAddVehicleType_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.VehicleType); } private void btnVehicleList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.VehicleType); } private void btnAddColourType_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.ColourType); } private void btnColourList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.ColourType); } private void btnAddDensityType_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.DensityType); } private void btnDensityTypeList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.DensityType); } private void btnAddMakeMaster_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMasterForm(MasterType.Make); } private void btnMakeMasterList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { showMaster(MasterType.Make); } public bool showMasterForm(MasterType MasterType) { bool _result = false; try { frmAssetMaster frmAssetMaster = null; switch (MasterType) { case MasterType.CompanyType: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.CompanyType; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.MaterialType: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.MaterialType; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.Designation: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.Designation; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.AssetType: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.AssetType; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.AssetType1: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.AssetType1; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.PartyType: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.PartyType; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.VehicleType: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.VehicleType; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.ColourType: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.ColourType; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.DensityType: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.DensityType; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.AssetMainType: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.AssetMainType; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } case MasterType.Make: { if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } frmAssetMaster = new frmAssetMaster(); frmAssetMaster.MasterType = MasterType.Make; frmAssetMaster.ShowDialog(); _result = frmAssetMaster.IsMasterSave; if (frmAssetMaster != null) { frmAssetMaster.Dispose(); frmAssetMaster = null; } break; } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } return _result; } public bool showMaster(MasterType MasterType) { bool _result = false; try { LGRentalMgntSystem.Forms.frmAssetList frmAssetMasterList = null; switch (MasterType) { case MasterType.CompanyType: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.CompanyType; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.MaterialType: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.MaterialType; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.Designation: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.Designation; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.AssetType: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.AssetType; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.AssetType1: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.AssetType1; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.PartyType: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.PartyType; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.VehicleType: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.VehicleType; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.ColourType: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.ColourType; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.DensityType: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.DensityType; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.AssetMainType: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.AssetMainType; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } case MasterType.Make: { if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } frmAssetMasterList = new LGRentalMgntSystem.Forms.frmAssetList(); frmAssetMasterList.MasterType = MasterType.Make; frmAssetMasterList.ShowDialog(); if (frmAssetMasterList != null) { frmAssetMasterList.Dispose(); frmAssetMasterList = null; } break; } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } return _result; } #endregion #region "Master" private void btnAddCompanyMaster_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterAddCompany frmAddCompany = new frmMasterAddCompany(); frmAddCompany.ShowDialog(); } private void btnCompanyMasterList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterListCompany frmCompanyList = new frmMasterListCompany(); frmCompanyList.ShowDialog(); } private void btnAddCrewMaster_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterAddCrew frmAddCrew = new frmMasterAddCrew(); frmAddCrew.ShowDialog(); } private void btnCrewMasterList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterListCrewMember frmCrewList = new frmMasterListCrewMember(); frmCrewList.ShowDialog(); } private void btnAddPartyMaster_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterAddParty frmAddParty = new frmMasterAddParty(); frmAddParty.ShowDialog(); } private void btnPartyMasterList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterListParty frmPartyList = new frmMasterListParty(); frmPartyList.ShowDialog(); } private void btnAddGafferMaster_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterAddGaffer ofrmMasterAddGaffer = new frmMasterAddGaffer(); ofrmMasterAddGaffer.ShowDialog(); } private void btnGafferMasterList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterListGaffer frmGafferList = new frmMasterListGaffer(); frmGafferList.ShowDialog(); } private void btnAddLocationMaster_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterAddLocation ofrmMasterAddLocation = new frmMasterAddLocation(); ofrmMasterAddLocation.ShowDialog(); } private void btnLocationMasterList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmMasterListLocation ofrmMasterListLocation = new frmMasterListLocation(); ofrmMasterListLocation.ShowDialog(); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { class clsMasters { #region "Constructor & Distructor" private bool disposed = false; public clsMasters() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~clsMasters() { Dispose(false); } #endregion public Int64 nMasterID { get; set; } public string sMasterName { get; set; } public string sMasterCode { get; set; } public Int64 nMasterMainID { get; set; } public MasterType MasterType { get; set; } public bool IsAllowAccess { get; set; } public bool IsAllowSignatory { get; set; } public Int64 InsertUpdateMaster() { Int64 nMasterID = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objValue = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nMasterID", this.nMasterID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sMasterName", this.sMasterName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sMasterCode", this.sMasterCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@nMasterMainID", this.nMasterMainID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nMasterType", this.MasterType.GetHashCode(), ParameterDirection.Input, SqlDbType.Int); oDBParameter.Add("@bIsAllowAccess", this.IsAllowAccess, ParameterDirection.Input, SqlDbType.Bit); oDBParameter.Add("@bIsAllowSignatory", this.IsAllowSignatory, ParameterDirection.Input, SqlDbType.Bit); oDBParameter.Add("@nReturnID", 0, ParameterDirection.InputOutput, SqlDbType.Int); oDBAccess.OpenConnection(false); oDBAccess.Execute("lgsp_INUP_Masters", oDBParameter,out objValue); oDBAccess.CloseConnection(false); if (objValue != null) { nMasterID = Convert.ToInt64(objValue); } } catch (Exception ex) { oDBAccess.CloseConnection(false); nMasterID = -1; throw ex; //MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nMasterID; } public int DeleteMaster() { int nMasterID = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objValue = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nMasterID", this.nMasterID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nMasterType", this.MasterType.GetHashCode(), ParameterDirection.Input, SqlDbType.Int); oDBParameter.Add("@nReturnID", 0, ParameterDirection.InputOutput, SqlDbType.Int); oDBAccess.OpenConnection(false); oDBAccess.Execute("lgsp_Delete_Masters", oDBParameter, out objValue); oDBAccess.CloseConnection(false); if (objValue != null) { nMasterID = Convert.ToInt32(objValue); } } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nMasterID; } public DataTable GetAssetMainMasterType(Int32 nAssetType=0) { DataTable dt = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nAssetType", nAssetType, ParameterDirection.Input, SqlDbType.VarChar); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_getAssetMasterList", oDBParameter, out dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return dt; } public DataTable GetMasterTypeData(Int32 nMasterType) { DataTable dt = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nMasterType", nMasterType, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_AllMastersData", oDBParameter, out dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return dt; } public DataTable GetMasterTypeDataBbValue(Int32 nMasterType,string sSearchString="") { DataTable dt = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nMasterType", nMasterType, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sSearchString", sSearchString, ParameterDirection.Input, SqlDbType.VarChar); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_AllMastersData_Search", oDBParameter, out dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return dt; } } } <file_sep>using LGRentalMgntSystem.Class; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmLogin : DevExpress.XtraEditors.XtraForm { public string sMessageboxCaption =string.Empty; public frmLogin() { InitializeComponent(); //txtUsername.Text = "admin"; //txtPassword.Text = "<PASSWORD>"; sMessageboxCaption = System.Configuration.ConfigurationManager.AppSettings["MessageboxCaption"]; } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void btnLogin_Click(object sender, EventArgs e) { try { if (txtUsername.Text.Trim()=="") { MessageBox.Show("Please enter username.",sMessageboxCaption,MessageBoxButtons.OK,MessageBoxIcon.Information); txtUsername.Focus(); return; } else if (txtPassword.Text.Trim()=="") { MessageBox.Show("Please enter password.", sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); txtPassword.Focus(); return; } string sUserName = txtUsername.Text.Trim(); string sTestPassword = clsEncryption.EncryptToBase64String(txtPassword.Text.Trim()); string sPassword = txtPassword.Text.Trim(); UserMaster clsUserMaster = new UserMaster(); bool bIsUserValid=clsUserMaster.Login(sUserName,sPassword); if (bIsUserValid) { clsGlobal.LoginUserName = clsUserMaster.sUserName; clsGlobal.UserDesignation = clsUserMaster.sUserDesignation; clsGlobal.UserID = clsUserMaster.nUserID; this.Hide(); frmDashboard frmMain = new frmDashboard(); DialogResult dgResult= frmMain.ShowDialog(); if (dgResult==DialogResult.Cancel) { Application.Exit(); } } else { MessageBox.Show("User is not valid. Please check user name and Password.", sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); txtPassword.Clear(); return; } } catch (Exception ex) { MessageBox.Show("Error: "+ex.ToString(), sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem.Class { class UserMaster : IDisposable { #region "Constructor & Distructor" private bool disposed = false; public UserMaster() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~UserMaster() { Dispose(false); } #endregion #region "Properties" public Int64 nUserID { get; set; } public string sName { get; set; } public string sUserDesignation { get; set; } public string sAddressLine1 { get; set; } public string sAddressLine2 { get; set; } public string sCity { get; set; } public string sState { get; set; } public string sCountry { get; set; } public string sPincode { get; set; } public string sMobileNo { get; set; } public string sEmail { get; set; } public string sUserName { get; set; } public string sPassword { get; set; } public bool bIsActive { get; set; } #endregion #region Methods public bool Login(string sUserName,string sPassword) { bool bIsValidUser = false; string sDecryptPassword = string.Empty; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable dt = new DataTable(); try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@sUserName", sUserName, ParameterDirection.Input, SqlDbType.VarChar); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_getUserByUserName", oDBParameter, out dt); oDBAccess.CloseConnection(false); if (dt != null && dt.Rows.Count > 0) { sDecryptPassword = clsEncryption.DecryptFromBase64String(Convert.ToString(dt.Rows[0]["sPassword"])); if (sDecryptPassword==sPassword) { bIsValidUser = true; this.nUserID = Convert.ToInt64(dt.Rows[0]["nUserID"]); this.sName = Convert.ToString(dt.Rows[0]["sName"]); this.sUserName = Convert.ToString(dt.Rows[0]["sUserName"]); this.sUserDesignation = Convert.ToString(dt.Rows[0]["sUserDesignation"]); this.bIsActive = Convert.ToBoolean(dt.Rows[0]["bIsActive"]); } } } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), "Rental System LoginSP", MessageBoxButtons.OK, MessageBoxIcon.Information); } return bIsValidUser; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace LGRentalMgntSystem { static class clsEncryption { private static byte[] _key; private static byte[] _iv = { 18, 52, 86, 120, 144, 171, 205, 239 }; private static string encryptionKey = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Key"]); public static string EncryptToBase64String(string stringToEncrypt) { try { _key = Encoding.UTF8.GetBytes(encryptionKey.Substring(0, 8)); //convert our input string to a byte array byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt); MemoryStream ms = new MemoryStream(); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); // Encrypt the bytearray CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(_key, _iv), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } catch (Exception ex) { return null; } } public static string DecryptFromBase64String(string stringToDecrypt) { try { byte[] inputByteArray = new byte[stringToDecrypt.Length]; _key = Encoding.UTF8.GetBytes(encryptionKey.Substring(0, 8)); inputByteArray = Convert.FromBase64String(stringToDecrypt); MemoryStream ms = new MemoryStream(); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(_key, _iv), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.UTF8.GetString(ms.ToArray()); } catch (Exception ex) { return null; } } } } <file_sep>using LGRentalMgntSystem.Class; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmAsset : Form { public frmAsset() { InitializeComponent(); } private void tsb_Save_Click(object sender, EventArgs e) { if (MessageBox.Show("Do you want to save asset?", clsGlobal.MessageboxCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question)==DialogResult.No) { return; } else { SaveAsset(); } } private void tsb_Close_Click(object sender, EventArgs e) { if (MessageBox.Show("Do you want to save asset?", clsGlobal.MessageboxCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { this.Close(); } else { SaveAsset(); } } private Int64 SaveAsset() { AssetMaster oAssetMaster = null; Int64 nAssetID = 0; try { oAssetMaster = new AssetMaster(); //oAssetMaster.nAssetID = 0; //oAssetMaster.sAssetName = txtAssetName.Text.Trim(); //oAssetMaster.sAssetDescription = txtAssetDescription.Text.Trim(); //oAssetMaster.sAssetShortDescription = txtAssetShortDescription.Text.Trim(); //oAssetMaster.nCompanyID = Convert.ToInt64(cmbCompanyList.SelectedValue); ////oAssetMaster.nBarcodeID = Convert.ToInt64(txtAssetBarcode.Text.Trim()); //oAssetMaster.nAssetMainTypeID = Convert.ToInt64(cmbAssetTypeName.SelectedValue); //oAssetMaster.sAssetSize = txtAssetSize.Text.Trim(); //oAssetMaster.sAssetCapacity = txtAssetCapacity.Text.Trim(); //oAssetMaster.sAssetDensity = txtAssetDensity.Text.Trim(); //oAssetMaster.sAssetQuality = txtAssetQuality.Text.Trim(); //oAssetMaster.nAssetMaterialID = Convert.ToInt64(cmbAssetmaterialType.SelectedValue); //oAssetMaster.sAssetMake = txtAssetMake.Text.Trim(); //oAssetMaster.nAssetTypeID = Convert.ToInt64(cmbAssetType.SelectedValue); //oAssetMaster.nAssetTypeOneID = Convert.ToInt64(cmbAssetType1.SelectedValue); //oAssetMaster.sAssetWeight = txtAssetWeight.Text.Trim(); //oAssetMaster.sAssetPackingDimention = txtAssetPackingDimention.Text.Trim(); //oAssetMaster.sAssetShelfLife = txtAssetShelfLife.Text.Trim(); //oAssetMaster.sAssetShelfLifeUnit = cmbAssetShelfLifeUnit.Text.Trim(); //oAssetMaster.sAssetHSN_SACCode = txtAssetHSNOrSACCode.Text.Trim(); //oAssetMaster.sAssetVendor = txtAssetVendor.Text.Trim(); //oAssetMaster.sAssetReorderTime = txtAssetReorderTime.Text.Trim(); //oAssetMaster.dtAssetDateOFIntroduction =Convert.ToDateTime(dtpIntroductionDate.Text.ToString()); //oAssetMaster.dtAssetDateOfRetirement = Convert.ToDateTime(dtpRetirementDate.Text.ToString()); //oAssetMaster.sAssetRate = txtAssetRate.Text.Trim(); //oAssetMaster.sAssetRentalRate = txtAssetRentalRate.Text.Trim(); //oAssetMaster.sAssetAbbrivation = GenerateAbbrivation(txtAssetName.Text.Trim()); //oAssetMaster.sAssetCode = GenerateCode(); //nAssetID= oAssetMaster.InsertUpdateAsset(); } catch (Exception ex) { throw; } return nAssetID; } private string GenerateAbbrivation(string sAssetName) { string sAbbrivation = string.Empty; string[] sFullName = sAssetName.Split(' '); foreach (var item in sFullName) { if (item.All(char.IsDigit)) { sAbbrivation = sAbbrivation + item.ToString(); } else { sAbbrivation = sAbbrivation + item[0].ToString().ToUpper(); } } return sAbbrivation; } private string GenerateCode() { //For Fixtures,Equipment’s, & Lights: Make (Char 3) Voltage(Char 4) Fixture Type (Char 3) Type (Char 3) Sr.No (Number 3) //Cloth Size (Char 5) Density (Char 4) Type (Char 4) Sr. No.(Number 3) //Accessories Type(NumChar 5) Sr.no.(Number 3) string sAssetCode = string.Empty; switch (cmbAssetTypeName.Text.Trim().ToString()) { case "Cloth": { string sSize = txtAssetSize.Text.Substring(0, 3); string sDensity = txtAssetDensity.Text.Substring(0, 4); string sType = cmbAssetType.Text.Substring(0, 3); string sNumber = ""; sAssetCode = sSize + sDensity + sType + sNumber; break; } case "Accessories": { string sType = cmbAssetType.Text.Substring(0, 3); string sNumber = ""; sAssetCode = sType + sNumber; break; } case "Light": case "Stands": case "Grip": { string sMake = txtAssetMake.Text.Substring(0, 3); string sVoltage = txtAssetCapacity.Text.Substring(0, 4); string sFixtureType = ""; string sType = cmbAssetType.Text.Substring(0, 3); string sNumber = ""; sAssetCode = sMake + sVoltage + sFixtureType + sType + sNumber; break; } } return sAssetCode; } private void frmAsset_Load(object sender, EventArgs e) { //get CompanyList LoadMasterData(); } private void LoadMasterData() { AssetMaster oAssetMaster = null; DataSet dsMaster = null; try { oAssetMaster = new AssetMaster(); dsMaster = oAssetMaster.GetAllMasterData(0); if (dsMaster != null && dsMaster.Tables.Count > 0) { cmbAssetTypeName.DataSource = dsMaster.Tables[0]; cmbAssetTypeName.DisplayMember = "sAssetType"; cmbAssetTypeName.ValueMember = "nAssetMainTypeID"; cmbAssetmaterialType.DataSource = dsMaster.Tables[1]; cmbAssetmaterialType.DisplayMember = "sAssetMaterialName"; cmbAssetmaterialType.ValueMember = "nAssetMaterialID"; cmbAssetType.DataSource = dsMaster.Tables[2]; cmbAssetType.DisplayMember = "sAssetTypeName"; cmbAssetType.ValueMember = "nAssetTypeID"; cmbAssetType1.DataSource = dsMaster.Tables[3]; cmbAssetType1.DisplayMember = "sAssetTypeOneName"; cmbAssetType1.ValueMember = "nAssetTypeOneID"; cmbAssetShelfLifeUnit.DataSource = dsMaster.Tables[4]; cmbAssetShelfLifeUnit.DisplayMember = "sAssetShelfLifeUnit"; cmbAssetShelfLifeUnit.ValueMember = "nAssetShelfLifeUnit"; } } catch (Exception) { throw; } finally { if (oAssetMaster != null) { oAssetMaster.Dispose(); oAssetMaster = null; } } } } } <file_sep>using LGRentalMgntSystem.Class; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { class clsGeneral { #region "Constructor & Distructor" private bool disposed = false; public clsGeneral() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~clsGeneral() { Dispose(false); } #endregion #region "Methods" public Int64 GetSequenceNumber_Transaction(TransactionType oTransactionType) { Int64 nSequencNo = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nTransactionType", oTransactionType.GetHashCode(), ParameterDirection.Input, SqlDbType.Int); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_SequenceNoTransaction", oDBParameter, out _dt); oDBAccess.CloseConnection(false); if (_dt != null && _dt.Rows.Count > 0) { nSequencNo = Convert.ToInt64(_dt.Rows[0][0]); } } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nSequencNo; } public Int64 GetSequenceNumber(int nMasterType) { Int64 nSequencNo = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt=null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nMasterType", nMasterType, ParameterDirection.Input, SqlDbType.Int); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_SequenceNo", oDBParameter,out _dt); oDBAccess.CloseConnection(false); if (_dt!=null&&_dt.Rows.Count>0) { nSequencNo = Convert.ToInt64(_dt.Rows[0][0]); } } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nSequencNo; } public DataSet GetCompanyMaster() { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataSet _dsCompanyMaster = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_CompanyMasterDate", out _dsCompanyMaster); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess!=null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter!=null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dsCompanyMaster; } public DataSet GetCrewMaster() { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataSet _dsCompanyMaster = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_CrewMasterData", out _dsCompanyMaster); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dsCompanyMaster; } public DataSet GetPartyMaster() { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataSet _dsCompanyMaster = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_PartyMasterData", out _dsCompanyMaster); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dsCompanyMaster; } public DataSet GetGafferMaster() { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataSet _dsCompanyMaster = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_CSCMasterData", out _dsCompanyMaster); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dsCompanyMaster; } public DataSet GetLocationMaster() { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataSet _dsCompanyMaster = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_CSCMasterData", out _dsCompanyMaster); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dsCompanyMaster; } public Int64 GetDeleteMasterType(int nMasterType, Int64 nID) { Int64 nSequencNo = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nMasterType", nMasterType, ParameterDirection.Input, SqlDbType.Int); oDBParameter.Add("@nID", nID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Delete_MasterType", oDBParameter, out _dt); oDBAccess.CloseConnection(false); if (_dt != null && _dt.Rows.Count > 0) { nSequencNo = Convert.ToInt64(_dt.Rows[0][0]); } } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return nSequencNo; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { class LocationMaster { #region "Constructor & Distructor" private bool disposed = false; public LocationMaster() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~LocationMaster() { Dispose(false); } #endregion #region "Properties" public Int64 nLocationID { get; set; } public string sDescription { get; set; } public string sLocationCode { get; set; } public string sAddressLine1 { get; set; } public string sAddressLine2 { get; set; } public string sCity { get; set; } public string sState { get; set; } public string sCountry { get; set; } public string sPincode { get; set; } public string sVillageDistTown { get; set; } #endregion #region "Method" public Int64 InsertUpdateLocationMaster() { Int64 _nLocationID = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objValue = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nLocationID", this.nLocationID, ParameterDirection.InputOutput, SqlDbType.BigInt); oDBParameter.Add("@sDescription", this.sDescription, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sLocationCode", this.sLocationCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAddressLine1", this.sAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAddressLine2", this.sAddressLine2, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCity", this.sCity, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sState", this.sState, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPincode", this.sPincode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCountry", this.sCountry, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sVillageDistTown", this.sVillageDistTown, ParameterDirection.Input, SqlDbType.VarChar); oDBAccess.OpenConnection(false); oDBAccess.Execute("lgsp_INUP_LocationMaster", oDBParameter, out objValue); oDBAccess.CloseConnection(false); if (objValue != null) { _nLocationID = Convert.ToInt64(objValue); } } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _nLocationID; } public DataTable GetLocationInformation(Int64 nLocationID) { DataSet ds = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nLocationID", nLocationID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_LocationDetails", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } public DataTable GetLocationlist(Int64 nLocationID) { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nLocationID", nLocationID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_LocationListDetails", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMasterAddCompany : DevExpress.XtraEditors.XtraForm { public frmMasterAddCompany() { InitializeComponent(); fillMasterData(); GetAndSetSequence(); txtCompanyName.Focus(); ShowHidePhonePanel(); } public frmMasterAddCompany(Int64 nCompanyID) { InitializeComponent(); lblCompanyID.Text = Convert.ToString(nCompanyID); lblFormHeader.Text = "Edit Company"; fillMasterData(); //GetAndSetSequence(); txtCompanyName.Focus(); ShowHidePhonePanel(); } private void ShowHidePhonePanel(string sPhoneType = "", string sPhoneNo = "", int PhoneCount = 1) { switch (PhoneCount) { case 1: { if (sPhoneType.ToLower() == "company") { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = false; pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone1.Text = sPhoneNo; } else if (sPhoneType.ToLower() == "wh") { pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = false; pnlWHPhone3.Visible = false; pnlWHPhone4.Visible = false; pnlWHPhone5.Visible = false; txtWHPhone1.Text = sPhoneNo; } else { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = false; pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = false; pnlWHPhone3.Visible = false; pnlWHPhone4.Visible = false; pnlWHPhone5.Visible = false; txtPhone1.Text = sPhoneNo; txtWHPhone1.Text = sPhoneNo; } break; } case 2: { if (sPhoneType.ToLower() == "company") { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneTwo.BringToFront(); pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone2.Text = sPhoneNo; } else if (sPhoneType.ToLower() == "wh") { pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = true; pnlWHPhone2.BringToFront(); pnlWHPhone3.Visible = false; pnlWHPhone4.Visible = false; pnlWHPhone5.Visible = false; txtWHPhone2.Text = sPhoneNo; } else { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneTwo.BringToFront(); pnlPhoneThree.Visible = false; pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = true; pnlWHPhone2.BringToFront(); pnlWHPhone3.Visible = false; pnlWHPhone4.Visible = false; pnlWHPhone5.Visible = false; txtPhone2.Text = sPhoneNo; txtWHPhone2.Text = sPhoneNo; } break; } case 3: { if (sPhoneType.ToLower() == "company") { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneThree.BringToFront(); pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; txtPhone3.Text = sPhoneNo; } else if (sPhoneType.ToLower() == "wh") { pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = true; pnlWHPhone3.Visible = true; pnlWHPhone3.BringToFront(); pnlWHPhone4.Visible = false; pnlWHPhone5.Visible = false; txtWHPhone3.Text = sPhoneNo; } else { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneThree.BringToFront(); pnlPhoneFour.Visible = false; pnlPhoneFive.Visible = false; pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = true; pnlWHPhone3.Visible = true; pnlWHPhone3.BringToFront(); pnlWHPhone4.Visible = false; pnlWHPhone5.Visible = false; txtPhone3.Text = sPhoneNo; txtWHPhone3.Text = sPhoneNo; } break; } case 4: { if (sPhoneType.ToLower() == "company") { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFour.BringToFront(); pnlPhoneFive.Visible = false; txtPhone4.Text = sPhoneNo; } else if (sPhoneType.ToLower() == "wh") { pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = true; pnlWHPhone3.Visible = true; pnlWHPhone4.Visible = true; pnlWHPhone4.BringToFront(); pnlWHPhone5.Visible = false; txtWHPhone4.Text = sPhoneNo; } else { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFour.BringToFront(); pnlPhoneFive.Visible = false; pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = true; pnlWHPhone3.Visible = true; pnlWHPhone4.Visible = true; pnlWHPhone4.BringToFront(); pnlWHPhone5.Visible = false; txtPhone4.Text = sPhoneNo; txtWHPhone4.Text = sPhoneNo; } break; } case 5: { if (sPhoneType.ToLower() == "company") { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFive.Visible = true; pnlPhoneFive.BringToFront(); txtPhone5.Text = sPhoneNo; } else if (sPhoneType.ToLower() == "wh") { pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = true; pnlWHPhone3.Visible = true; pnlWHPhone4.Visible = true; pnlWHPhone5.Visible = true; pnlWHPhone5.BringToFront(); txtWHPhone5.Text = sPhoneNo; } else { pnlPhoneOne.Visible = true; pnlPhoneTwo.Visible = true; pnlPhoneThree.Visible = true; pnlPhoneFour.Visible = true; pnlPhoneFive.Visible = true; pnlPhoneFive.BringToFront(); pnlWHPhone1.Visible = true; pnlWHPhone2.Visible = true; pnlWHPhone3.Visible = true; pnlWHPhone4.Visible = true; pnlWHPhone5.Visible = true; pnlWHPhone5.BringToFront(); txtPhone5.Text = sPhoneNo; txtWHPhone5.Text = sPhoneNo; } break; } } } private void ShowHideSignWHPanel(string sPanelType = "", Int64 nID = 0, int PhoneCount = 1) { switch (PhoneCount) { case 1: { if (sPanelType.ToLower() == "sign") { pnlCompSign1.Visible = true; pnlCompSign2.Visible = false; pnlCompSign3.Visible = false; cmbCompanySignatory1.SelectedValue = nID; } else if (sPanelType.ToLower() == "wh") { pnlWHSupervisor1.Visible = true; pnlWHSupervisor2.Visible = false; pnlWHSupervisor3.Visible = false; cmbWarehouseSupervisor1.SelectedValue = nID; } else { pnlCompSign1.Visible = true; pnlCompSign2.Visible = false; pnlCompSign3.Visible = false; pnlWHSupervisor1.Visible = true; pnlWHSupervisor2.Visible = false; pnlWHSupervisor3.Visible = false; cmbCompanySignatory1.SelectedValue = nID; cmbWarehouseSupervisor1.SelectedValue = nID; } break; } case 2: { if (sPanelType.ToLower() == "sign") { pnlCompSign1.Visible = true; pnlCompSign2.Visible = true; pnlCompSign2.BringToFront(); pnlCompSign3.Visible = false; cmbCompanySignatory2.SelectedValue = nID; } else if (sPanelType.ToLower() == "wh") { pnlWHSupervisor1.Visible = true; pnlWHSupervisor2.Visible = true; pnlWHSupervisor2.BringToFront(); pnlWHSupervisor3.Visible = false; cmbWarehouseSupervisor2.SelectedValue = nID; } else { pnlCompSign1.Visible = true; pnlCompSign2.Visible = true; pnlCompSign2.BringToFront(); pnlCompSign3.Visible = false; pnlWHSupervisor1.Visible = true; pnlWHSupervisor2.Visible = true; pnlWHSupervisor2.BringToFront(); pnlWHSupervisor3.Visible = false; cmbCompanySignatory2.SelectedValue = nID; cmbWarehouseSupervisor2.SelectedValue = nID; } break; } case 3: { if (sPanelType.ToLower() == "sign") { pnlCompSign1.Visible = true; pnlCompSign2.Visible = true; pnlCompSign3.Visible = true; pnlCompSign3.BringToFront(); cmbCompanySignatory3.SelectedValue = nID; } else if (sPanelType.ToLower() == "wh") { pnlWHSupervisor1.Visible = true; pnlWHSupervisor2.Visible = true; pnlWHSupervisor3.Visible = true; pnlWHSupervisor3.BringToFront(); cmbWarehouseSupervisor3.SelectedValue = nID; } else { pnlCompSign1.Visible = true; pnlCompSign2.Visible = true; pnlCompSign3.Visible = true; pnlCompSign3.BringToFront(); pnlWHSupervisor1.Visible = true; pnlWHSupervisor2.Visible = true; pnlWHSupervisor3.Visible = true; pnlWHSupervisor3.BringToFront(); cmbCompanySignatory3.SelectedValue = nID; cmbWarehouseSupervisor3.SelectedValue = nID; } break; } } } private void fillMasterData() { txtCountry.Text = "India"; txtCity.Text = "Mumbai"; txtState.Text = "Maharashtra"; txtWHCountry.Text = "India"; txtWHCity.Text = "Mumbai"; txtWHState.Text = "Maharashtra"; clsGeneral oclsGeneral = null; try { oclsGeneral = new clsGeneral(); DataSet dsCompanyMaster = oclsGeneral.GetCompanyMaster(); if (dsCompanyMaster != null && dsCompanyMaster.Tables.Count > 0) { DataTable dtCompanyType = dsCompanyMaster.Tables[0]; //DataTable dtStateMaster = dsCompanyMaster.Tables[1]; //DataTable dtCityMaster = dsCompanyMaster.Tables[2]; //DataTable dtCountryMaster = dsCompanyMaster.Tables[3]; DataRow drCompanyType = dtCompanyType.NewRow(); drCompanyType["nCompanyTypeID"] = "0"; drCompanyType["sCompanyTypeName"] = ""; dtCompanyType.Rows.InsertAt(drCompanyType, 0); cmbCompanyType.DataSource = dtCompanyType; cmbCompanyType.DisplayMember = "sCompanyTypeName"; cmbCompanyType.ValueMember = "nCompanyTypeID"; //cmbCompStateMaster.DataSource = dtStateMaster; //cmbCompStateMaster.DisplayMember = "StateName"; //cmbCompStateMaster.ValueMember = "StateName"; //cmbCompStateMaster.Text = "Maharashtra"; //cmbCompCityMaster.DataSource = dtCityMaster; //cmbCompCityMaster.DisplayMember = "CityName"; //cmbCompCityMaster.ValueMember = "CityName"; //cmbCompCityMaster.Text = "Mumbai"; //cmbCompCountryMaster.DataSource = dtCountryMaster; //cmbCompCountryMaster.DisplayMember = "sCountryName"; //cmbCompCountryMaster.ValueMember = "sCountryName"; //cmbCompCountryMaster.Text = "India"; //cmbWHCState.DataSource = dtStateMaster.Copy(); //cmbWHCState.DisplayMember = "StateName"; //cmbWHCState.ValueMember = "StateName"; //cmbWHCState.Text = "Maharashtra"; //cmbWHCity.DataSource = dtCityMaster.Copy(); //cmbWHCity.DisplayMember = "CityName"; //cmbWHCity.ValueMember = "CityName"; //cmbWHCity.Text = "Mumbai"; //cmbWHCountry.DataSource = dtCountryMaster.Copy(); //cmbWHCountry.DisplayMember = "sCountryName"; //cmbWHCountry.ValueMember = "sCountryName"; //cmbWHCountry.Text = "India"; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } } } private void GetAndSetSequence() { clsGeneral oclsGeneral = null; try { oclsGeneral = new clsGeneral(); txtCompanyCode.Text = "CMP/" + Convert.ToString(oclsGeneral.GetSequenceNumber(MainMasterType.Company.GetHashCode())); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } } } private void btnAddCompanyPhone_Click(object sender, EventArgs e) { int nCompanyPhoneCount = CheckPanelVisibility("Company"); if (nCompanyPhoneCount <= 5) { ShowHidePhonePanel("Company", "", nCompanyPhoneCount); } } private int CheckPanelVisibility(string sCheckPanelFor) { int nPanelCount = 0; switch (sCheckPanelFor) { case "Company": { if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == false && pnlPhoneThree.Visible == false && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 2; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == false && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 3; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == false && pnlPhoneFive.Visible == false) { nPanelCount = 4; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == true && pnlPhoneFive.Visible == false) { nPanelCount = 5; } else if (pnlPhoneOne.Visible == true && pnlPhoneTwo.Visible == true && pnlPhoneThree.Visible == true && pnlPhoneFour.Visible == true && pnlPhoneFive.Visible == false) { nPanelCount = 6; } break; } case "WH": { if (pnlWHPhone1.Visible == true && pnlWHPhone2.Visible == false && pnlWHPhone3.Visible == false && pnlWHPhone4.Visible == false && pnlWHPhone5.Visible == false) { nPanelCount = 2; } else if (pnlWHPhone1.Visible == true && pnlWHPhone2.Visible == true && pnlWHPhone3.Visible == false && pnlWHPhone4.Visible == false && pnlWHPhone5.Visible == false) { nPanelCount = 3; } else if (pnlWHPhone1.Visible == true && pnlWHPhone2.Visible == true && pnlWHPhone3.Visible == true && pnlWHPhone4.Visible == false && pnlWHPhone5.Visible == false) { nPanelCount = 4; } else if (pnlWHPhone1.Visible == true && pnlWHPhone2.Visible == true && pnlWHPhone3.Visible == true && pnlWHPhone4.Visible == true && pnlWHPhone5.Visible == false) { nPanelCount = 5; } else if (pnlWHPhone1.Visible == true && pnlWHPhone2.Visible == true && pnlWHPhone3.Visible == true && pnlWHPhone4.Visible == true && pnlWHPhone5.Visible == false) { nPanelCount = 6; } break; } } return nPanelCount; } private int CheckPanelSignWHVisibility(string sCheckPanelFor) { int nPanelCount = 0; switch (sCheckPanelFor) { case "Sign": { if (pnlCompSign1.Visible == true && pnlCompSign2.Visible == false && pnlCompSign3.Visible == false) { nPanelCount = 2; } else if (pnlCompSign1.Visible == true && pnlCompSign2.Visible == true && pnlCompSign3.Visible == false) { nPanelCount = 3; } else if (pnlCompSign1.Visible == true && pnlCompSign2.Visible == true && pnlCompSign3.Visible == true) { nPanelCount = 4; } break; } case "WH": { if (pnlWHSupervisor1.Visible == true && pnlWHSupervisor2.Visible == false && pnlWHSupervisor3.Visible == false) { nPanelCount = 2; } else if (pnlWHSupervisor1.Visible == true && pnlWHSupervisor2.Visible == true && pnlWHSupervisor3.Visible == false) { nPanelCount = 3; } else if (pnlWHSupervisor1.Visible == true && pnlWHSupervisor2.Visible == true && pnlWHSupervisor3.Visible == true) { nPanelCount = 4; } break; } } return nPanelCount; } private void btnWHAddPhone_Click(object sender, EventArgs e) { int nWHPhoneCount = CheckPanelVisibility("WH"); if (nWHPhoneCount <= 5) { ShowHidePhonePanel("WH", "", nWHPhoneCount); } } private void rdImageFormat_CheckedChanged(object sender, EventArgs e) { FillTermsCondition(); } private void rdTextFormat_CheckedChanged(object sender, EventArgs e) { FillTermsCondition(); } private void FillTermsCondition() { if (rdImageFormat.Checked) { pnlTermsImage.Visible = true; pnlTermsImage.BringToFront(); pnlTermsText.Visible = false; } else { pnlTermsText.Visible = true; pnlTermsText.BringToFront(); pnlTermsImage.Visible = false; } } private void frmMasterAddCompany_Load(object sender, EventArgs e) { rdImageFormat.Checked = true; dtCompanyFormedOn.EditValue = DateTime.Now; txtDocumentDate.EditValue = DateTime.Now; FillSignatoryInfo(); FillWarehouseSuperintendentInfo(); if (Convert.ToInt64(lblCompanyID.Text) > 0) { FillCompanyDetails(Convert.ToInt64(lblCompanyID.Text)); } //clsGlobal.SetDateFormat(dtCompanyFormedOn); } private void FillCompanyDetails(Int64 nCompanyID) { CompanyMaster clsCompanyMaster = null; DataSet ds = null; DataTable dtCompDetails = null; DataTable dtCompTransDetails = null; DataTable dtCompWHDetails = null; DataTable dtCompImageDetails = null; try { clsCompanyMaster = new CompanyMaster(); ds = clsCompanyMaster.GetCompanyInformation(nCompanyID); if (ds != null && ds.Tables.Count > 0) { dtCompDetails = ds.Tables[0]; dtCompTransDetails = ds.Tables[1]; dtCompWHDetails = ds.Tables[2]; dtCompImageDetails = ds.Tables[3]; if (dtCompDetails != null && dtCompDetails.Rows.Count > 0) { lblCompanyID.Text = Convert.ToString(dtCompDetails.Rows[0]["nCompanyID"]); lblCompanyInfoImageID.Text = Convert.ToString(dtCompDetails.Rows[0]["nCompanyImageInfoID"]); lblCompanyTransportID.Text = Convert.ToString(dtCompDetails.Rows[0]["nCompanyTransporterID"]); lblCompWarehouseID.Text = Convert.ToString(dtCompDetails.Rows[0]["nCompanyWarehouseID"]); txtCompanyCode.Text = Convert.ToString(dtCompDetails.Rows[0]["sCompanyCode"]); txtCompanyAbbrivation.Text = Convert.ToString(dtCompDetails.Rows[0]["sCompAbbrivation"]); txtCompanyName.Text = Convert.ToString(dtCompDetails.Rows[0]["sCompanyName"]); cmbCompanyType.SelectedValue = Convert.ToInt64(dtCompDetails.Rows[0]["nCompanyTypeID"]); //cmbCompanySignatory1.SelectedValue = Convert.ToInt64(dtCompDetails.Rows[0]["nCompanySignatory"]); txtAddressLine1.Text = Convert.ToString(dtCompDetails.Rows[0]["sAddressLine1"]); txtAddressLine2.Text = Convert.ToString(dtCompDetails.Rows[0]["sAddressLine2"]); txtCity.Text = Convert.ToString(dtCompDetails.Rows[0]["sCity"]); txtState.Text = Convert.ToString(dtCompDetails.Rows[0]["sState"]); txtCountry.Text = Convert.ToString(dtCompDetails.Rows[0]["sCountry"]); txtPincode.Text = Convert.ToString(dtCompDetails.Rows[0]["sPincode"]); txtEmail.Text = Convert.ToString(dtCompDetails.Rows[0]["sEmail"]); txtWebsiteURL.Text = Convert.ToString(dtCompDetails.Rows[0]["sWebsite"]); txtFaxNo.Text = Convert.ToString(dtCompDetails.Rows[0]["sFax"]); txtHSN_SAVCode.Text = Convert.ToString(dtCompDetails.Rows[0]["sHSN_SACCode"]); txtGSTNo.Text = Convert.ToString(dtCompDetails.Rows[0]["sGSTNO"]); txtPANNo.Text = Convert.ToString(dtCompDetails.Rows[0]["sPANNO"]); dtCompanyFormedOn.EditValue = Convert.ToDateTime(dtCompDetails.Rows[0]["dtCompanyFormedOn"]); string[] sPhoneAll = Convert.ToString(dtCompDetails.Rows[0]["sPhoneNo"]).Split(','); if (sPhoneAll.Length > 0) { int nCompPanelCount = GetPanelCount(sPhoneAll.Length); for (int i = 0; i < nCompPanelCount; i++) { ShowHidePhonePanel("Company", sPhoneAll[i], i + 1); } } string[] sSignatoryAll = Convert.ToString(dtCompDetails.Rows[0]["sCompanySignatory"]).Split(','); if (sSignatoryAll.Length > 0) { int nCompPanelCount = GetPanelCount(sSignatoryAll.Length); for (int i = 0; i < nCompPanelCount; i++) { ShowHideSignWHPanel("Sign", Convert.ToInt64(sSignatoryAll[i]), i + 1); } } } if (dtCompTransDetails != null && dtCompTransDetails.Rows.Count > 0) { txtTransporterID.Text = Convert.ToString(dtCompTransDetails.Rows[0]["sTransportorID"]); txtDocumentName.Text = Convert.ToString(dtCompTransDetails.Rows[0]["sDoumentName"]); txtDocumentNumber.Text = Convert.ToString(dtCompTransDetails.Rows[0]["sDoumentNumber"]); txtDocumentDate.EditValue = Convert.ToDateTime(dtCompTransDetails.Rows[0]["sDocumentDate"]); } if (dtCompWHDetails != null && dtCompWHDetails.Rows.Count > 0) { txtWHAddressLine1.Text = Convert.ToString(dtCompWHDetails.Rows[0]["sWarehouseAddressLine1"]); txtWHAddressLine2.Text = Convert.ToString(dtCompWHDetails.Rows[0]["sWarehouseAddressLine2"]); txtWHCity.Text = Convert.ToString(dtCompWHDetails.Rows[0]["sCity"]); txtWHState.Text = Convert.ToString(dtCompWHDetails.Rows[0]["sState"]); txtWHCountry.Text = Convert.ToString(dtCompWHDetails.Rows[0]["sCountry"]); txtWHPincode.Text = Convert.ToString(dtCompWHDetails.Rows[0]["sPincode"]); //cmbWarehouseSupervisor1.SelectedValue = Convert.ToInt64(dtCompWHDetails.Rows[0]["nSupervisorID"]); string[] sWHPhoneAll = Convert.ToString(dtCompWHDetails.Rows[0]["sPhoneNo"]).Split(','); if (sWHPhoneAll.Length > 0) { int nPanelCount = GetPanelCount(sWHPhoneAll.Length); for (int i = 0; i < nPanelCount; i++) { ShowHidePhonePanel("WH", sWHPhoneAll[i], i + 1); } } string[] sSupervisorAll = Convert.ToString(dtCompWHDetails.Rows[0]["nSupervisorID"]).Split(','); if (sSupervisorAll.Length > 0) { int nCompPanelCount = GetPanelCount(sSupervisorAll.Length); for (int i = 0; i < nCompPanelCount; i++) { ShowHideSignWHPanel("WH", Convert.ToInt64(sSupervisorAll[i]), i + 1); } } } if (dtCompImageDetails != null && dtCompImageDetails.Rows.Count > 0) { byte[] HeaderImage = null; byte[] FooterImage = null; byte[] Terms_CondImage = null; string sTermsAndCondition = string.Empty; if (dtCompImageDetails.Rows[0]["imgHeaderAddress"] != DBNull.Value) { HeaderImage = (byte[])dtCompImageDetails.Rows[0]["imgHeaderAddress"]; MemoryStream msHeaderImage = new MemoryStream(HeaderImage); picHeaderImage.Image = Image.FromStream(msHeaderImage); } if (dtCompImageDetails.Rows[0]["imgFooterAddress"] != DBNull.Value) { FooterImage = (byte[])dtCompImageDetails.Rows[0]["imgFooterAddress"]; MemoryStream msFooterImage = new MemoryStream(FooterImage); picFooterImage.Image = Image.FromStream(msFooterImage); } if (Convert.ToInt32(dtCompImageDetails.Rows[0]["nTermsAndConditionType"]) == 0) { rdImageFormat.Checked = true; if (dtCompImageDetails.Rows[0]["imgTermsAndCondition"] != DBNull.Value) { Terms_CondImage = (byte[])dtCompImageDetails.Rows[0]["imgTermsAndCondition"]; MemoryStream msTerms_CondImage = new MemoryStream(Terms_CondImage); picFooterImage.Image = Image.FromStream(msTerms_CondImage); } } else if (Convert.ToInt32(dtCompImageDetails.Rows[0]["nTermsAndConditionType"]) == 1) { rdTextFormat.Checked = true; sTermsAndCondition = Convert.ToString(dtCompImageDetails.Rows[0]["sTermsAndCondition"]); txtTermsCondition.Text = sTermsAndCondition; } } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private int GetPanelCount(int nStringLength) { int nPanelCount = 0; if (nStringLength <= 5) { switch (nStringLength) { case 1: nPanelCount = 1; break; case 2: nPanelCount = 2; break; case 3: nPanelCount = 3; break; case 4: nPanelCount = 4; break; case 5: nPanelCount = 5; break; } } return nPanelCount; } public Int64 SaveCompanyDetails() { Int64 nresult = 0; CompanyMaster clsCompanyMaster = null; try { string sPhone1 = Convert.ToString(txtPhone1.Text.Trim()); string sPhone2 = Convert.ToString(txtPhone2.Text.Trim()); string sPhone3 = Convert.ToString(txtPhone3.Text.Trim()); string sPhone4 = Convert.ToString(txtPhone4.Text.Trim()); string sPhone5 = Convert.ToString(txtPhone5.Text.Trim()); string sPhoneAll = string.Empty; if (sPhone1 != "") { sPhoneAll += sPhone1; } if (sPhone2 != "") { sPhoneAll += "," + sPhone2; } if (sPhone3 != "") { sPhoneAll += "," + sPhone3; } if (sPhone4 != "") { sPhoneAll += "," + sPhone4; } if (sPhone5 != "") { sPhoneAll += "," + sPhone5; } string sWHPhone1 = Convert.ToString(txtWHPhone1.Text.Trim()); string sWHPhone2 = Convert.ToString(txtWHPhone2.Text.Trim()); string sWHPhone3 = Convert.ToString(txtWHPhone3.Text.Trim()); string sWHPhone4 = Convert.ToString(txtWHPhone4.Text.Trim()); string sWHPhone5 = Convert.ToString(txtWHPhone5.Text.Trim()); string sWHPhoneAll = string.Empty; if (sWHPhone1 != "") { sWHPhoneAll += sWHPhone1; } if (sWHPhone2 != "") { sWHPhoneAll += "," + sWHPhone2; } if (sWHPhone3 != "") { sWHPhoneAll += "," + sWHPhone3; } if (sWHPhone4 != "") { sWHPhoneAll += "," + sWHPhone4; } if (sWHPhone5 != "") { sWHPhoneAll += "," + sWHPhone5; } string sCompSign1 = Convert.ToString(cmbCompanySignatory1.SelectedValue); string sCompSign2 = Convert.ToString(cmbCompanySignatory2.SelectedValue); string sCompSign3 = Convert.ToString(cmbCompanySignatory3.SelectedValue); string sCompSign = string.Empty; if (sCompSign1 != "0") { sCompSign += sCompSign1; } if (sCompSign2 != "0") { sCompSign += "," + sCompSign2; } if (sCompSign3 != "0") { sCompSign += "," + sCompSign3; } string sWHSupervisor1 = Convert.ToString(cmbWarehouseSupervisor1.SelectedValue); string sWHSupervisor2 = Convert.ToString(cmbWarehouseSupervisor2.SelectedValue); string sWHSupervisor3 = Convert.ToString(cmbWarehouseSupervisor3.SelectedValue); string sWHSupervisor = string.Empty; if (sWHSupervisor1 != "0") { sWHSupervisor += sWHSupervisor1; } if (sWHSupervisor2 != "0") { sWHSupervisor += "," + sWHSupervisor2; } if (sWHSupervisor3 != "0") { sWHSupervisor += "," + sWHSupervisor3; } clsCompanyMaster = new CompanyMaster(); clsCompanyMaster.nCompanyID = Convert.ToInt64(lblCompanyID.Text); clsCompanyMaster.nCompTransportID = Convert.ToInt64(lblCompanyTransportID.Text); clsCompanyMaster.nCompWarehouseID = Convert.ToInt64(lblCompWarehouseID.Text); clsCompanyMaster.nCompImageID = Convert.ToInt64(lblCompanyInfoImageID.Text); clsCompanyMaster.sCompanyCode = Convert.ToString(txtCompanyCode.Text.Trim()); clsCompanyMaster.sCompanyName = Convert.ToString(txtCompanyName.Text.Trim()); clsCompanyMaster.sCompAbbrivation = Convert.ToString(txtCompanyAbbrivation.Text.Trim()); clsCompanyMaster.nCompanyTypeID = Convert.ToInt64(cmbCompanyType.SelectedValue); clsCompanyMaster.sCompSignatoryID = sCompSign == "" ? "0" : sCompSign; clsCompanyMaster.sCompAddressLine1 = Convert.ToString(txtAddressLine1.Text.Trim()); clsCompanyMaster.sCompAddressLine2 = Convert.ToString(txtAddressLine2.Text.Trim()); clsCompanyMaster.sCompCity = Convert.ToString(txtCity.Text.Trim()); clsCompanyMaster.sCompState = Convert.ToString(txtState.Text.Trim()); clsCompanyMaster.sCompCountry = Convert.ToString(txtCountry.Text.Trim()); clsCompanyMaster.sCompPincode = Convert.ToString(txtPincode.Text.Trim()); clsCompanyMaster.sCompEmail = Convert.ToString(txtEmail.Text.Trim()); clsCompanyMaster.sCompWebsite = Convert.ToString(txtWebsiteURL.Text.Trim()); clsCompanyMaster.sCompFax = Convert.ToString(txtFaxNo.Text.Trim()); clsCompanyMaster.sCompHSN_SACCode = Convert.ToString(txtHSN_SAVCode.Text.Trim()); clsCompanyMaster.sCompGSTNo = Convert.ToString(txtGSTNo.Text.Trim()); clsCompanyMaster.sCompPANNo = Convert.ToString(txtPANNo.Text.Trim()); clsCompanyMaster.dtCompanyFormedDate = Convert.ToDateTime(dtCompanyFormedOn.Text.Trim()); clsCompanyMaster.sCompAllPhoneNo = sPhoneAll; clsCompanyMaster.sTransporterID = Convert.ToString(txtTransporterID.Text.Trim()); clsCompanyMaster.sTransDocumentDate = Convert.ToDateTime(txtDocumentDate.Text.Trim()); clsCompanyMaster.sTransDocumentName = Convert.ToString(txtDocumentName.Text.Trim()); clsCompanyMaster.sTransDocumentNumber = Convert.ToString(txtDocumentNumber.Text.Trim()); clsCompanyMaster.sWHAddressLine1 = Convert.ToString(txtWHAddressLine1.Text.Trim()); clsCompanyMaster.sWHAddressLine2 = Convert.ToString(txtWHAddressLine2.Text.Trim()); clsCompanyMaster.sWHCity = Convert.ToString(txtCity.Text.Trim()); clsCompanyMaster.sWHState = Convert.ToString(txtState.Text.Trim()); clsCompanyMaster.sWHCountry = Convert.ToString(txtCountry.Text.Trim()); clsCompanyMaster.sWHPincode = Convert.ToString(txtWHPincode.Text.Trim()); clsCompanyMaster.nWHSupervisorID = sWHSupervisor==""?"0":sWHSupervisor; clsCompanyMaster.sWHAllPhoneNo = sWHPhoneAll; byte[] HeaderImage = null; byte[] FooterImage = null; byte[] Terms_CondImage = null; string sTermsAndCondition = string.Empty; if (picHeaderImage.Image != null) { using (MemoryStream ms = new MemoryStream()) { picHeaderImage.Image.Save(ms, ImageFormat.Jpeg); HeaderImage = new byte[ms.Length]; ms.Position = 0; ms.Read(HeaderImage, 0, HeaderImage.Length); } } if (picFooterImage.Image != null) { using (MemoryStream ms = new MemoryStream()) { picFooterImage.Image.Save(ms, ImageFormat.Jpeg); FooterImage = new byte[ms.Length]; ms.Position = 0; ms.Read(FooterImage, 0, FooterImage.Length); } } if (rdImageFormat.Checked && picTermsCondition.Image != null) { using (MemoryStream ms = new MemoryStream()) { picFooterImage.Image.Save(ms, ImageFormat.Jpeg); Terms_CondImage = new byte[ms.Length]; ms.Position = 0; ms.Read(Terms_CondImage, 0, Terms_CondImage.Length); } } else if (rdTextFormat.Checked) { sTermsAndCondition = txtTermsCondition.Text.Trim(); } clsCompanyMaster.imgCompHeader = HeaderImage; clsCompanyMaster.imgCompFooter = FooterImage; clsCompanyMaster.imgTerms_Condition = Terms_CondImage; if (rdImageFormat.Checked) { clsCompanyMaster.nTerms_ConditionType = 0; } else { clsCompanyMaster.nTerms_ConditionType = 1; } clsCompanyMaster.sTerms_Condition = sTermsAndCondition; Int64 nCompanyID = clsCompanyMaster.InsertUpdateCompanyMaster(); if (nCompanyID != 0) { MessageBox.Show("Company is saved successfully.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); ClearForm(); } else { MessageBox.Show("Error while saving company.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } return nresult; } private void btnSave_Click(object sender, EventArgs e) { if (ValidateForm()) { SaveCompanyDetails(); } } public bool ValidateForm() { bool bIsValidForm = true; if (txtCompanyName.Text.Trim() == "") { MessageBox.Show("Please enter company name.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; txtCompanyName.Focus(); return bIsValidForm; } if (cmbCompanyType.Text.Trim() == "") { MessageBox.Show("Please enter company type.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); bIsValidForm = false; cmbCompanyType.Focus(); return bIsValidForm; } return bIsValidForm; } private void txtCompanyName_EditValueChanged(object sender, EventArgs e) { txtCompanyAbbrivation.Text = clsGlobal.GenerateAbbrivation(txtCompanyName.Text.Trim()); } private void btnAddCompanySignatory_Click(object sender, EventArgs e) { int nCompanyPhoneCount = CheckPanelSignWHVisibility("Sign"); if (nCompanyPhoneCount <= 3) { ShowHideSignWHPanel("Sign", 0, nCompanyPhoneCount); } return; clsMasters clsMaster = null; try { clsMaster = new clsMasters(); Int64 nSignatoryID = 0; DataTable dtMaster = clsMaster.GetMasterTypeDataBbValue(MasterType.Designation.GetHashCode(), "Signatory"); if (dtMaster != null && dtMaster.Rows.Count > 0) { nSignatoryID = Convert.ToInt64(dtMaster.Rows[0]["TypeID"]); } frmMasterAddCrew frmMasterCrew = new frmMasterAddCrew(); frmMasterCrew.nSignatoryID = nSignatoryID; frmMasterCrew.ShowDialog(this); FillSignatoryInfo(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void FillSignatoryInfo() { CompanyMaster oCompanyMaster = null; DataTable dt = null; try { oCompanyMaster = new CompanyMaster(); dt = oCompanyMaster.GetListData("signatory"); if (dt != null) { DataRow dr = dt.NewRow(); dr["ID"] = 0; dr["Code"] = ""; dt.Rows.InsertAt(dr, 0); cmbCompanySignatory1.DataSource = dt; cmbCompanySignatory1.DisplayMember = "Code"; cmbCompanySignatory1.ValueMember = "ID"; cmbCompanySignatory2.DataSource = dt.Copy(); cmbCompanySignatory2.DisplayMember = "Code"; cmbCompanySignatory2.ValueMember = "ID"; cmbCompanySignatory3.DataSource = dt.Copy(); cmbCompanySignatory3.DisplayMember = "Code"; cmbCompanySignatory3.ValueMember = "ID"; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oCompanyMaster != null) { oCompanyMaster.Dispose(); oCompanyMaster = null; } } } private void FillWarehouseSuperintendentInfo() { CompanyMaster oCompanyMaster = null; DataTable dt = null; try { oCompanyMaster = new CompanyMaster(); dt = oCompanyMaster.GetListData("Warehouse Superintendent"); if (dt != null) { DataRow dr = dt.NewRow(); dr["ID"] = 0; dr["Code"] = ""; dt.Rows.InsertAt(dr, 0); cmbWarehouseSupervisor1.DataSource = dt; cmbWarehouseSupervisor1.DisplayMember = "Code"; cmbWarehouseSupervisor1.ValueMember = "ID"; cmbWarehouseSupervisor2.DataSource = dt.Copy(); cmbWarehouseSupervisor2.DisplayMember = "Code"; cmbWarehouseSupervisor2.ValueMember = "ID"; cmbWarehouseSupervisor3.DataSource = dt.Copy(); cmbWarehouseSupervisor3.DisplayMember = "Code"; cmbWarehouseSupervisor3.ValueMember = "ID"; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oCompanyMaster != null) { oCompanyMaster.Dispose(); oCompanyMaster = null; } } } private void ClearForm() { txtCompanyAbbrivation.Text = string.Empty; txtCompanyName.Text = string.Empty; cmbCompanyType.SelectedValue = 0; txtAddressLine1.Text = string.Empty; txtAddressLine2.Text = string.Empty; txtCity.Text = "Mumbai"; txtState.Text = "Maharashtra"; txtCountry.Text = "India"; txtPincode.Text = string.Empty; txtEmail.Text = string.Empty; txtWebsiteURL.Text = string.Empty; txtFaxNo.Text = string.Empty; txtHSN_SAVCode.Text = string.Empty; txtGSTNo.Text = string.Empty; txtPANNo.Text = string.Empty; dtCompanyFormedOn.EditValue = DateTime.Now; txtPhone1.Text = string.Empty; txtPhone2.Text = string.Empty; txtPhone3.Text = string.Empty; txtPhone4.Text = string.Empty; txtPhone5.Text = string.Empty; txtTransporterID.Text = string.Empty; txtDocumentName.Text = string.Empty; txtDocumentNumber.Text = string.Empty; txtDocumentDate.EditValue = DateTime.Now; txtWHAddressLine1.Text = string.Empty; txtWHAddressLine2.Text = string.Empty; txtWHCity.Text = "Mumbai"; txtWHState.Text = "Maharashtra"; txtWHCountry.Text = "India"; txtWHPincode.Text = string.Empty; txtWHPhone1.Text = string.Empty; txtWHPhone2.Text = string.Empty; txtWHPhone3.Text = string.Empty; txtWHPhone4.Text = string.Empty; txtWHPhone5.Text = string.Empty; GetAndSetSequence(); cmbCompanySignatory1.SelectedValue = 0; cmbCompanySignatory2.SelectedValue = 0; cmbCompanySignatory3.SelectedValue = 0; cmbWarehouseSupervisor1.SelectedValue = 0; cmbWarehouseSupervisor2.SelectedValue = 0; cmbWarehouseSupervisor3.SelectedValue = 0; rdImageFormat.Checked = true; if (picFooterImage != null) { picFooterImage.Image = null; } if (picHeaderImage != null) { picHeaderImage.Image = null; } if (picTermsCondition != null) { picTermsCondition.Image = null; } if (txtTermsCondition.Text != "") { txtTermsCondition.Text = ""; } } private void btnWHAddSupervisor_Click(object sender, EventArgs e) { int nCompanyPhoneCount = CheckPanelSignWHVisibility("WH"); if (nCompanyPhoneCount <= 3) { ShowHideSignWHPanel("WH", 0, nCompanyPhoneCount); } return; clsMasters clsMaster = null; try { clsMaster = new clsMasters(); Int64 nSignatoryID = 0; DataTable dtMaster = clsMaster.GetMasterTypeDataBbValue(MasterType.Designation.GetHashCode(), "Warehouse Superintendent"); if (dtMaster != null && dtMaster.Rows.Count > 0) { nSignatoryID = Convert.ToInt64(dtMaster.Rows[0]["TypeID"]); } frmMasterAddCrew frmMasterCrew = new frmMasterAddCrew(); frmMasterCrew.nSignatoryID = nSignatoryID; frmMasterCrew.ShowDialog(this); FillWarehouseSuperintendentInfo(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmAddAsset : DevExpress.XtraEditors.XtraForm { public frmAddAsset() { InitializeComponent(); } public frmAddAsset(long nAssetID) { InitializeComponent(); // TODO: Complete member initialization lblAssetID.Text= Convert.ToString(nAssetID); } DataTable dtAssetCode = new DataTable(); private long nAssetID; private void frmAddAsset_Load(object sender, EventArgs e) { try { txtAssetName.Focus(); dtIntroductionDate.EditValueChanged-=dtIntroductionDate_EditValueChanged; dtIntroductionDate.EditValue = DateTime.Now; dtReorderTime.EditValue = DateTime.Now; dtIntroductionDate.EditValueChanged += dtIntroductionDate_EditValueChanged; dtShelfLife.EditValue = DateTime.Now; dtRetirementDate.EditValue = DateTime.Now; FillAssetMaster(); //FillAssetCode(); if (Convert.ToInt64(lblAssetID.Text) != 0) { //pnlSave.Visible = false; btnSave.Text = "Update"; FillAssetDetails(Convert.ToInt64(lblAssetID.Text)); EnableDisableCodeControl(Convert.ToInt64(lblAssetID.Text)); } //clsTabIndex.TabScheme scheme = clsTabIndex.TabScheme.AcrossFirst; //clsTabIndex tom = new clsTabIndex(this); //// This method actually sets the order all the way down the control hierarchy. //tom.SetTabOrder(scheme); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void FillAssetDetails(long nAssetID) { AssetMaster oAssetMaster = null; DataSet ds = null; try { oAssetMaster = new AssetMaster(); ds= oAssetMaster.GetAssetDetails(nAssetID); if (ds!=null && ds.Tables.Count>0) { DataTable dtAssetDetails = ds.Tables[0]; DataTable dtAssetCodeDetails = ds.Tables[1]; if (dtAssetDetails!=null && dtAssetDetails.Rows.Count>0) { lblAssetID.Text = Convert.ToString(dtAssetDetails.Rows[0]["nAssetID"]); cmbCompanyMst.SelectedValue = Convert.ToInt64(dtAssetDetails.Rows[0]["nCompanyID"]); cmbMainType.SelectedValue = Convert.ToInt64(dtAssetDetails.Rows[0]["nAssetMainTypeID"]); cmbType.SelectedValue = Convert.ToInt64(dtAssetDetails.Rows[0]["nAssetTypeID"]); cmbType1.SelectedValue = Convert.ToInt64(dtAssetDetails.Rows[0]["nAssetTypeOneID"]); cmbMaterialType.SelectedValue = Convert.ToInt64(dtAssetDetails.Rows[0]["nAssetMaterialID"]); cmbPartyVendor.SelectedValue = Convert.ToInt64(dtAssetDetails.Rows[0]["nAssetVendorID"]); cmbDensity.SelectedValue = Convert.ToInt64(dtAssetDetails.Rows[0]["nDensityID"]); cmbColor.SelectedValue = Convert.ToInt64(dtAssetDetails.Rows[0]["nColorID"]); txtHSNCode.Text = Convert.ToString(dtAssetDetails.Rows[0]["sHSNCode"]); txtAssetName.Text = Convert.ToString(dtAssetDetails.Rows[0]["sAssetName"]); txtAssetAbbrivation.Text = Convert.ToString(dtAssetDetails.Rows[0]["sAssetAbbrivation"]); txtAssetDescription.Text = Convert.ToString(dtAssetDetails.Rows[0]["sDescription"]); dtIntroductionDate.EditValue = Convert.ToDateTime(dtAssetDetails.Rows[0]["dtIntroductionDate"]); dtReorderTime.EditValue = Convert.ToDateTime(dtAssetDetails.Rows[0]["dtReorderDate"]); txtReorderDays.Text = Convert.ToString(dtAssetDetails.Rows[0]["sReorderDays"]); txtReorderQuantity.Text = Convert.ToString(dtAssetDetails.Rows[0]["sReorderQuality"]); txtAssetRate.Text = Convert.ToString(dtAssetDetails.Rows[0]["sRate"]); txtAssetMake.Text = Convert.ToString(dtAssetDetails.Rows[0]["sMake"]); txtSizeHeight.Text = Convert.ToString(dtAssetDetails.Rows[0]["sSizeOrCapacity"]); txtQuality.Text = Convert.ToString(dtAssetDetails.Rows[0]["sQuality"]); txtDimention.Text = Convert.ToString(dtAssetDetails.Rows[0]["sDimention"]); txtWeight.Text = Convert.ToString(dtAssetDetails.Rows[0]["sWeight"]); txtWattage.Text = Convert.ToString(dtAssetDetails.Rows[0]["sWattage"]); txtSpan.Text = Convert.ToString(dtAssetDetails.Rows[0]["sSpan"]); txtAttachment.Text = Convert.ToString(dtAssetDetails.Rows[0]["sAttachment"]); txtAttachmentName.Text = Convert.ToString(dtAssetDetails.Rows[0]["sAttachmentName"]); txtLength.Text = Convert.ToString(dtAssetDetails.Rows[0]["sLength"]); txtCore.Text = Convert.ToString(dtAssetDetails.Rows[0]["sCoreOrPole"]); txtAmps.Text = Convert.ToString(dtAssetDetails.Rows[0]["sAmps"]); txtPlug.Text = Convert.ToString(dtAssetDetails.Rows[0]["sPlug"]); txtPower.Text = Convert.ToString(dtAssetDetails.Rows[0]["sPower"]); txtAssetCode.Text = GenerateCode(); } if (dtAssetCodeDetails!=null&&dtAssetCodeDetails.Rows.Count>0) { lblAssetID.Text = Convert.ToString(dtAssetCodeDetails.Rows[0]["nAssetID"]); lblAssetCodeID.Text = Convert.ToString(dtAssetCodeDetails.Rows[0]["nAssetCodeID"]); txtShelfLifeUnit.Text = Convert.ToString(dtAssetCodeDetails.Rows[0]["sShelfLifeUnit"]); dtShelfLife.EditValue = Convert.ToDateTime(dtAssetCodeDetails.Rows[0]["dtShelfLife"]); dtRetirementDate.EditValue = Convert.ToDateTime(dtAssetCodeDetails.Rows[0]["dtRetirementDate"]); txtShelfLifeUnit.Text = Convert.ToString(dtAssetCodeDetails.Rows[0]["sShelfLifeUnit"]); txtAssetCode.Text = Convert.ToString(dtAssetCodeDetails.Rows[0]["sUniqueCode"]); byte[] barcodeImage = (byte[])dtAssetCodeDetails.Rows[0]["barcode"]; if (barcodeImage.Length > 0) { barcodeImage = (byte[])dtAssetCodeDetails.Rows[0]["barcode"]; MemoryStream msHeaderImage = new MemoryStream(barcodeImage); picBarcodeImage.Image = Image.FromStream(msHeaderImage); } //gvAssetList.GridControl.DataSource = dtAssetCodeDetails; //gvAssetList.Columns[1].Visible = false; //gvAssetList.Columns[6].Visible = false; } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oAssetMaster!=null) { oAssetMaster.Dispose(); oAssetMaster = null; } if (ds!=null) { ds.Dispose(); ds = null; } } } private void FillAssetCode(Int64 nAssetID=0) { AssetMaster oAsset = null; try { oAsset = new AssetMaster(); dtAssetCode = oAsset.GetAssetCode(nAssetID); if (dtAssetCode != null) { gvAssetList.GridControl.DataSource = dtAssetCode; gvAssetList.Columns[1].Visible = false; gvAssetList.Columns[6].Visible = false; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oAsset != null) { oAsset.Dispose(); oAsset = null; } } } private void FillAssetMaster() { AssetMaster clsAsset = null; DataSet dsMaster = null; try { clsAsset = new AssetMaster(); dsMaster = clsAsset.GetAllMasterData_ByMainType(0); if (dsMaster != null && dsMaster.Tables.Count > 0) { DataTable dtMainType = dsMaster.Tables[0].Copy(); DataTable dtCompany = dsMaster.Tables[1].Copy(); DataTable dtMaterialType = dsMaster.Tables[2].Copy(); DataTable dtColorType = dsMaster.Tables[3].Copy(); DataTable dtDensity = dsMaster.Tables[4].Copy(); DataTable dtVendor = dsMaster.Tables[5].Copy(); DataRow drMainType = dtMainType.NewRow(); drMainType["ID"] = 0; drMainType["Code"] = ""; dtMainType.Rows.InsertAt(drMainType, 0); DataRow drCompany = dtCompany.NewRow(); drCompany["ID"] = 0; drCompany["Code"] = ""; dtCompany.Rows.InsertAt(drCompany, 0); DataRow drMaterialType = dtMaterialType.NewRow(); drMaterialType["ID"] = 0; drMaterialType["Code"] = ""; dtMaterialType.Rows.InsertAt(drMaterialType, 0); DataRow drColorType = dtColorType.NewRow(); drColorType["ID"] = 0; drColorType["Code"] = ""; dtColorType.Rows.InsertAt(drColorType, 0); DataRow drDensity = dtDensity.NewRow(); drDensity["ID"] = 0; drDensity["Code"] = ""; dtDensity.Rows.InsertAt(drDensity, 0); DataRow drVendor = dtVendor.NewRow(); drVendor["ID"] = 0; drVendor["Code"] = ""; dtVendor.Rows.InsertAt(drVendor, 0); cmbMainType.DataSource = dtMainType; cmbMainType.DisplayMember = "Code"; cmbMainType.ValueMember = "ID"; cmbCompanyMst.DataSource = dtCompany; cmbCompanyMst.DisplayMember = "Code"; cmbCompanyMst.ValueMember = "ID"; cmbColor.DataSource = dtColorType; cmbColor.DisplayMember = "Code"; cmbColor.ValueMember = "ID"; cmbMaterialType.DataSource = dtMaterialType; cmbMaterialType.DisplayMember = "Code"; cmbMaterialType.ValueMember = "ID"; cmbDensity.SelectedIndexChanged -= cmbDensity_SelectedIndexChanged; cmbDensity.DataSource = dtDensity; cmbDensity.DisplayMember = "Code"; cmbDensity.ValueMember = "ID"; cmbDensity.SelectedIndexChanged += cmbDensity_SelectedIndexChanged; cmbPartyVendor.DataSource = dtVendor; cmbPartyVendor.DisplayMember = "Code"; cmbPartyVendor.ValueMember = "ID"; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (clsAsset != null) { clsAsset.Dispose(); clsAsset = null; } if (dsMaster != null) { dsMaster.Dispose(); dsMaster = null; } } } private void txtAssetName_EditValueChanged(object sender, EventArgs e) { txtAssetAbbrivation.Text = clsGlobal.GenerateAbbrivation(txtAssetName.Text.Trim()); } private void cmbMainType_SelectedIndexChanged(object sender, EventArgs e) { if (cmbMainType.SelectedIndex > 0) { FillAssetSubType(Convert.ToInt64(cmbMainType.SelectedValue)); txtAssetCode.Text= GenerateCode(); } EnableDisableControl(cmbMainType.Text); } private void FillAssetSubType(Int64 nMaintype) { AssetMaster clsAsset = null; DataSet dsAssetSubtype = null; try { clsAsset = new AssetMaster(); dsAssetSubtype = clsAsset.GetAllMasterData_ByMainType(nMaintype); if (dsAssetSubtype != null && dsAssetSubtype.Tables.Count > 0) { DataTable dtType = dsAssetSubtype.Tables[0].Copy(); DataTable dtTypeOne = dsAssetSubtype.Tables[1].Copy(); //DataTable dtSequenceNo = dsAssetSubtype.Tables[2].Copy(); DataRow drType = dtType.NewRow(); drType["ID"] = 0; drType["Code"] = ""; dtType.Rows.InsertAt(drType, 0); DataRow drTypeOne = dtTypeOne.NewRow(); drTypeOne["ID"] = 0; drTypeOne["Code"] = ""; dtTypeOne.Rows.InsertAt(drTypeOne, 0); cmbType.SelectedIndexChanged -= cmbType_SelectedIndexChanged; cmbType.DataSource = dtType; cmbType.DisplayMember = "Code"; cmbType.ValueMember = "ID"; cmbType.SelectedIndexChanged += cmbType_SelectedIndexChanged; cmbType1.DataSource = dtTypeOne; cmbType1.DisplayMember = "Code"; cmbType1.ValueMember = "ID"; //string sControlsName = Convert.ToString(dtControls.Rows[0]["ControlNames"]); //string sMainType = Convert.ToString(dtControls.Rows[0]["AssetName"]); //if (dtSequenceNo != null && dtSequenceNo.Rows.Count > 0) //{ // lblSequenceNo.Text = Convert.ToString(dtSequenceNo.Rows[0]["SequenceNo"]); //} } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (clsAsset != null) { clsAsset.Dispose(); clsAsset = null; } if (dsAssetSubtype != null) { dsAssetSubtype.Dispose(); dsAssetSubtype = null; } } } private void EnableDisableControl(string sMainType) { switch (sMainType.ToLower()) { case "cloth": case "cloths": {//cloth: Wattage,Span,Attachment,Attachment Name,Length,Core,Amps,Plug,Power txtWattage.ReadOnly = true; txtSpan.ReadOnly = true; txtAttachment.ReadOnly = true; txtAttachmentName.ReadOnly = true; txtLength.ReadOnly = true; txtCore.ReadOnly = true; txtAmps.ReadOnly = true; txtPlug.ReadOnly = true; txtPower.ReadOnly = true; txtSizeHeight.ReadOnly = false; cmbColor.Enabled = true; txtQuality.ReadOnly = false; cmbDensity.Enabled = true; break; } case "grip": case "grips": { //Grip: Density,Wattage,Color,Length,Core,Amps,Plug,Power txtQuality.ReadOnly = false; cmbDensity.Enabled = false; txtWattage.ReadOnly = true; cmbColor.Enabled = false; txtLength.ReadOnly = true; txtCore.ReadOnly = true; txtAmps.ReadOnly = true; txtPlug.ReadOnly = true; txtPower.ReadOnly = true; txtSizeHeight.ReadOnly = false; txtSpan.ReadOnly = false; txtAttachment.ReadOnly = false; txtAttachmentName.ReadOnly = false; break; } case "accessories": case "": { //Accessories: txtSizeHeight.ReadOnly = false; cmbColor.Enabled = true; txtQuality.ReadOnly = false; cmbDensity.Enabled = true; txtSpan.ReadOnly = false; txtAttachment.ReadOnly = false; txtAttachmentName.ReadOnly = false; txtCore.ReadOnly = false; txtAmps.ReadOnly = false; txtPlug.ReadOnly = false; txtWattage.ReadOnly = false; txtPower.ReadOnly = false; txtLength.ReadOnly = false; break; } case "light": case "lights": { //light: size,Color, Density, Span,Attachment,Attachment Name,Length,Core,Amps,Plug,Power txtSizeHeight.ReadOnly = true; cmbColor.Enabled = false; cmbDensity.Enabled = false; txtSpan.ReadOnly = true; txtAttachment.ReadOnly = true; txtAttachmentName.ReadOnly = true; txtLength.ReadOnly = true; txtCore.ReadOnly = true; txtAmps.ReadOnly = true; txtPlug.ReadOnly = true; txtPower.ReadOnly = true; txtQuality.ReadOnly = false; txtWattage.ReadOnly = false; break; } case "light accessories": case "lights accessories": { //light Accessories: size,Color,Quality, Density, Span,Attachment,Attachment Name,Core,Amps,Plug txtSizeHeight.ReadOnly = true; cmbColor.Enabled = false; txtQuality.ReadOnly = true; cmbDensity.Enabled = false; txtSpan.ReadOnly = true; txtAttachment.ReadOnly = true; txtAttachmentName.ReadOnly = true; txtCore.ReadOnly = true; txtAmps.ReadOnly = true; txtPlug.ReadOnly = true; txtWattage.ReadOnly = false; txtPower.ReadOnly = false; txtLength.ReadOnly = false; break; } case "power distribution": case "power distributions": { //Power Distribution: size,Color,Quality, Density,Wattage, Span,Attachment,Attachment Name,Power txtSizeHeight.ReadOnly = true; cmbColor.Enabled = false; txtQuality.ReadOnly = true; cmbDensity.Enabled = false; txtWattage.ReadOnly = true; txtSpan.ReadOnly = true; txtAttachment.ReadOnly = true; txtAttachmentName.ReadOnly = true; txtPower.ReadOnly = true; txtCore.ReadOnly = false; txtAmps.ReadOnly = false; txtPlug.ReadOnly = false; txtLength.ReadOnly = false; break; } } } private string GenerateAssetAbbrivation(string sAssetName) { string sAbbrivation = string.Empty; string[] sFullName = sAssetName.Split(' '); foreach (var item in sFullName) { if (item.All(char.IsDigit)) { sAbbrivation = sAbbrivation + item.ToString(); } else { sAbbrivation = sAbbrivation + item[0].ToString().ToUpper(); } } return sAbbrivation; } private void EnableDisableCodeControl(Int64 nAssetID) { if (nAssetID>0) { switch (cmbMainType.Text.Trim().ToLower()) { case "cloth": { txtSizeHeight.ReadOnly = true; cmbType.Enabled = false; cmbMainType.Enabled = false; cmbDensity.Enabled = false; break; } case "accessories": { cmbType.Enabled = false; break; } case "light": case "stands": case "grip": { txtAssetMake.ReadOnly = true; cmbType.Enabled = false; cmbMainType.Enabled = false; txtQuality.ReadOnly = true; break; } } } } private string GenerateCode() { //For Fixtures,Equipment’s, & Lights: Make (Char 3) Voltage(Char 4) Fixture Type (Char 3) Type (Char 3) Sr.No (Number 3) //Cloth Size (Char 5) Density (Char 4) Type (Char 4) Sr. No.(Number 3) //Accessories Type(NumChar 5) Sr.no.(Number 3) string sAssetCode = string.Empty; Int32 number = Convert.ToInt32(lblSequenceNo.Text)+1; switch (cmbMainType.Text.Trim().ToString().ToLower()) { case "cloth": { string sSize = string.Empty; string sDensity = string.Empty; string sType = string.Empty; string sNumber = string.Empty; if (txtSizeHeight.Text.Trim().Replace(" ", "") != "") { if (txtSizeHeight.Text.Length <= 5) { sSize = txtSizeHeight.Text.Trim().Replace(" ", ""); } else if (txtSizeHeight.Text.Length > 5) { sSize = txtSizeHeight.Text.Substring(0, 5).Trim().Replace(" ", ""); } } if (cmbDensity.Text.Trim().Replace(" ", "") != "") { if (cmbDensity.Text.Length <= 4) { sDensity = cmbDensity.Text.Trim().Replace(" ", ""); } else if (cmbDensity.Text.Length > 4) { sDensity = cmbDensity.Text.Substring(0, 4).Trim().Replace(" ", ""); } } if (cmbType.Text.Trim().Replace(" ", "") != "") { if (cmbType.Text.Length <= 4) { sType = cmbType.Text.Trim().Replace(" ", ""); } else if (cmbType.Text.Length > 4) { sType = cmbType.Text.Substring(0, 4).Trim().Replace(" ", ""); } } //sNumber = number.ToString(); //string sSize = txtSizeHeight.Text.Trim().Replace(" ","") == "" ? "" : txtSizeHeight.Text.Substring(0, 5); //string sDensity = cmbDensity.Text.Substring(0, 4); //string sType = cmbType.Text.Substring(0, 4); //string sNumber = lblSequenceNo.Text; sAssetCode = sSize + sDensity + sType;// +sNumber; break; } case "accessories": { string sType = string.Empty; string sNumber = string.Empty; if (cmbType.Text.Trim().Replace(" ", "") != "") { if (cmbType.Text.Length <= 5) { sType = cmbType.Text.Trim().Replace(" ", ""); } else if (cmbType.Text.Length > 5) { sType = cmbType.Text.Substring(0, 5).Trim().Replace(" ", ""); } } //sNumber = number.ToString(); sAssetCode = sType;//+ sNumber; break; } case "light": case "stands": case "grip": { string sMake = string.Empty; string sVoltage = string.Empty; string sFixtureType = string.Empty; string sType = string.Empty; string sNumber = string.Empty; if (txtAssetMake.Text.Trim().Replace(" ", "") != "") { if (txtAssetMake.Text.Length <= 3) { sMake = txtAssetMake.Text.Trim().Replace(" ", ""); } else if (txtAssetMake.Text.Length > 3) { sMake = txtAssetMake.Text.Substring(0, 3).Trim().Replace(" ", ""); } } if (txtQuality.Text.Trim().Replace(" ", "") != "") { if (txtQuality.Text.Length <= 4) { sVoltage = txtQuality.Text.Trim().Replace(" ", ""); } else if (txtQuality.Text.Length > 4) { sVoltage = txtQuality.Text.Substring(0, 4).Trim().Replace(" ", ""); } } if (cmbMainType.Text.Trim().Replace(" ", "") != "") { if (cmbMainType.Text.Length <= 3) { sFixtureType = cmbMainType.Text.Trim().Replace(" ", ""); } else if (cmbMainType.Text.Length > 3) { sFixtureType = cmbMainType.Text.Substring(0, 3).Trim().Replace(" ", ""); } } if (cmbType.Text.Trim().Replace(" ", "") != "") { if (cmbType.Text.Length <= 3) { sType = cmbType.Text.Trim().Replace(" ", ""); } else if (cmbType.Text.Length > 3) { sType = cmbType.Text.Substring(0, 3).Trim().Replace(" ", ""); } } //sNumber = number.ToString(); sAssetCode = sMake + sVoltage + sFixtureType + sType;// +sNumber; break; } } return sAssetCode; } private void btnAddBarcodeDetails_Click(object sender, EventArgs e) { try { int num = 0; byte[] BarcodeImage = new byte[] { }; if (picBarcodeImage != null) { if (picBarcodeImage.Image!=null) { using (MemoryStream ms = new MemoryStream()) { picBarcodeImage.Image.Save(ms, ImageFormat.Jpeg); BarcodeImage = new byte[ms.Length]; ms.Position = 0; ms.Read(BarcodeImage, 0, BarcodeImage.Length); } } } string sValue = string.Empty; num = dtAssetCode.Rows.Count; num++; sValue = num.ToString(); if (num < 1000) { sValue = num.ToString("000"); } if (Convert.ToInt64(lblAssetID.Text) > 0) { AssetCode oAssetCode = null; if (btnAddBarcodeDetails.Text.ToLower() == "add") { oAssetCode = new AssetCode(); oAssetCode.nAssetID = Convert.ToInt64(lblAssetID.Text); oAssetCode.nAssetCodeID = Convert.ToInt64(lblAssetCodeID.Text); oAssetCode.nSequenceNo = num; oAssetCode.sInitialCode = txtAssetCode.Text; oAssetCode.sUniqueCode = txtAssetCode.Text + lblSequenceNo.Text; oAssetCode.barcode = BarcodeImage; oAssetCode.dtShelfLife = Convert.ToDateTime(dtShelfLife.Text); oAssetCode.dtRetirementDate = Convert.ToDateTime(dtRetirementDate.Text); oAssetCode.sShelfLifeUnit = txtShelfLifeUnit.Text.Trim(); } else if(btnAddBarcodeDetails.Text.ToLower()=="edit") { oAssetCode = new AssetCode(); oAssetCode.nAssetID = Convert.ToInt64(lblAssetID.Text); oAssetCode.nAssetCodeID = Convert.ToInt64(lblAssetCodeID.Text); oAssetCode.nSequenceNo = 0; oAssetCode.sInitialCode = lblInitialCode.Text; oAssetCode.sUniqueCode = lblInitialCode.Text + lblSequenceNo.Text; oAssetCode.barcode = BarcodeImage; oAssetCode.dtShelfLife = Convert.ToDateTime(dtShelfLife.Text); oAssetCode.dtRetirementDate = Convert.ToDateTime(dtRetirementDate.Text); oAssetCode.sShelfLifeUnit = txtShelfLifeUnit.Text.Trim(); } Int64 nStatus = oAssetCode.UpdateAssetCode(); if (nStatus > 0) { FillAssetCode(oAssetCode.nAssetID); } } else { if (btnAddBarcodeDetails.Text.ToLower() == "edit") { DataRow[] drSelected = dtAssetCode.Select("RowNo=" + lblSelectedRow.Text); foreach (DataRow drAsset in drSelected) { drAsset["barcode"] = BarcodeImage; drAsset["dtShelfLife"] = Convert.ToDateTime(dtShelfLife.Text.ToString()); drAsset["sShelfLifeUnit"] = txtShelfLifeUnit.Text.Trim().ToString(); drAsset["dtRetirementDate"] = Convert.ToDateTime(dtRetirementDate.Text.ToString()); } dtAssetCode.AcceptChanges(); gvAssetList.RefreshData(); } else { //string sValue = string.Empty; //num = dtAssetCode.Rows.Count; //num++; //sValue = num.ToString(); //if (num < 1000) //{ // sValue = num.ToString("000"); //} //MessageBox.Show("Value: " + sValue); DataRow drAsset = dtAssetCode.NewRow(); drAsset["nSequenceNo"] = sValue; drAsset["sInitialCode"] = txtAssetCode.Text.Trim(); drAsset["sUniqueCode"] = txtAssetCode.Text.Trim() + num.ToString(); drAsset["barcode"] = BarcodeImage; drAsset["dtShelfLife"] = Convert.ToDateTime(dtShelfLife.Text.ToString()); drAsset["sShelfLifeUnit"] = txtShelfLifeUnit.Text.Trim().ToString(); drAsset["dtRetirementDate"] = Convert.ToDateTime(dtRetirementDate.Text.ToString()); drAsset["RowNo"] = num; dtAssetCode.Rows.Add(drAsset); gvAssetList.GridControl.DataSource = dtAssetCode; gvAssetList.Columns[1].Visible = false; gvAssetList.Columns[6].Visible = false; } } ClearAssetCodeDetails(); } catch (Exception ex) { MessageBox.Show("Error asset code: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ClearAssetCodeDetails() { if (picBarcodeImage!=null) { picBarcodeImage.Image = null; } dtShelfLife.EditValue = DateTime.Now; dtRetirementDate.EditValue = DateTime.Now; txtShelfLifeUnit.Text = ""; lblAssetCodeID.Text = "0"; lblInitialCode.Text = "0"; lblSequenceNo.Text = "0"; btnAddBarcodeDetails.Text = "Add"; } private void ClearAssetDetails() { cmbCompanyMst.SelectedValue = 0; cmbMainType.SelectedValue = 0; cmbType.SelectedValue = 0; cmbType1.SelectedValue = 0; cmbMaterialType.SelectedValue = 0; cmbPartyVendor.SelectedValue = 0; cmbDensity.SelectedValue = 0; cmbColor.SelectedValue = 0; txtHSNCode.Text = ""; txtAssetName.Text = ""; txtAssetAbbrivation.Text = ""; txtAssetDescription.Text = ""; dtIntroductionDate.EditValueChanged -= dtIntroductionDate_EditValueChanged; dtIntroductionDate.EditValue = DateTime.Now; dtReorderTime.EditValue = DateTime.Now; dtIntroductionDate.EditValueChanged += dtIntroductionDate_EditValueChanged; txtReorderDays.Text = ""; txtReorderQuantity.Text = ""; txtAssetRate.Text = ""; txtAssetMake.Text = ""; txtSizeHeight.Text = ""; txtQuality.Text = ""; txtDimention.Text = ""; txtWeight.Text = ""; txtWattage.Text = ""; txtSpan.Text = ""; txtAttachment.Text = ""; txtAttachmentName.Text = ""; txtLength.Text = ""; txtCore.Text = ""; txtAmps.Text = ""; txtPlug.Text = ""; txtPower.Text = ""; if (picBarcodeImage != null) { picBarcodeImage.Image = null; } dtShelfLife.EditValue = DateTime.Now; dtRetirementDate.EditValue = DateTime.Now; txtShelfLifeUnit.Text = ""; txtAssetCode.Text = string.Empty; //FillAssetCode(); } private void txtSizeHeight_EditValueChanged(object sender, EventArgs e) { //if (txtSizeHeight.Text.Trim() != "") //{ // txtAssetCode.Text = GenerateCode(); //} //UpdateAssetCodeTable(); } private void UpdateAssetCodeTable() { txtAssetCode.Text = GenerateCode(); //DataColumn dc = new DataColumn("sUniqueCode"); //dc.DataType = typeof(string); //dc.DefaultValue = GenerateCode();`` //dtAssetCode.Columns.Remove("sUniqueCode"); //dtAssetCode.Columns.Add(dc); //dtAssetCode.AcceptChanges(); //gvAssetList.RefreshData(); } private void cmbType_SelectedIndexChanged(object sender, EventArgs e) { //if (cmbType.Text.Trim() != "") //{ // txtAssetCode.Text = GenerateCode(); //} } private void cmbDensity_SelectedIndexChanged(object sender, EventArgs e) { //if (cmbDensity.Text.Trim() != "") //{ // txtAssetCode.Text = GenerateCode(); //} } private void txtAssetMake_EditValueChanged(object sender, EventArgs e) { //if (txtAssetMake.Text.Trim() != "") //{ // txtAssetCode.Text = GenerateCode(); //} } private void txtQuality_EditValueChanged(object sender, EventArgs e) { } private void txtSizeHeight_Leave(object sender, EventArgs e) { UpdateAssetCodeTable(); } private void cmbType_Leave(object sender, EventArgs e) { UpdateAssetCodeTable(); } private void txtAssetMake_Leave(object sender, EventArgs e) { if (cmbMainType.Text == "Grip" || cmbMainType.Text == "Light") { UpdateAssetCodeTable(); } } private void txtQuality_Leave(object sender, EventArgs e) { if (cmbMainType.Text == "Grip" || cmbMainType.Text == "Light") { UpdateAssetCodeTable(); } } private void cmbDensity_Leave(object sender, EventArgs e) { if (cmbMainType.Text == "Cloth") { UpdateAssetCodeTable(); } } private void btnSave_Click(object sender, EventArgs e) { if (ValidateForm()) { SaveAssetDetails(); } } private void SaveAssetDetails(bool bIsSaveAsset_Code=true) { AssetMaster oAsset = null; try { oAsset = new AssetMaster(); oAsset.nAssetID = Convert.ToInt64(lblAssetID.Text); oAsset.nCompanyID = Convert.ToInt64(cmbCompanyMst.SelectedValue); oAsset.nAssetMainTypeID = Convert.ToInt64(cmbMainType.SelectedValue); oAsset.nAssetTypeID = Convert.ToInt64(cmbType.SelectedValue); oAsset.nAssetTypeOneID = Convert.ToInt64(cmbType1.SelectedValue); oAsset.nAssetMaterialID = Convert.ToInt64(cmbMaterialType.SelectedValue); oAsset.nAssetVendorID = Convert.ToInt64(cmbPartyVendor.SelectedValue); oAsset.nDensityID = cmbDensity.Enabled == true ? Convert.ToInt64(cmbDensity.SelectedValue) : 0; oAsset.nColorID = cmbColor.Enabled == true ? Convert.ToInt64(cmbColor.SelectedValue) : 0; oAsset.sHSNCode = Convert.ToString(txtHSNCode.Text); oAsset.sAssetName = Convert.ToString(txtAssetName.Text); oAsset.sAssetAbbrivation = Convert.ToString(txtAssetAbbrivation.Text); oAsset.sAssetDescription = Convert.ToString(txtAssetDescription.Text); oAsset.dtReorderDate = Convert.ToDateTime(dtReorderTime.Text); oAsset.dtIntroductionDate = Convert.ToDateTime(dtIntroductionDate.Text); oAsset.sReorderDays = Convert.ToString(txtReorderDays.Text); oAsset.sReorderQuntity = Convert.ToString(txtReorderQuantity.Text); oAsset.sAssetRate = Convert.ToString(txtAssetRate.Text); oAsset.sAssetMake = Convert.ToString(txtAssetMake.Text); oAsset.sAssetSizeOrCapacity = Convert.ToString(txtSizeHeight.Text); oAsset.sAssetQuality = Convert.ToString(txtAssetAbbrivation.Text); oAsset.sAssetDimention = Convert.ToString(txtWeight.Text); oAsset.sAssetWeight = Convert.ToString(txtWeight.Text); oAsset.sWattage = Convert.ToString(txtWattage.Text); oAsset.sSpan = Convert.ToString(txtSpan.Text); oAsset.sAttachment = Convert.ToString(txtAttachment.Text); oAsset.sAttachmentName = Convert.ToString(txtAttachmentName.Text); oAsset.sLength = Convert.ToString(txtLength.Text); oAsset.sCoreOrPole = Convert.ToString(txtCore.Text); oAsset.sAmps = Convert.ToString(txtAmps.Text); oAsset.sPlug = Convert.ToString(txtPlug.Text); oAsset.sPower = Convert.ToString(txtPower.Text); List<AssetCode> lstAssetCode = new List<AssetCode>(); byte[] BarcodeImage = new byte[] { }; if (picBarcodeImage != null) { if (picBarcodeImage.Image != null) { using (MemoryStream ms = new MemoryStream()) { picBarcodeImage.Image.Save(ms, ImageFormat.Jpeg); BarcodeImage = new byte[ms.Length]; ms.Position = 0; ms.Read(BarcodeImage, 0, BarcodeImage.Length); } } } using (AssetCode oAssetCode = new AssetCode()) { oAssetCode.nAssetCodeID = Convert.ToInt64(lblAssetCodeID.Text); oAssetCode.nSequenceNo = 1; oAssetCode.sInitialCode = Convert.ToString(txtAssetCode.Text); oAssetCode.sUniqueCode = Convert.ToString(txtAssetCode.Text); oAssetCode.barcode = BarcodeImage; oAssetCode.dtShelfLife = Convert.ToDateTime(dtShelfLife.Text); oAssetCode.sShelfLifeUnit = Convert.ToString(txtShelfLifeUnit.Text); oAssetCode.dtRetirementDate = Convert.ToDateTime(dtRetirementDate.Text); lstAssetCode.Add(oAssetCode); } oAsset.lstAssetCode = lstAssetCode; Int64 nAssetID = oAsset.InsertUpdateAsset(bIsSaveAsset_Code); if (nAssetID == 0) { MessageBox.Show("Asset details not saved.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (nAssetID == 2) { MessageBox.Show("Asset code already present. Please change asset code.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Asset details saved successfully", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); ClearAssetDetails(); } } catch (Exception ex) { MessageBox.Show("Error Save : " + ex.Message, clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oAsset!=null) { oAsset.Dispose(); oAsset = null; } } } public bool ValidateForm() { if (txtAssetName.Text.Trim()=="") { MessageBox.Show("Enter Asset Name.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); txtAssetName.Focus(); return false; } if (cmbMainType.Text.Trim()=="") { MessageBox.Show("Select Asset Type.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); cmbMainType.Focus(); return false; } return true; } private void dtReorderTime_EditValueChanged(object sender, EventArgs e) { CalculateReorderDays(); } private void CalculateReorderDays() { double nDays = 0; DateTime dtIntroDate = Convert.ToDateTime(dtIntroductionDate.Text); DateTime dtROrderDate = Convert.ToDateTime(dtReorderTime.Text); if (dtROrderDate < dtIntroDate) { MessageBox.Show("Re-order date must be greater than or equal to Introduction date.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else if (dtIntroDate>dtROrderDate) { MessageBox.Show("Introduction date must be less than or equal to Re-order date.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } nDays = (dtROrderDate - dtIntroDate).TotalDays; txtReorderDays.Text = Convert.ToString(nDays); } private void gvAssetList_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e) { //try //{ // if (e.Column.Caption == "Delete") // { // int nVal = Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; // bool val = Convert.ToBoolean(nVal); // if (val) // { // DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); // ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; // ritem.ReadOnly = false; // ritem.Buttons[0].Enabled = false; // ritem.Buttons[0].Visible = false; // e.RepositoryItem = ritem; // } // } //} //catch (Exception ex) //{ // MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); //} } private void gvAssetList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e) { //try //{ // if (e.Column.Caption == "Edit") // { // var row = gvAssetList.GetFocusedDataRow(); // txtShelfLifeUnit.Text=Convert.ToString(row[10]); // dtShelfLife.Text=Convert.ToString(row[9]); // dtRetirementDate.Text=Convert.ToString(row[11]); // byte[] barcodeImage = (byte[])row[8]; // lblAssetCodeID.Text = Convert.ToString(row[1]); // lblInitialCode.Text = Convert.ToString(row[3]); // lblSequenceNo.Text = Convert.ToString(row[4]); // lblSelectedRow.Text = Convert.ToString(row[0]); // btnAddBarcodeDetails.Text = "Edit"; // if (barcodeImage.Length > 0) // { // barcodeImage = (byte[])row[9]; // MemoryStream msHeaderImage = new MemoryStream(barcodeImage); // picBarcodeImage.Image = Image.FromStream(msHeaderImage); // } // } // if (e.Column.Caption == "Delete") // { // var row = gvAssetList.GetFocusedDataRow(); // int n = Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvAssetList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; // if (n == 1) // { // return; // } // if (Convert.ToInt64(lblAssetID.Text)>0) // { // Int64 nAssetCodeID = Convert.ToInt64(row["nAssetCodeID"]); // AssetCode oAssetCode = new AssetCode(); // oAssetCode.nAssetCodeID = nAssetCodeID; // if (oAssetCode.DeleteAssetCode() > 0) // { // MessageBox.Show("Asset code deleted successfully.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); // } // else // { // MessageBox.Show("Asset code not deleted.", clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); // } // FillAssetCode(Convert.ToInt64(lblAssetID.Text)); // if (oAssetCode != null) // { // oAssetCode.Dispose(); // oAssetCode = null; // } // } // else // { // Int64 nRowNo = Convert.ToInt64(row["RowNo"]); // DataRow[] drDelete = dtAssetCode.Select("RowNo=" + Convert.ToInt64(nRowNo)); // foreach (DataRow dr in drDelete) // { // dr.Delete(); // } // dtAssetCode.AcceptChanges(); // int nRow = 0; // foreach (DataRow dr in dtAssetCode.Rows) // { // nRow++; // dr["RowNo"] = nRow; // } // //gvAssetList.GridControl.DataSource = dtAssetCode; // //gvAssetList.RefreshData(); // } // gvAssetList.GridControl.DataSource = dtAssetCode; // gvAssetList.RefreshData(); // //FillAssetCode(); // } //} //catch (Exception ex) //{ // MessageBox.Show("Error : " + ex, clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); //} } private void btnUpdateAsset_Click(object sender, EventArgs e) { if (ValidateForm()) { SaveAssetDetails(false); } } private void labelControl2_Click(object sender, EventArgs e) { } private void dtShelfLife_EditValueChanged(object sender, EventArgs e) { } private void labelControl3_Click(object sender, EventArgs e) { } private void dtRetirementDate_EditValueChanged(object sender, EventArgs e) { } private void groupControl2_Paint(object sender, PaintEventArgs e) { } private void labelControl20_Click(object sender, EventArgs e) { } private void labelControl18_Click(object sender, EventArgs e) { } private void labelControl16_Click(object sender, EventArgs e) { } private void dtIntroductionDate_EditValueChanged(object sender, EventArgs e) { CalculateReorderDays(); } } } <file_sep>using LGRentalMgntSystem.Class; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { class CompanyMaster { #region "Constructor & Distructor" private bool disposed = false; public CompanyMaster() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~CompanyMaster() { Dispose(false); } #endregion #region "Properties" public Int64 nCompanyID { get; set; } public Int64 nCompTransportID { get; set; } public Int64 nCompWarehouseID { get; set; } public Int64 nCompImageID { get; set; } public string sCompanyName { get; set; } public string sCompanyCode { get; set; } public string sCompAbbrivation { get; set; } public Int64 nCompanyTypeID { get; set; } public String sCompSignatoryID { get; set; } public string sCompAddressLine1 { get; set; } public string sCompAddressLine2 { get; set; } public string sCompCity { get; set; } public string sCompState { get; set; } public string sCompCountry { get; set; } public string sCompPincode { get; set; } public string sCompEmail { get; set; } public string sCompWebsite { get; set; } public string sCompPhone1 { get; set; } public string sCompPhone2 { get; set; } public string sCompPhone3 { get; set; } public string sCompPhone4 { get; set; } public string sCompPhone5 { get; set; } public string sCompAllPhoneNo { get; set; } public string sCompFax { get; set; } public string sCompHSN_SACCode { get; set; } public string sCompGSTNo { get; set; } public string sCompPANNo { get; set; } public DateTime dtCompanyFormedDate { get; set; } #region "Transportation Details" public string sTransporterID { get; set; } public string sTransDocumentName { get; set; } public string sTransDocumentNumber { get; set; } public DateTime sTransDocumentDate { get; set; } #endregion #region "Warehouse Details" public string nWHSupervisorID { get; set; } public string sWHAddressLine1 { get; set; } public string sWHAddressLine2 { get; set; } public string sWHCity { get; set; } public string sWHState { get; set; } public string sWHCountry { get; set; } public string sWHPincode { get; set; } public string sWHPhone1 { get; set; } public string sWHPhone2 { get; set; } public string sWHPhone3 { get; set; } public string sWHPhone4 { get; set; } public string sWHPhone5 { get; set; } public string sWHAllPhoneNo { get; set; } #endregion #region "Image Details" public byte[] imgCompHeader { get; set; } public byte[] imgCompFooter { get; set; } public byte[] imgTerms_Condition { get; set; } public string sTerms_Condition { get; set; } public Int32 nTerms_ConditionType { get; set; } #endregion #endregion #region "Method" public Int64 InsertUpdateCompanyMaster() { Int64 _nCompanyID = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objValue = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nCompanyID", this.nCompanyID, ParameterDirection.InputOutput, SqlDbType.BigInt); oDBParameter.Add("@sCompanyName", this.sCompanyName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompanyCode", this.sCompanyCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompAbbrivation", this.sCompAbbrivation, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@nCompanyTypeID", this.nCompanyTypeID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sCompanySignatory", this.sCompSignatoryID, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompAddressLine1", this.sCompAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompAddressLine2", this.sCompAddressLine2, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompCity", this.sCompCity, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompState", this.sCompState, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompCountry", this.sCompCountry, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompPincode", this.sCompPincode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompEmail", this.sCompEmail, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompWebsite", this.sCompWebsite, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompAllPhoneNo", this.sCompAllPhoneNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompFax", this.sCompFax, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompHSN_SACCode", this.sCompHSN_SACCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompGSTNo", this.sCompGSTNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCompPANNo", this.sCompPANNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtCompanyFormedOn", this.dtCompanyFormedDate, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sTransporterID", this.sTransporterID, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sTransDocumentDate", this.sTransDocumentDate, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sTransDocumentName", this.sTransDocumentName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sTransDocumentNumber", this.sTransDocumentNumber, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWHAddressLine1", this.sWHAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWHAddressLine2", this.sWHAddressLine2, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWHCity", this.sWHCity, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWHState", this.sWHState, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWHCountry", this.sWHCountry, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWHPincode", this.sWHPincode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@nWHSupervisorID", this.nWHSupervisorID, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWHAllPhoneNo", this.sWHAllPhoneNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@imgCompHeader", this.imgCompHeader, ParameterDirection.Input, SqlDbType.Image); oDBParameter.Add("@imgCompFooter", this.imgCompFooter, ParameterDirection.Input, SqlDbType.Image); oDBParameter.Add("@imgTerms_Condition", this.imgTerms_Condition, ParameterDirection.Input, SqlDbType.Image); oDBParameter.Add("@sTerms_Condition", this.sTerms_Condition, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@nTerms_ConditionType", this.nTerms_ConditionType, ParameterDirection.Input, SqlDbType.Int); oDBParameter.Add("@nTransportationID", this.nCompTransportID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nWarehouseID", this.nCompWarehouseID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nImageID", this.nCompImageID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Execute("lgsp_INUP_CompanyMasters", oDBParameter, out objValue); oDBAccess.CloseConnection(false); if (objValue != null) { _nCompanyID = Convert.ToInt64(objValue); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess!=null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter!=null) { oDBParameter.Dispose(); oDBParameter = null; } } return _nCompanyID; } public DataSet GetCompanyInformation(Int64 nCompanyID) { DataSet ds = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nCompanyID", nCompanyID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_CompanyDetails", oDBParameter, out ds); oDBAccess.CloseConnection(false); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return ds; } public DataTable GetCompanylist(Int64 nCompanyID) { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nCompanyID", nCompanyID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_CompanyListDetails", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } public DataTable GetListData(string sListType) { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@sListType", sListType, ParameterDirection.Input, SqlDbType.VarChar); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_ListData", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { class GafferMaster { #region "Constructor & Distructor" private bool disposed = false; public GafferMaster() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~GafferMaster() { Dispose(false); } #endregion #region "Properties" public Int64 nGafferID { get; set; } public Int64 nGafferTypeID { get; set; } public string sGafferName { get; set; } public string sGafferCode { get; set; } public string sGafferAbbrivation { get; set; } public string sGafferGender { get; set; } public DateTime dtGafferDOB { get; set; } public string sGafferAge { get; set; } public string sAddressLine1 { get; set; } public string sAddressLine2 { get; set; } public string sCity { get; set; } public string sState { get; set; } public string sCountry { get; set; } public string sPincode { get; set; } public string sEmail { get; set; } public string sAllPhoneNo { get; set; } public string sUserName { get; set; } public string sPassword { get; set; } public string sPin { get; set; } #endregion #region "Method" public Int64 InsertUpdateGafferMaster() { Int64 _nGafferID = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objValue = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nGafferID", this.nGafferID, ParameterDirection.InputOutput, SqlDbType.BigInt); oDBParameter.Add("@sGafferCode", this.sGafferCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sGafferName", this.sGafferName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sGafferAbbrivation", this.sGafferAbbrivation, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sGender", this.sGafferGender, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtDOB", this.dtGafferDOB, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sAge", this.sGafferAge, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAddressLine1", this.sAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAddressLine2", this.sAddressLine2, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCity", this.sCity, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sState", this.sState, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPincode", this.sPincode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCountry", this.sCountry, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sEmail", this.sEmail, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAllPhoneNo", this.sAllPhoneNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sUserName", this.sUserName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPassword", this.sPassword, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPin", this.sPin, ParameterDirection.Input, SqlDbType.VarChar); oDBAccess.OpenConnection(false); oDBAccess.Execute("lgsp_INUP_GafferMaster", oDBParameter, out objValue); oDBAccess.CloseConnection(false); if (objValue != null) { _nGafferID = Convert.ToInt64(objValue); } } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _nGafferID; } public DataTable GetGafferInformation(Int64 nGafferID) { DataSet ds = null; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nGafferID",nGafferID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_GafferDetails", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } public DataTable GetGafferlist(Int64 nGafferID) { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nGafferID", nGafferID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_GafferListDetails", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } #endregion } } <file_sep>using LGRentalMgntSystem.Class; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem.Forms { public partial class frmAssetList : DevExpress.XtraEditors.XtraForm { public frmAssetList() { InitializeComponent(); } public MasterType MasterType { get; set; } private void frmAssetList_Load(object sender, EventArgs e) { FillAssetList(); } private void FillAssetList() { clsMasters oClsMaster = null; DataTable dt = null; try { oClsMaster = new clsMasters(); dt = oClsMaster.GetMasterTypeData(this.MasterType.GetHashCode()); if (dt != null) { gvMasterList.GridControl.DataSource = dt; gvMasterList.Columns["TypeID"].Visible = false; gvMasterList.Columns["nAssetMainTypeID"].Visible = false; gvMasterList.Columns["IsUsed"].Visible = false; switch (MasterType) { case MasterType.AssetType: case MasterType.AssetType1: gvMasterList.Columns["AssetType"].Visible = true; gvMasterList.Columns["AllowAccess"].Visible = false; gvMasterList.Columns["AllowSignatory"].Visible = false; break; case MasterType.Designation: gvMasterList.Columns["AssetType"].Visible = false; gvMasterList.Columns["AllowAccess"].Visible = true; gvMasterList.Columns["AllowSignatory"].Visible = true; break; default: gvMasterList.Columns["AssetType"].Visible = false; gvMasterList.Columns["AllowAccess"].Visible = false; gvMasterList.Columns["AllowSignatory"].Visible = false; break; } } switch (MasterType) { case MasterType.CompanyType: { lblFormHeader.Text = "Company Type Details"; lblTypeName.Text = "Company Type : "; break; } case MasterType.MaterialType: { lblFormHeader.Text = "Material Type Details"; lblTypeName.Text = "Material Type : "; break; } case MasterType.Designation: { lblFormHeader.Text = "Designation Details"; lblTypeName.Text = "Designation : "; break; } case MasterType.AssetType: { lblFormHeader.Text = "Asset Type Details"; lblTypeName.Text = "Asset Type : "; break; } case MasterType.AssetType1: { lblFormHeader.Text = "Asset Type 1 Details"; lblTypeName.Text = "Asset Type 1 : "; break; } case MasterType.PartyType: { lblFormHeader.Text = "Party Type Details"; lblTypeName.Text = "Party Type : "; break; } case MasterType.VehicleType: { lblFormHeader.Text = "Vehicle Type Details"; lblTypeName.Text = "Vehicle Type : "; break; } case MasterType.ColourType: { lblFormHeader.Text = "Colour Type Details"; lblTypeName.Text = "Colour Type : "; break; } case MasterType.DensityType: { lblFormHeader.Text = "Density Type Details"; lblTypeName.Text = "Density Type : "; break; } case MasterType.AssetMainType: { lblFormHeader.Text = "Asset Main Type Details"; lblTypeName.Text = "Asset Main Type : "; break; } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void gvMasterList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e) { try { if (e.Column.Caption == "Edit") { Int64 nTypeID = 0; var row = gvMasterList.GetFocusedDataRow(); if (Convert.ToBoolean(row[7])) { return; } if (Convert.ToString(row[3])=="Warehouse Superintendent") { return; } nTypeID = Convert.ToInt64(row[1]); frmAssetMaster frmMaster = new frmAssetMaster(); frmMaster.MasterType = this.MasterType; frmMaster.nTypeID = Convert.ToInt64(row[1]); frmMaster.sTypeName = Convert.ToString(row[3]); frmMaster.bIsAllowAccess = Convert.ToBoolean(row[5]); frmMaster.bIsAllowSignatory = Convert.ToBoolean(row[6]); frmMaster.sTypeCode = Convert.ToString(row[8]); switch (MasterType) { case MasterType.AssetType: case MasterType.AssetType1: frmMaster.nMainTypeID = Convert.ToInt64(row[2]); break; } frmMaster.ShowDialog(); FillAssetList(); } if (e.Column.Caption == "Delete") { var row = gvMasterList.GetFocusedDataRow(); int n = Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; if (Convert.ToBoolean(row[7])) { return; } if (Convert.ToString(row[3]) == "Warehouse Superintendent") { return; } if (n == 1) { return; } if (MessageBox.Show("Do you want to delete?", clsGlobal._sMessageboxCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } clsMasters oclsMaster = new clsMasters(); oclsMaster.nMasterID = Convert.ToInt64(row[1]); oclsMaster.MasterType = this.MasterType; oclsMaster.DeleteMaster(); FillAssetList(); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btnSearch_Click(object sender, EventArgs e) { } private void txtSearch_EditValueChanged(object sender, EventArgs e) { try { DataView dv = (DataView)gvMasterList.DataSource; string sSearchText = txtSearch.Text; string fileter = ""; if (sSearchText != "") { fileter = dv.Table.Columns["TypeName"].Caption + " Like '%" + sSearchText + "%'"; dv.RowFilter = fileter; } else { dv.RowFilter = fileter; } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void gvMasterList_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e) { try { //if (e.Column.Caption == "Edit") //{ // bool val = Convert.ToBoolean(gvMasterList.GetRowCellValue(e.RowHandle, "IsUsed")); // if (val) // { // DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); // ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; // ritem.ReadOnly = false; // ritem.Buttons[0].Enabled = false; // ritem.Buttons[0].Visible = false; // e.RepositoryItem = ritem; // } //} TypeName if (e.Column.Caption == "Delete") { int nSystemDefined = Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "SystemDefined")) == "" || Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "SystemDefined")) == "0" ? 0 : 1; if (nSystemDefined==0) { int nVal = Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; string sVal = Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "TypeName")); bool val = Convert.ToBoolean(nVal); if (val) { DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; ritem.ReadOnly = false; ritem.Buttons[0].Enabled = false; ritem.Buttons[0].Visible = false; e.RepositoryItem = ritem; } if (sVal == "Warehouse Superintendent") { DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; ritem.ReadOnly = false; ritem.Buttons[0].Enabled = false; ritem.Buttons[0].Visible = false; e.RepositoryItem = ritem; } } else { DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; ritem.ReadOnly = false; ritem.Buttons[0].Enabled = false; ritem.Buttons[0].Visible = false; e.RepositoryItem = ritem; } } if (e.Column.Caption == "Edit") { int nSystemDefined = Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "SystemDefined")) == "" || Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "SystemDefined")) == "0" ? 0 : 1; if (nSystemDefined == 0) { string sVal = Convert.ToString(gvMasterList.GetRowCellValue(e.RowHandle, "TypeName")); if (sVal == "Warehouse Superintendent") { DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; ritem.ReadOnly = false; ritem.Buttons[0].Enabled = false; ritem.Buttons[0].Visible = false; e.RepositoryItem = ritem; } } else { DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; ritem.ReadOnly = false; ritem.Buttons[0].Enabled = false; ritem.Buttons[0].Visible = false; e.RepositoryItem = ritem; } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } //var row=gvMasterList.GetRowCellValue(e.RowHandle,gvMasterList.Columns[3]); //if (row == "Cloth") //{ // DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ri = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); //} } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { class StaffMaster { #region "Constructor & Distructor" private bool disposed = false; public StaffMaster() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { } } disposed = true; } ~StaffMaster() { Dispose(false); } #endregion #region "Properties" public Int64 nStaffID { get; set; } public Int64 nDesignationID { get; set; } public Int64 nCompanyID { get; set; } public string sStaffCode { get; set; } public string sStaffName { get; set; } public string sStaffAbbrivation { get; set; } public DateTime dtDOB { get; set; } public string sAge { get; set; } public string sGender { get; set; } public string sPhoneNo { get; set; } public string sPermanentAddressLine1 { get; set; } public string sPermanentAddressLine2 { get; set; } public string sPermanentPincode { get; set; } public string sPermanentDistTown { get; set; } public string sAddressLine1 { get; set; } public string sAddressLine2 { get; set; } public string sCity { get; set; } public string sState { get; set; } public string sCountry { get; set; } public string sPincode { get; set; } public string sEmail { get; set; } public DateTime dtDOJ { get; set; } public string sGSTNNo { get; set; } public string sPANNo { get; set; } public string sAadharNo { get; set; } public string sReferenceBy { get; set; } public string sAllergies { get; set; } public string sBloodGroup { get; set; } public string sWorkingSince { get; set; } public string sSalary { get; set; } public string sDailyWages { get; set; } public string sUnionID { get; set; } public DateTime dtUnionIDRenewalDate { get; set; } public string sFirstLicenseNumber { get; set; } public DateTime dtFirstLicenseRenewalDate { get; set; } public string sSecondLicenseNumber { get; set; } public DateTime dtSecondLicenseRenewalDate { get; set; } public string sThirdLicenseNumber { get; set; } public DateTime dtThirdLicenseRenewalDate { get; set; } public byte[] imgPhoto { get; set; } public bool bIsAllowAccess { get; set; } public string sUserName { get; set; } public string sPin { get; set; } public string sPassword { get; set; } #endregion #region "Method" public Int64 InsertUpdateStaffMaster() { Int64 _nStaffID = 0; DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; Object objValue = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nStaffID", this.nStaffID, ParameterDirection.InputOutput, SqlDbType.BigInt); oDBParameter.Add("@nDesignationID", this.nDesignationID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@nCompanyID", this.nCompanyID, ParameterDirection.Input, SqlDbType.BigInt); oDBParameter.Add("@sStaffCode", this.sStaffCode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sStaffName", this.sStaffName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sStaffAbbrivation", this.sStaffAbbrivation, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtDOB", this.dtDOB, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sAge", this.sAge, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sGender", this.sGender, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPhoneNo", this.sPhoneNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPermanentAddressLine1", this.sPermanentAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPermanentAddressLine2", this.sPermanentAddressLine2, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPermanentPincode", this.sPermanentPincode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPermanentDistTown", this.sPermanentDistTown, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAddressLine1", this.sAddressLine1, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAddressLine2", this.sAddressLine2, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCity", this.sCity, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sState", this.sState, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sCountry", this.sCountry, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPincode", this.sPincode, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sEmail", this.sEmail, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtDOJ", this.dtDOJ, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sGSTNNo", this.sGSTNNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPANNo", this.sPANNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAadharNo", this.sAadharNo, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sReferenceBy", this.sReferenceBy, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sAllergies", this.sAllergies, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sBloodGroup", this.sBloodGroup, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sWorkingSince", this.sWorkingSince, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sSalary", this.sSalary, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sDailyWages", this.sDailyWages, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sUnionID", this.sUnionID, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtUnionIDRenewalDate", this.dtUnionIDRenewalDate, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sFirstLicenseNumber", this.sFirstLicenseNumber, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtFirstLicenseRenewalDate", this.dtFirstLicenseRenewalDate, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sSecondLicenseNumber", this.sSecondLicenseNumber, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtSecondLicenseRenewalDate", this.dtSecondLicenseRenewalDate, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@sThirdLicenseNumber", this.sThirdLicenseNumber, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@dtThirdLicenseRenewalDate", this.dtThirdLicenseRenewalDate, ParameterDirection.Input, SqlDbType.DateTime); oDBParameter.Add("@imgPhoto", this.imgPhoto, ParameterDirection.Input, SqlDbType.Image); oDBParameter.Add("@bIsAllowAccess", this.bIsAllowAccess, ParameterDirection.Input, SqlDbType.Bit); oDBParameter.Add("@sUserName", this.sUserName, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPin", this.sPin, ParameterDirection.Input, SqlDbType.VarChar); oDBParameter.Add("@sPassword", this.sPassword, ParameterDirection.Input, SqlDbType.VarChar); oDBAccess.OpenConnection(false); oDBAccess.Execute("lgsp_INUP_CompanyStaff", oDBParameter, out objValue); oDBAccess.CloseConnection(false); if (objValue != null) { _nStaffID = Convert.ToInt64(objValue); } } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _nStaffID; } public DataTable GetStaffInformation(Int64 nStaffID) { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nStaffID", nStaffID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_StaffDetails", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } public DataTable GetStafflist(Int64 nStaffID) { DatabaseAccess oDBAccess = null; DatabaseParameters oDBParameter = null; DataTable _dt = null; try { oDBAccess = new DatabaseAccess(); oDBParameter = new DatabaseParameters(); oDBParameter.clear(); oDBParameter.Add("@nStaffID", nStaffID, ParameterDirection.Input, SqlDbType.BigInt); oDBAccess.OpenConnection(false); oDBAccess.Retrive("lgsp_Get_StaffListDetails", oDBParameter, out _dt); oDBAccess.CloseConnection(false); } catch (Exception ex) { oDBAccess.CloseConnection(false); MessageBox.Show("Error: " + ex.ToString(), clsGlobal.MessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (oDBAccess != null) { oDBAccess.Dispose(); oDBAccess = null; } if (oDBParameter != null) { oDBParameter.Dispose(); oDBParameter = null; } } return _dt; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LGRentalMgntSystem { public partial class frmMasterListGaffer : DevExpress.XtraEditors.XtraForm { public frmMasterListGaffer() { InitializeComponent(); } private void gvGafferList_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e) { try { if (e.Column.Caption == "Delete") { int nVal = Convert.ToString(gvGafferList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvGafferList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; bool val = Convert.ToBoolean(nVal); if (val) { DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit ritem = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); ritem.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor; ritem.ReadOnly = false; ritem.Buttons[0].Enabled = false; ritem.Buttons[0].Visible = false; e.RepositoryItem = ritem; } } } catch (Exception ex) { } } private void gvGafferList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e) { try { if (e.Column.Caption == "Edit") { Int64 nPartyID = 0; var row = gvGafferList.GetFocusedDataRow(); nPartyID = Convert.ToInt64(row[1]); frmMasterAddGaffer frmGaffer = new frmMasterAddGaffer(nPartyID); frmGaffer.ShowDialog(); FillGafferMasterList(); } if (e.Column.Caption == "Delete") { var row = gvGafferList.GetFocusedDataRow(); int n = Convert.ToString(gvGafferList.GetRowCellValue(e.RowHandle, "IsUsed")) == "" || Convert.ToString(gvGafferList.GetRowCellValue(e.RowHandle, "IsUsed")) == "0" ? 0 : 1; if (n == 1) { return; } if (MessageBox.Show("Do you want to delete?", clsGlobal._sMessageboxCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } clsGeneral oclsGeneral = new clsGeneral(); if (oclsGeneral.GetDeleteMasterType(MainMasterType.Gaffer.GetHashCode(), Convert.ToInt64(row[1])) > 0) { MessageBox.Show("Gaffer details deleted successfully.", clsGlobal._sMessageboxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } if (oclsGeneral != null) { oclsGeneral.Dispose(); oclsGeneral = null; } //clsMasters oclsMaster = new clsMasters(); //oclsMaster.nMasterID = Convert.ToInt64(row[1]); //oclsMaster.MasterType = this.MasterType; //oclsMaster.DeleteMaster(); FillGafferMasterList(); } } catch (Exception ex) { } } private void FillGafferMasterList() { GafferMaster clsGafferMaster = null; DataTable dt = null; try { clsGafferMaster = new GafferMaster(); dt = clsGafferMaster.GetGafferlist(0); if (dt!=null) { gvGafferList.GridControl.DataSource = dt; gvGafferList.Columns[1].Visible = false; gvGafferList.Columns[8].Visible = false; } } catch (Exception ex) { throw; } } private void frmMasterListGaffer_Load(object sender, EventArgs e) { FillGafferMasterList(); } } }
d8274225c7a89ee311f0df3817534de3172628dd
[ "C#" ]
30
C#
MayurPawar89/RentalMgntSystem
f9714209717e95239166f0387c572ddca3c16ee3
2393fdea7323a7feea42dc08ea90a631f7aca481
refs/heads/master
<repo_name>robotgoblin/turret-defence<file_sep>/source/Shoot.cpp #include "Shoot.h" bool _bullet_queued = false; int _lua_TurretShoot( lua_State* l ) { // No arguments are needed _bullet_queued = true; return 0; // 0 shows that there are no return values } bool BulletQueued() { return _bullet_queued; } void DequeueBullet() { _bullet_queued = false; } <file_sep>/source/Turret.h #ifndef _TURRET_H_ #define _TURRET_H_ #include <PurpleEngine/PurpleEngine.h> enum ETurretDirection { TD_NONE = 0, TD_CLOCKWISE, TD_ANTICLOCKWISE }; class Turret { public: Turret( float x, float y, float radius, Purple::Image* image ); ~Turret(); void Rotate( ETurretDirection direction ); float GetRotation(); ETurretDirection GetRotateDirection(); bool Hit( Purple::Sprite* other ); void Update(); private: Purple::Image* m_TurretImage; Purple::Sprite* m_TurretSprite; float m_Rotation; float m_Radius; void Rotate( float offset ); void SetRotation( float rotation ); ETurretDirection m_RotateDirection; }; void SetActiveTurret( Turret* ); Turret* GetActiveTurret(); #endif <file_sep>/source/Scan.h #ifndef _SCAN_H_ #define _SCAN_H_ #include <map> #include <string> #include "LuaHeader.h" void SetLastScanned( float x, float y ); int _lua_GetLastScanned( lua_State* l ); #endif <file_sep>/source/Scan.cpp #include "Scan.h" using std::string; using std::map; using std::pair; float last_scanned_x = 0.0f; float last_scanned_y = 0.0f; void SetLastScanned( float x, float y ) { last_scanned_x = x; last_scanned_y = y; } int _lua_GetLastScanned( lua_State* l ) { // This function doesn't need any arguments, so it isn't necessary to check them map< string, int > positions; positions.insert( pair< string, float >( "x", last_scanned_x ) ); positions.insert( pair< string, float >( "y", last_scanned_y ) ); lua_newtable( l ); int t = lua_gettop( l ); for( map<string, int>::iterator it = positions.begin(); it != positions.end(); it++ ) { lua_pushstring( l, it->first.c_str() ); lua_pushnumber( l, it->second ); lua_settable( l, t ); } return 1; } <file_sep>/source/Makefile # Build version VERSION=0.0.3 # Compiler to use (default=g++) CC=g++ # Basic compile flags CFLAGS=-c -D_VERSION_=$(VERSION) -DDEBUG `pkg-config --cflags lua5.1` # Linker flags LFLAGS=-lpurpleengine `pkg-config --libs lua5.1` # Source files SOURCES=main.cpp Turret.cpp Enemy.cpp Bullet.cpp Scan.cpp Shoot.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=run #EXECUTABLE=run.$(VERSION) all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(OBJECTS) -o $@ $(LFLAGS) clean: rm *.o .cpp.o: $(CC) $(CFLAGS) $< -o $@ <file_sep>/source/Enemy.cpp #include "Enemy.h" using namespace Purple; Enemy::Enemy( float x, float y, Image* image ) { this->m_Image = image; this->m_Sprite = image->CreateSprite( x, y, 0.0f ); this->m_Scanned = false; } Enemy::~Enemy() { this->m_Image->RemoveSprite( this->m_Sprite ); this->m_Sprite = NULL; } void Enemy::Face( float x, float y ) { float face_x = x - this->m_Sprite->GetX(); float face_y = y - this->m_Sprite->GetY(); float length = sqrt( pow( face_x, 2 ) + pow( face_y, 2 ) ); face_x /= length; face_y /= length; this->m_FaceX = face_x; this->m_FaceY = face_y; } void Enemy::Move( float speed ) { this->m_Sprite->Move( speed * this->m_FaceX, speed * this->m_FaceY, 0.0f ); } Sprite* Enemy::GetSprite() { return this->m_Sprite; } void Enemy::Hide() { this->m_Sprite->SetVisible( false ); } void Enemy::SetScanned( bool scanned ) { this->m_Scanned = scanned; } bool Enemy::GetScanned() { return this->m_Scanned; } <file_sep>/source/Turret.cpp #include "Turret.h" using namespace Purple; Turret* _active_turret = NULL; void SetActiveTurret( Turret* turret ) { _active_turret = turret; } Turret* GetActiveTurret() { return _active_turret; } Turret::Turret( float x, float y, float radius, Image* image ) { this->m_TurretImage = image; this->m_TurretSprite = image->CreateSprite( x, y, 0.0f ); this->m_TurretSprite->SetCollisionType( SC_CIRCLE ); this->m_TurretSprite->SetRadius( radius ); this->m_Rotation = 0.0f; } Turret::~Turret() { this->m_TurretImage->RemoveSprite( this->m_TurretSprite ); this->m_TurretSprite = NULL; } void Turret::Rotate( ETurretDirection direction ) { this->m_RotateDirection = direction; } void Turret::Rotate( float offset ) { this->SetRotation( this->m_Rotation + offset ); } void Turret::SetRotation( float rotation ) { this->m_Rotation = rotation; this->m_TurretSprite->SetRotation( this->m_Rotation ); // limit to being between 0 and 360 while ( this->m_Rotation > 360.0f ) { this->m_Rotation -= 360.0f; } while ( this->m_Rotation < 0 ) { this->m_Rotation += 360.0f; } } ETurretDirection Turret::GetRotateDirection() { return this->m_RotateDirection; } float Turret::GetRotation() { return this->m_Rotation; } bool Turret::Hit( Sprite* other ) { if ( this->m_TurretSprite->Collides( other ) ) { return true; } else return false; } void Turret::Update() { switch ( this->m_RotateDirection ) { case TD_CLOCKWISE: this->Rotate( 5.0f ); break; case TD_ANTICLOCKWISE: this->Rotate( -5.0f ); break; // Other cases need not be handled } } <file_sep>/source/Enemy.h #ifndef _ENEMY_H_ #define _ENEMY_H_ #include <PurpleEngine/PurpleEngine.h> class Enemy { public: Enemy( float x, float y, Purple::Image* image ); ~Enemy(); void Face( float x, float y ); void Move( float speed ); void Hide(); Purple::Sprite* GetSprite(); bool GetScanned(); void SetScanned( bool ); private: Purple::Image* m_Image; Purple::Sprite* m_Sprite; float m_FaceX; float m_FaceY; float m_Speed; bool m_Scanned; }; #endif <file_sep>/source/Shoot.h #ifndef _SHOOT_H_ #define _SHOOT_H_ /* * Allowing the player to shoot via a Lua function is acheived by having one boolean variable that * states whether or not a bullet is waiting to be fired. * This is for several reasons, firsly to overcome some issues with the scope of the bullet-related * variables, secondly to ensure the player can only shoot one bullet per frame, instead of queueing * many bullets to be fired all at once. */ #include "LuaHeader.h" int _lua_TurretShoot( lua_State* l ); bool BulletQueued(); void DequeueBullet(); #endif <file_sep>/source/Bullet.h #ifndef _BULLET_H_ #define _BULLET_H_ #include <PurpleEngine/PurpleEngine.h> class Bullet { public: Bullet( float x, float y, float rotation, Purple::Image* image ); ~Bullet(); void Move( float speed ); Purple::Sprite* GetSprite(); private: Purple::Image* m_Image; Purple::Sprite* m_Sprite; float m_FaceX; float m_FaceY; }; #endif <file_sep>/source/LuaMaths.h #ifndef _LUAMATHS_H_ #define _LUAMATHS_H_ #include <cmath> #include "LuaHeader.h" const float PI = 3.1415926535897931; // *PI/180 to convert degrees to radians inline int _lua_sin( lua_State* l ) { // Number of arguments necessary const int number_of_args = 1; if ( lua_gettop( l ) != number_of_args ) { std::cerr << "Incorrect number of arguments provided to lua_sin" << std::endl; return 0; } float x = (float)lua_tonumber( l, 1 ); lua_pushnumber( l, sin( x * PI/180.0f ) ); return 1; } inline int _lua_cos( lua_State* l ) { // Number of arguments necessary const int number_of_args = 1; if ( lua_gettop( l ) != number_of_args ) { std::cerr << "Incorrect number of arguments provided to lua_cos" << std::endl; return 0; } float x = (float)lua_tonumber( l, 1 ); lua_pushnumber( l, cos( x * PI/180.0f ) ); return 1; } inline int _lua_tan( lua_State* l ) { // Number of arguments necessary const int number_of_args = 1; if ( lua_gettop( l ) != number_of_args ) { std::cerr << "Incorrect number of arguments provided to lua_tan" << std::endl; return 0; } float x = (float)lua_tonumber( l, 1 ); lua_pushnumber( l, tan( x * PI/180.0f ) ); return 1; } inline int _lua_asin( lua_State* l ) { // Number of arguments necessary const int number_of_args = 1; if ( lua_gettop( l ) != number_of_args ) { std::cerr << "Incorrect number of arguments provided to lua_asin" << std::endl; return 0; } float x = (float)lua_tonumber( l, 1 ); lua_pushnumber( l, asin( x ) * 180.0f/PI ); return 1; } inline int _lua_acos( lua_State* l ) { // Number of arguments necessary const int number_of_args = 1; if ( lua_gettop( l ) != number_of_args ) { std::cerr << "Incorrect number of arguments provided to lua_acos" << std::endl; return 0; } float x = (float)lua_tonumber( l, 1 ); lua_pushnumber( l, acos( x ) * 180.0f/PI ); return 1; } inline int _lua_atan( lua_State* l ) { // Number of arguments necessary const int number_of_args = 1; if ( lua_gettop( l ) != number_of_args ) { std::cerr << "Incorrect number of arguments provided to lua_atan" << std::endl; return 0; } float x = (float)lua_tonumber( l, 1 ); lua_pushnumber( l, atan( x ) * 180.0f/PI ); return 1; } inline int _lua_sqrt( lua_State* l ) { // Number of arguments necessary const int number_of_args = 1; if ( lua_gettop( l ) != number_of_args ) { std::cerr << "Incorrect number of arguments provided to lua_sqrt" << std::endl; return 0; } float x = (float)lua_tonumber( l, 1 ); lua_pushnumber( l, (float)sqrt( x ) ); return 1; } inline int _lua_pow( lua_State* l ) { // Number of arguments necessary const int number_of_args = 2; if ( lua_gettop( l ) != number_of_args ) { std::cerr << "Incorrect number of arguments provided to lua_pow" << std::endl; return 0; } float n = (float)lua_tonumber( l, 1 ); // Get the first argument (n) float power = (float)lua_tonumber( l, 2 ); // Get the second argument (power) lua_pushnumber( l, (float)pow( n, power ) ); return 1; } inline int _lua_abs( lua_State* l ) { // Number of arguments necessary const int number_of_args = 1; if ( lua_gettop( l ) != number_of_args ) { std::cerr << "Incorrect number of arguments provided to lua_abs" << std::endl; return 0; } float x = (float)lua_tonumber( l, 1 ); lua_pushnumber( l, (float)abs(x) ); return 1; } inline void register_maths( lua_State* l ) { lua_register( l, "sin", _lua_sin ); lua_register( l, "cos", _lua_cos ); lua_register( l, "tan", _lua_tan ); lua_register( l, "asin", _lua_asin ); lua_register( l, "acos", _lua_acos ); lua_register( l, "atan", _lua_atan ); lua_register( l, "sqrt", _lua_sqrt ); lua_register( l, "pow", _lua_pow ); lua_register( l, "abs", _lua_abs ); } #endif <file_sep>/source/main.cpp #include <iostream> #include <string> #include <vector> #include <PurpleEngine/PurpleEngine.h> #include "Turret.h" #include "Enemy.h" #include "Bullet.h" #include "Scan.h" #include "TurretMovement.h" #include "LuaMaths.h" #include "Shoot.h" using namespace Purple; using std::string; using std::vector; const char* SETTINGS_FILE = "settings.set"; const float TEMP_SCAN_RANGE = 600.0f; float* p_turret_health = NULL; int _lua_GetHealth( lua_State* l ); int main( int argc, char* argv[] ) { // Seed random to ensure proper random numbers srand( time( NULL ) ); //------------- Primary Settings ------------- int screen_width, screen_height; string screen_title; string attacker_image_file; string turret_set_file; string player_set_file; string bullet_image_file; float bullet_speed; float enemy_random_x; float enemy_random_y; int enemy_count; float enemy_speed; string font_file; float font_size; SettingManager setting_loader; if ( setting_loader.LoadFile( SETTINGS_FILE ) ) { setting_loader.GetNumber<int>( "screen_width", screen_width ); setting_loader.GetNumber<int>( "screen_height", screen_height ); setting_loader.GetString( "screen_title", screen_title ); setting_loader.GetString( "turret_settings", turret_set_file ); setting_loader.GetString( "player_settings", player_set_file ); setting_loader.GetString( "attacker_image", attacker_image_file ); setting_loader.GetNumber<float>( "enemy_random_x", enemy_random_x ); setting_loader.GetNumber<float>( "enemy_random_y", enemy_random_y ); setting_loader.GetNumber<int>( "enemy_count", enemy_count ); setting_loader.GetNumber<float>( "enemy_speed", enemy_speed ); setting_loader.GetString( "bullet_image", bullet_image_file ); setting_loader.GetNumber<float>( "bullet_speed", bullet_speed ); setting_loader.GetString( "font_file", font_file ); setting_loader.GetNumber<float>( "font_size", font_size ); } else { std::cerr << "Unable to load primary settings file." << std::endl; return 1; // return 1 to signify error } //------------------------------------------- //------------- Turret Settings ------------- float turret_x, turret_y, turret_radius, turret_health; string turret_image_file; if ( setting_loader.LoadFile( turret_set_file ) ) { setting_loader.GetNumber<float>( "turret_x", turret_x ); setting_loader.GetNumber<float>( "turret_y", turret_y ); setting_loader.GetNumber<float>( "turret_radius", turret_radius ); setting_loader.GetNumber<float>( "turret_health", turret_health ); setting_loader.GetString( "turret_image", turret_image_file ); // Set player health pointer p_turret_health = &turret_health; } else { std::cerr << "Unable to load turret settings." << std::endl; return 1; // return 1 to signify error } //------------------------------------------- //------------- Load Player File ------------- lua_State* l = lua_open(); luaL_openlibs( l ); if ( luaL_dofile( l, player_set_file.c_str() ) != 0 ) { std::cerr << "Unable to load player Lua file." << std::endl; lua_close( l ); return 1; // return 1 to signify error } // Register functions for the player's script to use lua_register( l, "GetLastScanned", _lua_GetLastScanned ); lua_register( l, "TurretRotateClockwise", _lua_TurretRotateClockwise ); lua_register( l, "TurretRotateAntiClockwise", _lua_TurretRotateAntiClockwise ); lua_register( l, "TurretRotateStop", _lua_TurretRotateStop ); lua_register( l, "TurretShoot", _lua_TurretShoot ); lua_register( l, "GetTurretRotation", _lua_GetTurretRotation ); lua_register( l, "GetHealth", _lua_GetHealth ); register_maths( l ); //-------------------------------------------- //----Initialise game engine and create window, etc. ---- Engine2D* my_engine = new Engine2D( screen_width, screen_height, screen_title.c_str() ); my_engine->SetDesiredFps( 30 ); //------------------------------------------------------- //------------- Load Images ------------- Image* turret_image = my_engine->LoadImage( turret_image_file.c_str() ); Image* attacker_image = my_engine->LoadImage( attacker_image_file.c_str() ); Image* bullet_image = my_engine->LoadImage( bullet_image_file.c_str() ); //--------------------------------------- //------------- Load Font ------------- Font* main_font = my_engine->LoadFont( font_file.c_str(), font_size ); //------------------------------------- //------------- Game Objects ------------- Turret* turret = new Turret( turret_x, turret_y, turret_radius, turret_image ); SetActiveTurret( turret ); vector<Bullet*> bullets; // Create enemies vector<Enemy*> enemies; for ( int i = 0; i < enemy_count; i++ ) { Enemy* enemy; int area = util::Random( 4, 0 ); // Select which area the enemy will be in (see switch below) // Place the new enemy float x = util::Random( enemy_random_x ); float y = util::Random( enemy_random_y ); switch ( area ) { case 0: // TOP enemy = new Enemy( x, 0.0f - y, attacker_image ); break; case 1: // BOTTOM enemy = new Enemy( x, my_engine->GetHeight() + y, attacker_image ); break; case 2: // LEFT enemy = new Enemy( 0.0f - x, y, attacker_image ); break; case 3: // RIGHT enemy = new Enemy( my_engine->GetWidth() + x, y, attacker_image ); break; default: // TOP enemy = new Enemy( x, 0.0f - y, attacker_image ); break; } // Set the enemy to face the turret enemy->Face( turret_x, turret_y ); enemies.push_back( enemy ); } //---------------------------------------- //------------- Game State ------------- enum EGameState { STATE_PREPARE = 0, // Intro screen (Press space to begin) STATE_RUN, // The normal running game STATE_WIN, // The player has won STATE_LOSE // The player has lost }; EGameState game_state = STATE_PREPARE; //-------------------------------------- while( my_engine->IsAlive() ) { my_engine->Update(); // This has to be run switch ( game_state ) { case STATE_RUN: { #ifdef DEBUG // Debug and testing keys if ( my_engine->IsKeyHeld( KEY_RIGHT ) ) { turret->Rotate( TD_CLOCKWISE ); } else if ( my_engine->IsKeyHeld( KEY_LEFT ) ) { turret->Rotate( TD_ANTICLOCKWISE ); } if ( my_engine->IsKeyHit( KEY_SPACE ) ) { // Cheat to shoot a bullet _lua_TurretShoot( NULL ); } #endif // Update turret lua_getglobal( l, "update_turret" ); if (! lua_isfunction( l, -1 ) ) { std::cerr << "FATAL: Lua function update_turret not found!" << std::endl; my_engine->Stop(); } else lua_call( l, 0, 1 ); turret->Update(); // Check if a bullet needs to be fired if ( BulletQueued() ) { Bullet* temp_bullet = new Bullet( turret_x, turret_y, turret->GetRotation(), bullet_image ); temp_bullet->Move( turret_radius ); bullets.push_back( temp_bullet ); DequeueBullet(); } // Update enemies for ( int i = 0; i < enemies.size(); i++ ) { enemies[i]->Move( enemy_speed ); // Check if the enemy is within scan range and hasn't been scanned if ( ! enemies[i]->GetScanned() ) { float x = turret_x - enemies[i]->GetSprite()->GetX(); float y = turret_y - enemies[i]->GetSprite()->GetY(); float distance = sqrt( pow( x, 2 ) + pow( y, 2 ) ); if ( distance < TEMP_SCAN_RANGE ) { enemies[i]->SetScanned( true ); SetLastScanned( enemies[i]->GetSprite()->GetX(), enemies[i]->GetSprite()->GetY() ); lua_getglobal( l, "enemy_scanned" ); if ( lua_isfunction( l, -1 ) ) { lua_call( l, 0, 1 ); } #ifdef DEBUG else { std::cout << "Enemy scanned, but no \"enemy_scanned\" Lua function found." << std::endl; } #endif } } // Check for collisions between the player and enemy if ( turret->Hit( enemies[i]->GetSprite() ) ) { delete enemies[i]; enemies.erase( enemies.begin() + i ); i--; if ( --turret_health <= 0 ) { game_state = STATE_LOSE; break; } } } // Update bullets for ( int i = 0; i < bullets.size(); i++ ) { bullets[i]->Move( bullet_speed ); // Check if the bullet has hit an enemy for ( int j = 0; j < enemies.size(); j++ ) { if ( bullets[i]->GetSprite()->Collides( enemies[j]->GetSprite() ) ) { // Destroy the enemy and bullet then break the loop delete enemies[j]; enemies.erase( enemies.begin() + j ); delete bullets[i]; bullets.erase( bullets.begin() + i ); i--; // Check if the enemies are all dead if ( enemies.size() <= 0 ) { // Player wins game_state = STATE_WIN; } break; // break the for loop, the enemy has already been destoryed } } } } break; case STATE_PREPARE: { // Draw a message to instruct the player to press space const char* prepare_message = "Press SPACE to begin!"; float x = (my_engine->GetWidth() - main_font->MeasureWidth( prepare_message )) / 2.0f; float y = 100.0f; main_font->DrawText( prepare_message, x, y, 255, 255, 255 ); if ( my_engine->IsKeyHit( KEY_SPACE ) ) { game_state = STATE_RUN; } } break; case STATE_WIN: { // Draw a message to instruct the player to press space const char* message = "You Win!"; float x = (my_engine->GetWidth() - main_font->MeasureWidth( message )) / 2.0f; float y = 100.0f; main_font->DrawText( message, x, y, 255, 255, 255 ); } break; case STATE_LOSE: { // Draw a message to instruct the player to press space const char* message = "You Lose!"; float x = (my_engine->GetWidth() - main_font->MeasureWidth( message )) / 2.0f; float y = 100.0f; main_font->DrawText( message, x, y, 255, 255, 255 ); } break; } if ( my_engine->IsKeyHit( KEY_ESCAPE ) ) { my_engine->Stop(); } } // Clean up lua_close( l ); for ( int i = 0; i < enemies.size(); i++ ) { delete enemies[i]; } enemies.clear(); for ( int i = 0; i < bullets.size(); i++ ) { delete bullets[i]; } bullets.clear(); delete turret; delete my_engine; return 0; } int _lua_GetHealth( lua_State* l ) { // No arguments necessary if ( p_turret_health == NULL ) { std::cerr << "Error: Player health pointer not set" << std::endl; return 0; } float health = *p_turret_health; lua_pushnumber( l, health ); return 1; } <file_sep>/source/turret.lua function update_turret() -- Work with the turret print( "You can print any debug information if you're running the game in a command-line." ); end <file_sep>/source/Bullet.cpp #include "Bullet.h" using namespace Purple; float degreesToRadians( float degrees ) { const float PI = 3.141592653589793f; return degrees * (PI / 180.0f); } Bullet::Bullet( float x, float y, float rotation, Image* image ) { this->m_Image = image; this->m_Sprite = image->CreateSprite( x, y, 0.0f ); this->m_FaceX = sin( degreesToRadians( rotation ) ); this->m_FaceY = -cos( degreesToRadians( rotation ) ); } Bullet::~Bullet() { this->m_Image->RemoveSprite( this->m_Sprite ); } void Bullet::Move( float speed ) { this->m_Sprite->Move( speed * this->m_FaceX, speed * this->m_FaceY, 0.0f ); } Sprite* Bullet::GetSprite() { return this->m_Sprite; } <file_sep>/source/TurretMovement.h #ifndef _TURRETMOVEMENT_H_ #define _TURRETMOVEMENT_H_ #include "Turret.h" inline int _lua_TurretRotateClockwise( lua_State* l ) { // No arguments are needed Turret* active_turret = GetActiveTurret(); active_turret->Rotate( TD_CLOCKWISE ); return 0; // 0 shows that there are no return values } inline int _lua_TurretRotateAntiClockwise( lua_State* l ) { // No arguments are needed Turret* active_turret = GetActiveTurret(); active_turret->Rotate( TD_ANTICLOCKWISE ); return 0; // 0 shows that there are no return values } inline int _lua_TurretRotateStop( lua_State* l ) { // No arguments are needed Turret* active_turret = GetActiveTurret(); active_turret->Rotate( TD_NONE ); return 0; // 0 shows that there are no return values } inline int _lua_GetTurretRotation( lua_State* l ) { // No arguments are needed Turret* active_turret = GetActiveTurret(); float rotation = active_turret->GetRotation(); lua_pushnumber( l, rotation ); return 1; } #endif
4480a17aaff54fb29bdba90d6c848ef2ffecb417
[ "C", "Makefile", "C++", "Lua" ]
15
C++
robotgoblin/turret-defence
03af86cdf6bb883eee0dbe356a376326d0716e79
5b7c814bd9c93dc4f1ee9eb6292cd44ae21ebf5b
refs/heads/master
<file_sep>var searchData= [ ['animal_0',['Animal',['../class_animal.html',1,'']]] ]; <file_sep>/* * Bank.h */ #ifndef SRC_BANK_H_ #define SRC_BANK_H_ #include "Account.h" #include "BankOfficer.h" #include <vector> class Bank { vector<Account *> accounts; vector<BankOfficer> bankOfficers; public: Bank(); void addAccount(Account *a); void addBankOfficer(BankOfficer b); vector<BankOfficer> getBankOfficers() const; vector<Account *> getAccounts() const; double getWithdraw(string cod1) const; vector<Account *> removeBankOfficer(string name); const BankOfficer& addAccountToBankOfficer(Account *ac, string name); void sortAccounts(); }; template <class T> unsigned int numberDifferent (const vector<T> & v1) { unsigned int counter = 0; bool repeated; for (typename vector<T>::const_iterator i = v1.begin(); i != v1.end(); i++) { repeated = false; for (typename vector<T>::const_iterator j = v1.begin(); j != i; j++) { if ((*i) == (*j)) { repeated = true; } } if (!repeated) { counter++; } } return counter; } class NoBankOfficerException { private: string name; public: NoBankOfficerException(string name); string getName(); }; #endif /* SRC_BANK_H_ */ <file_sep>var searchData= [ ['serviceprovider_137',['ServiceProvider',['../class_service_provider.html',1,'']]] ]; <file_sep>var searchData= [ ['bat_1',['Bat',['../class_bat.html',1,'']]] ]; <file_sep>#include <iostream> #include <string> #include <fstream> #include <sstream> #include "dictionary.h" #include "bst.h" using namespace std; BST<WordMeaning> Dictionary::getWords() const { return words; } bool WordMeaning::operator < (const WordMeaning &wm1) const { return word < wm1.word; } void Dictionary::readDictionary(ifstream &f) { string w, m; while (!f.eof()) { getline(f, w); getline(f, m); WordMeaning newWM(w,m); words.insert(newWM); } } string Dictionary::searchFor(string word) const { BSTItrIn<WordMeaning> it(words); string wb = "", mb = "", wa = "", ma = ""; while(!it.isAtEnd()) { if (it.retrieve().getWord() == word) { //word was found return it.retrieve().getMeaning(); } else if (it.retrieve().getWord() < word) { //word still might be found wb = it.retrieve().getWord(); mb = it.retrieve().getMeaning(); } else if (it.retrieve().getWord() > word) { //we know for sure that word does not exist wa = it.retrieve().getWord(); ma = it.retrieve().getMeaning(); break; } it.advance(); } throw WordInexistent(wb, mb, wa, ma); } bool Dictionary::correct(string word, string newMeaning) { BSTItrIn<WordMeaning> it(words); while (!it.isAtEnd()) { if (it.retrieve().getWord() == word) { words.remove(it.retrieve()); //removes the incorrect one WordMeaning corrected(word, newMeaning); words.insert(corrected); //inserts the corrected one return true; } it.advance(); } WordMeaning newWM(word, newMeaning); //otherwise just inserts a new one words.insert(newWM); return false; } void Dictionary::print() const { BSTItrIn<WordMeaning> it(words); while (!it.isAtEnd()) { cout << it.retrieve().getWord() << endl << it.retrieve().getMeaning() << endl; it.advance(); } } <file_sep>var searchData= [ ['lift_129',['Lift',['../class_lift.html',1,'']]], ['liftdoesnotexist_130',['LiftDoesNotExist',['../class_lift_does_not_exist.html',1,'']]] ]; <file_sep>var searchData= [ ['maintenance_131',['Maintenance',['../struct_maintenance.html',1,'']]], ['moves_132',['Moves',['../struct_moves.html',1,'']]] ]; <file_sep>var searchData= [ ['removeemployee_73',['removeEmployee',['../class_pitch.html#aa66c003ecbe8ca2d6ec436733efac250',1,'Pitch::removeEmployee(Employee *toRemove)'],['../class_pitch.html#a6285fc9613025bcad4b063f27a32f19b',1,'Pitch::removeEmployee(unsigned int nif)']]], ['removetask_74',['removeTask',['../class_service_provider.html#ad32644a0131dce5d85042d64dbcd90c1',1,'ServiceProvider']]], ['review_75',['review',['../class_employee.html#a7a85952f84ca65a6b8756508b7df2fe6',1,'Employee']]], ['reviewassociatedemployee_76',['reviewAssociatedEmployee',['../class_pitch.html#a3e46166eb1360f24958fd8c9e15b7d0a',1,'Pitch']]], ['reviewserviceprovided_77',['reviewServiceProvided',['../class_pitch.html#a5d118f8137b6b175ef6ee5e0a4c0af41',1,'Pitch']]] ]; <file_sep>var searchData= [ ['maintenance_64',['Maintenance',['../struct_maintenance.html',1,'']]], ['moves_65',['Moves',['../struct_moves.html',1,'']]] ]; <file_sep>#ifndef SRC_HOTEL_H_ #define SRC_HOTEL_H_ #include <vector> #include <list> template <class Chamber> class Hotel { std::vector<Chamber *> chambers; const unsigned int maxCapacity; const std::string city; std::list<Chamber> reservationsDone; public: Hotel(int size, std::string municipality); ~Hotel(); std::vector<Chamber *> getChambers() const; void setChambers(std::vector<Chamber *> chambers); int getCapacity() const; std::list<Chamber> getReservationsDone() const; bool addChamber(Chamber *chamber); void addReservationDone(Chamber chamber); Chamber* removeChamber(std::string code, int floor); float avgArea(int floor) const; void sortChambers(); bool doReservation(std::string code, int floor); std::list<Chamber> roomsNeverReserved() const; }; class NoSuchChamberException { public: NoSuchChamberException() { } }; class NoSuchFloorException { private: int floor; public: NoSuchFloorException(int floor); int getFloor(); }; NoSuchFloorException::NoSuchFloorException(int floor) { this->floor = floor; } int NoSuchFloorException::getFloor() { return floor; } template <class Chamber> Hotel<Chamber>::Hotel(int size, std::string municipality) : maxCapacity(size), city(municipality) { } template <class Chamber> Hotel<Chamber>::~Hotel(){ typename std::vector<Chamber *>::const_iterator it; for (it=chambers.begin(); it!=chambers.end(); it++) { delete *it; } } template<class Chamber> std::vector<Chamber *> Hotel<Chamber>::getChambers() const { return chambers; } template<class Chamber> void Hotel<Chamber>::setChambers(std::vector<Chamber*> chambers) { this->chambers = chambers; } template<class Chamber> int Hotel<Chamber>::getCapacity() const { return maxCapacity; } template<class Chamber> void Hotel<Chamber>::addReservationDone(Chamber chamber) { reservationsDone.push_back(chamber); } template<class Chamber> std::list<Chamber> Hotel<Chamber>::getReservationsDone() const { return reservationsDone; } template<class Chamber> bool Hotel<Chamber>::addChamber(Chamber *chamber) { if (chambers.size() == maxCapacity) { //reached maximum capacity return false; } for (typename std::vector<Chamber*>::const_iterator it = chambers.begin(); it != chambers.end(); it++) { if (*(*it) == *chamber) { //chamber already exists return false; } } chambers.push_back(chamber); return true; } bool sortRooms(Room *r1, Room *r2) { if (r1->getCode() < r2->getCode()) return true; else if (r1->getCode() == r2->getCode() && r2->getFloor() < r1->getFloor()) return true; else return false; } template<class Chamber> void Hotel<Chamber>::sortChambers() { sort(chambers.begin(), chambers.end(), sortRooms); } template<class Chamber> Chamber* Hotel<Chamber>::removeChamber(std::string code, int floor) { for (typename std::vector<Chamber*>::const_iterator it = chambers.begin(); it != chambers.end(); it++) { if ((*it)->getCode() == code && (*it)->getFloor() == floor) { Chamber* temp = *it; chambers.erase(it); return temp; } } throw NoSuchChamberException(); } template<class Chamber> float Hotel<Chamber>::avgArea(int floor) const { float sum = 0; int n = 0; for (typename std::vector<Chamber*>::const_iterator it = chambers.begin(); it != chambers.end(); it++) { if ((*it)->getFloor() == floor) { sum += (*it)->getArea(); n++; } } if (sum == 0 && n == 0) { throw NoSuchFloorException(floor); } return sum/n; } template<class Chamber> bool Hotel<Chamber>::doReservation(std::string code, int floor) { for (typename std::vector<Chamber*>::const_iterator it = chambers.begin(); it != chambers.end(); it++) { if ((*it)->getCode() == code && (*it)->getFloor() == floor) { if ((*it)->getReservation() == false) { (*it)->setReservation(true); reservationsDone.push_back(*(*it)); return true; } } } return false; } template<class Chamber> std::list<Chamber> Hotel<Chamber>::roomsNeverReserved() const { std::list<Chamber> res; bool hasBeen; typename std::vector<Chamber*>::const_iterator i; typename std::list<Chamber>::const_iterator j; for (i = chambers.begin(); i != chambers.end(); i++) { hasBeen = false; for (j = reservationsDone.begin(); j != reservationsDone.end(); j++) { if ((*j).getCode() == (*i)->getCode() && (*j).getFloor() == (*i)->getFloor()) { hasBeen = true; } } if (!hasBeen) { res.push_back(*(*i)); hasBeen = false; } } return res; } #endif /* SRC_HOTEL_H_ */ <file_sep>var searchData= [ ['invaliddate_53',['InvalidDate',['../class_invalid_date.html',1,'']]], ['invalidnumfloors_54',['InvalidNumFloors',['../class_invalid_num_floors.html',1,'']]], ['invalidtime_55',['InvalidTime',['../class_invalid_time.html',1,'']]], ['isbusy_56',['isBusy',['../class_service_provider.html#a1d55c2846995532a8a387e885313d48c',1,'ServiceProvider']]] ]; <file_sep>/* * FEUPConsulting.h * * Created on: 10/12/2017 * Author: CS */ #ifndef SRC_FEUPCONSULTING_H_ #define SRC_FEUPCONSULTING_H_ #include "BST.h" #include <vector> #include <unordered_set> #include <queue> #include "Expertize.h" #include "Student.h" #include "Project.h" using namespace std; struct StudentPtrHash { int operator()(const StudentPtr &student) const { int hash = 0; for (auto ix = student.getEMail().length(); ix++) { hash = 37 * hash + student.getEMail()[ix]; } return hash; /* //original resolution from https://github.com/andrefmrocha return (student.getEMail().size() * student.getName().size())%50; */ } bool operator()(const StudentPtr &student1, const StudentPtr &student2) const { return (student1.getEMail() == student2.getEMail()); /* //original resolution from https://github.com/andrefmrocha return student1.getEMail() == student2.getEMail(); */ } }; typedef unordered_set <StudentPtr, StudentPtrHash, StudentPtrHash> HashTabStudentPtr; class FEUPConsulting { vector<Project *> projects; BST<Expertize> expertizes; HashTabStudentPtr students; priority_queue <Student> activeStudents; public: FEUPConsulting(); FEUPConsulting(vector<Project *> projects); void addProjects(vector<Project *> projects); vector<Project *> getProjects() const; // Part I - BST Expertize getExpertize(string name, unsigned cost); void addNewExpertize(const Expertize &expertize1); void addProject(Project *project); BST<Expertize> getExpertizes() const; // Part II - Hash Table vector <StudentPtr> getStudents() const; void setStudents(vector <StudentPtr> &newStudents); // Part III - Priority Queue priority_queue <Student> getActiveStudents() const; void setActiveStudents(priority_queue <Student> &students); // TODO: Implement methods below... // Part I - BST /* A */ void addAvailability(Student *student, string expertize, unsigned cost); /* B */ vector<Student *> getCandidateStudents(Project *book) const; /* C */ bool assignProjectToStudent(Project *project, Student *student); // Part II - Hash Table /* D */ void addStudent(Student *user); /* E */ void changeStudentEMail(Student *student, string newEMail); // Part III - Piority Queue /* F */ void addActiveStudents(const vector <Student> &candidates, int min); /* G */ int mostActiveStudent(Student &studentMaximus); }; #endif /* SRC_FEUPCONSULTING_H_ */ <file_sep>#include "fleet.h" #include <string> using namespace std; void Fleet::addVehicle(Vehicle *v1) { vehicles.push_back(v1); } int Fleet::numVehicles() const { return vehicles.size(); } int Fleet::lowestYear() const { if (numVehicles() == 0) return 0; // there is no vehicle int lowest = 3000; for (int i = 0; i < numVehicles(); i++) { if (vehicles[i]->getYear() < lowest) { lowest = vehicles[i]->getYear(); } } return lowest; } float Fleet::totalTax() const { float total = 0; for (int i = 0; i < numVehicles(); i++) { total += vehicles[i]->calculateTax(); } return total; } unsigned Fleet::removeOldVehicles(int y1) { vector<Vehicle *> vehiclesUpdated; unsigned removed; for (int i = 0; i < numVehicles(); i++) { if (vehicles[i]->getYear() > y1) vehiclesUpdated.push_back(vehicles[i]); } removed = numVehicles() - vehiclesUpdated.size(); vehicles.clear(); for (int i = 0; i < vehiclesUpdated.size(); i++) vehicles.push_back(vehiclesUpdated[i]); return removed; } vector<Vehicle *> Fleet::getVehicles() const { return vehicles; } vector<Vehicle *> Fleet::operator()(int y1) const { vector<Vehicle *> v; for (size_t i = 0; i < numVehicles(); i++) { if (vehicles[i]->getYear() == y1) v.push_back(vehicles[i]); } return v; } ostream & operator<<(ostream & o, const Fleet & f) { for (int i = 0; i < f.numVehicles(); i++) { f.vehicles[i]->info(o); } return o; }<file_sep>// CSimpleList - Implementacao Simples de Lista Ligada #include <iostream> #include <string> using namespace std; class CNode{ private: int d_data; CNode *d_next; public: CNode(int data, CNode *next){ d_data=data; d_next=next; } void setData(int data) { d_data=data; } void setNext(CNode *next) { d_next=next; } int data() const { return d_data;} CNode *next() const { return d_next;} void print() const { cout << d_data << " ";} }; class CSimpleList { private: CNode *first; public: CSimpleList() { first=0; } ~CSimpleList() { CNode *aux=first; CNode *cur; while(aux!=0) { cur = aux; aux = aux->next(); delete cur; } } bool empty() const { return (first==0); } string toStr() const { stringstream oss; CNode *aux=first; while(aux!=0) { oss << aux->data() << " "; aux=aux->next(); } return oss.str(); } void print() const { CNode *aux=first; cout << "List: "; while(aux!=0) { aux->print(); aux=aux->next(); } cout << endl; } CNode *find(int elem) { CNode *aux = first; while(aux!=0 && aux->data()!=elem) aux=aux->next(); if(aux!=0) return aux; else { cerr << "Elem is not in list\n"; return 0;} } void insert_head(int elem){ CNode *res = new CNode(elem, first); first = res; } void insert_end(int elem){ CNode *node, *aux; node = new CNode(elem,0); aux = first; if(aux==0) first=node; else { while(aux->next()!=0) aux = aux->next(); aux->setNext(node); } } void insert_sort(int elem) { CNode *prev, *node, *aux; node = new CNode(elem,0); prev = 0; aux = first; while(aux!=0 && aux->data()<elem) { prev = aux; aux = aux->next();} node->setNext(aux); if(prev==NULL) first=node; else prev->setNext(node); } void intercalar(const CSimpleList &lst) { //Grupo 2 c) CNode* b = lst.first; CNode* a = first; //if *this is empty, *this will end up equal to lst //if lst is empty, *this will remain equal while (true) { if (b != 0) { CNode* toInsert = new CNode(b->data(), a->next()); //the node to be inserted has the same data as the one from lst and points to the next of the original *this a->setNext(toInsert); b = b->next(); //'b' now points to the next element of lst that we will be inserting in *this } if (a != 0) { a = a->next(); //'a' now points to the element from lst that we have just inserted, 'b' if (a != 0) { a = a->next(); //'a' now points to the next element of the original *this } } if (a == 0 && b == 0) { //we finished traversing both lists so we can't do anything else break; } } } int zipar() { //Grupo 2 d) CNode* node = first; CNode* nextNode = node; int counter = 0; while (true) { if (node != 0) { while (true) { nextNode = nextNode->next(); if (nextNode != 0) { if (nextNode->data() == node->data()) counter++; else break; } else break; } node->setNext(nextNode); node = node->next(); if (node == 0) break; } else break; } return counter; } }; <file_sep>#include "game.h" #include <cstdlib> #include <ctime> #include <iostream> #include <algorithm> #include <vector> using namespace std; unsigned int Game::numberOfWords(string phrase) { if ( phrase.length() == 0 ) return 0; unsigned n=1; size_t pos = phrase.find(' '); while (pos != string::npos) { phrase = phrase.substr(pos+1); pos = phrase.find(' '); n++; } return n; } Game::Game() { kids.clear(); } Game::Game(list<Kid>& l2) { kids = l2; } void Game::addKid(const Kid &k1) { kids.push_back(k1); } list<Kid> Game::getKids() const { return kids; } string Game::write() const { stringstream oss; for (list<Kid>::const_iterator it = kids.begin(); it != kids.end(); it++) { oss << it->write() << '\n'; } return oss.str(); } Kid& Game::loseGame(string phrase) { int nw = numberOfWords(phrase) - 1; //number of words list<Kid>::iterator it = kids.begin(); list<Kid>::iterator end = kids.end(); while (kids.size() > 1) { int p = nw % kids.size(); for (int i = 1; i <= p ; i++) { it++; if (it == end) it = kids.begin(); //reached the last element but continues at the other end } it = kids.erase(it); if (it == end) it = kids.begin(); //in the next iteration it will start counting from the first element } return *it; } list<Kid>& Game::reverse() { kids.reverse(); return kids; } list<Kid> Game::removeOlder(unsigned id) { list<Kid> kidsCopy(kids.begin(), kids.end()); list<Kid> removed; kids.clear(); for (list<Kid>::const_iterator it = kidsCopy.begin(); it != kidsCopy.end(); it++) { if((*it).getAge() > id) { removed.push_back(*it); } else { kids.push_back(*it); } } return removed; } void Game::setKids(const list<Kid>& l1) { this->kids = l1; } bool Game::operator==(Game& g2) { if (kids.size() != g2.kids.size()) return false; list<Kid>::iterator itg2 = g2.kids.begin(); for (list<Kid>::const_iterator itg1 = kids.begin(); itg1 != kids.end(); itg1++) { if (!((*itg1)==(*itg2))) { return false; } else { itg2++; } } return true; } list<Kid> Game::shuffle() const { vector<Kid> kidsVector; for (list<Kid>::const_iterator it = kids.begin(); it != kids.end(); it++) { kidsVector.push_back(*it); } random_shuffle(kidsVector.begin(), kidsVector.end()); list<Kid> shuffledKids; for (vector<Kid>::const_iterator it = kidsVector.begin(); it != kidsVector.end(); it++) { shuffledKids.push_back(*it); } return shuffledKids; } <file_sep>#include "game.h" #include <sstream> //TODO ostream &operator << (ostream &os, Circle &c1) { return os; } Game::Game(int h, vector<int> &points, vector<bool> &states) { game = build(h, 0, points, states); } BinaryTree<Circle> Game::build(int h, int n, vector<int> &points, vector<bool> &states) { Circle c(points[n], states[n]); if(h == 0) { return BinaryTree<Circle>(c); } BinaryTree<Circle> left = build(h - 1, 2 * n + 1, points, states); BinaryTree<Circle> right = build(h - 1, 2 * n + 2, points, states); return BinaryTree<Circle>(c, left, right); } string Game::writeGame() { stringstream stream; BTItrLevel<Circle> it(game); while (!it.isAtEnd()) { stream << it.retrieve().getPoints() << '-'; if (it.retrieve().getState()) { stream << "true-"; } else { stream << "false-"; } stream << it.retrieve().getNVisits() << '\n'; it.advance(); } return stream.str(); } int Game::move() { BTItrLevel<Circle> it(game); int current = 1, next = 1, points = 0; while(!it.isAtEnd()) { if (current == next) { if (it.retrieve().getState()) { next = 2 * it.retrieve().getPoints() + 1; //true -> go to the right } else { next = 2 * it.retrieve().getPoints(); //false -> go to the left } it.retrieve().changeState(); it.retrieve().addVisit(); points = it.retrieve().getPoints(); } current++; it.advance(); } return points; } int Game::mostVisited() { int max = 0; BTItrLevel<Circle> it(game); it.advance(); //the root does not count while(!it.isAtEnd()) { if (it.retrieve().getNVisits() > max) { max = it.retrieve().getNVisits(); } it.advance(); } return max; } <file_sep>var searchData= [ ['notanentrepreneur_66',['NotAnEntrepreneur',['../class_not_an_entrepreneur.html',1,'']]], ['notaserviceprovider_67',['NotAServiceProvider',['../class_not_a_service_provider.html',1,'']]], ['numreviews_68',['numReviews',['../class_employee.html#a0580ae486a9a2b82a452f2cc6d649f52',1,'Employee']]] ]; <file_sep>#include "REAgency.h" REAgency::REAgency(): catalogItems(PropertyTypeItem("", "","", 0)) { //do nothing! } REAgency::REAgency(vector<Property*> properties): catalogItems(PropertyTypeItem("", "","", 0)) { this->properties = properties; } void REAgency::addProperty(Property* property) { this->properties.push_back(property); } void REAgency::addProperties(vector<Property*> properties) { this->properties = properties; } vector<Property*> REAgency::getProperties() const{ return this->properties; } PropertyTypeItem REAgency::getTypeItem(string address, string postalCode, string typology) { PropertyTypeItem itemNotFound("", "", "", 0); BSTItrIn<PropertyTypeItem> it(catalogItems); while (!it.isAtEnd()) { if( it.retrieve().getAddress() == address && it.retrieve().getPostalCode() == postalCode && it.retrieve().getTypology() == typology) { PropertyTypeItem pti(it.retrieve().getAddress(), it.retrieve().getPostalCode(), it.retrieve().getTypology(), 0); pti.setItems(it.retrieve().getItems()); return pti; } it.advance(); } return itemNotFound; } void REAgency::addTypeItem(Property* property) { PropertyTypeItem itemNotFound("", "","", 0); PropertyTypeItem pti(property->getAddress(), property->getPostalCode(), property->getTypology(), property-> getPrice()); PropertyTypeItem ptiX = catalogItems.find(pti); if(ptiX == itemNotFound) { pti.addItems(property); this->catalogItems.insert(pti); } else { this->catalogItems.remove(ptiX); ptiX.addItems(property); this->catalogItems.insert(ptiX); } properties.push_back(property); } BST<PropertyTypeItem> REAgency::getTypeItems() const { return this->catalogItems; } vector<ClientRecord> REAgency::getClientRecords() const { vector<ClientRecord> records; HashTabClientRecord::const_iterator it1 = this->listingRecords.begin(); HashTabClientRecord::const_iterator it2 = this->listingRecords.end(); for(; it1 != it2; it1++) { records.push_back(*it1); } return records; } void REAgency::setClientRecords(vector<ClientRecord>& crs) { for(unsigned int i = 0; i < crs.size(); i++) { listingRecords.insert(crs[i]); } } priority_queue<Client> REAgency::getClientProfiles() const { return clientProfiles; } void REAgency::setClientProfiles(priority_queue<Client>& profiles) { clientProfiles = profiles; } // // TODO: Part I - BST // void REAgency::generateCatalog() { bool found; for (auto it = properties.begin(); it != properties.end(); it++) { found = false; PropertyTypeItem newCatalog((*it)->getAddress(),(*it)->getPostalCode(), (*it)->getTypology(), (*it)->getPrice()); newCatalog.addItems(*it); BSTItrIn<PropertyTypeItem> iter(catalogItems); while (!iter.isAtEnd()) { if (iter.retrieve() == newCatalog) { iter.retrieve().addItems(*it); found = true; break; } iter.advance(); } if (!found) { catalogItems.insert(newCatalog); } } } vector<Property*> REAgency::getAvailableProperties(Property* property) const { vector<Property*> available; for (auto itr = properties.begin(); itr != properties.end(); itr++) { if ((*itr)->getAddress() == property->getAddress() && (*itr)->getPostalCode() == property->getPostalCode() && (*itr)->getTypology() == property->getTypology() && (*itr)->getReservation() == tuple<Client*, int>()) { available.push_back((*itr)); } } return available; } bool REAgency::reservePropertyFromCatalog(Property* property, Client* client, int percentage) { PropertyTypeItem catalogToSearch(property->getAddress(), property->getPostalCode(), property->getTypology(), property->getPrice()); BSTItrIn<PropertyTypeItem> itr(catalogItems); while(!itr.isAtEnd()) { if (itr.retrieve() == catalogToSearch) { for (auto p = itr.retrieve().getItems().begin(); p != itr.retrieve().getItems().end(); p++) { if (get<0>((*p)->getReservation()) == NULL) { int offer = (*p)->getPrice() * (1.0 - ((float)percentage / 100.0)); tuple<Client*, int> reservation(client, offer); (*p)->setReservation(reservation); client->addVisiting((*p)->getAddress(), (*p)->getPostalCode(), (*p)->getTypology(), to_string((*p)->getPrice())); return true; } } } itr.advance(); } return false; } // // TODO: Part II - Hash Table // void REAgency::addClientRecord(Client* client) { listingRecords.insert(client); } void REAgency::deleteClients() { auto it = listingRecords.begin(); while (it != listingRecords.end()) { if (it->getClientPointer()->getVisitedProperties().empty()) { it = listingRecords.erase(it); } it++; } } // // TODO: Part III - Priority Queue // void REAgency::addBestClientProfiles(const vector<Client>candidates, int min) { for (auto c = candidates.begin(); c != candidates.end(); c++) { float ratio = 0; for (auto p = properties.begin(); p != properties.end(); p++) { if (get<0>((*p)->getReservation())->getEMail() == c->getEMail()) { ratio++; } } ratio = ratio / (*c).getVisitedProperties().size(); if (ratio > min) { clientProfiles.push((*c)); } } } vector<Property*> REAgency::suggestProperties() { vector<Property*> suggestedProperties; priority_queue<Client> tempProfiles = clientProfiles; while (!tempProfiles.empty()) { Client currProfile = tempProfiles.top(); tempProfiles.pop(); if (currProfile.getVisiting() == tuple<string, string, string, string>()) { continue; //client has never visited any property } int minPCDiff = 9999999; int lastVisitedPC = stoi(get<1>(currProfile.getVisiting())); Property* propertyToSuggest; for (auto it = properties.begin(); it != properties.end(); it++) { if (get<0>((*it)->getReservation()) == NULL) { //the property to be suggested can not be reserved int currPCDiff = abs(stoi((*it)->getPostalCode()) - lastVisitedPC); if (currPCDiff != 0 && currPCDiff < minPCDiff) { //need to make sure currPCDiff != 0 otherwise could be suggesting the last visited property propertyToSuggest = *it; minPCDiff = currPCDiff; } } } suggestedProperties.push_back(propertyToSuggest); } return suggestedProperties; } <file_sep>var searchData= [ ['notanentrepreneur_133',['NotAnEntrepreneur',['../class_not_an_entrepreneur.html',1,'']]], ['notaserviceprovider_134',['NotAServiceProvider',['../class_not_a_service_provider.html',1,'']]] ]; <file_sep>#include "parque.h" #include <vector> using namespace std; ParqueEstacionamento::ParqueEstacionamento(unsigned int lot, unsigned int nMaxCli): lotacao (lot), numMaximoClientes(nMaxCli) { clientes.clear(); // o parque encontra-se inicialmente vazio vagas = lot; } bool ParqueEstacionamento::adicionaCliente(const string & nome) { if (clientes.size() == numMaximoClientes) return 0; // foi atingido o número máximo de clientes else{ InfoCartao novoCliente; novoCliente.nome = nome; novoCliente.presente = false; // o cliente está inicialmente fora do parque clientes.push_back(novoCliente); return 1; } } bool ParqueEstacionamento::retiraCliente(const string & nome) { for (size_t i = 0; i < clientes.size(); i++){ if (clientes[i].nome == nome){ // o cliente existe if (clientes[i].presente == false){ // e está fora do parque clientes.erase(clientes.begin() + i); return 1; } } } return 0; } bool ParqueEstacionamento::entrar(const string & nome) { if (vagas == 0) return 0; // não há lugares disponíveis no estacionamento int pos = posicaoCliente(nome); if (pos != -1) { // o cliente existe if (clientes[pos].presente == false) { // e está fora do parque clientes[pos].presente = true; vagas--; return 1; } } return 0; } bool ParqueEstacionamento::sair(const string & nome) { int pos = posicaoCliente(nome); if (pos != -1) { // o cliente existe if (clientes[pos].presente == true) { // e está dentro do parque clientes[pos].presente = false; vagas++; return 1; } } return 0; } int ParqueEstacionamento::posicaoCliente(const string & nome) const { for (size_t i = 0; i < clientes.size(); i++){ if(clientes[i].nome == nome) return i; } return -1; } unsigned ParqueEstacionamento::getNumLugares() const { return lotacao; } unsigned ParqueEstacionamento::getNumMaximoClientes() const { return numMaximoClientes; } unsigned ParqueEstacionamento::getNumLugaresOcupados() const { return (lotacao - vagas); } unsigned ParqueEstacionamento::getNumClientesAtuais() const { return clientes.size(); } <file_sep>var searchData= [ ['animal_6',['Animal',['../class_animal.html',1,'']]] ]; <file_sep>#include "packagingMachine.h" #include <sstream> PackagingMachine::PackagingMachine(int boxCap): boxCapacity(boxCap) {} unsigned PackagingMachine::numberOfBoxes() { return boxes.size(); } unsigned PackagingMachine::addBox(Box& b1) { boxes.push(b1); return boxes.size(); } HeapObj PackagingMachine::getObjects() const { return this->objects; } HeapBox PackagingMachine::getBoxes() const { return this->boxes; } unsigned PackagingMachine::loadObjects(vector<Object> &objs) { unsigned counter = 0; for (vector<Object>::iterator it = objs.begin(); it != objs.end(); it++) { if ((*it).getWeight() <= boxCapacity) { objects.push(*it); counter++; objs.erase(it); it--; //erase returns an iterator pointing to the new location of the element that followed the last element erased by the function call } } return counter; } Box PackagingMachine::searchBox(Object& obj) { Box b; bool found = false; vector<Box> temp; while (!boxes.empty()) { if (!found && boxes.top().getFree() >= obj.getWeight()) { b = boxes.top(); boxes.pop(); found = true; } else { temp.push_back(boxes.top()); boxes.pop(); } } if (!found) { b = Box(boxCapacity); } for (vector<Box>::iterator it = temp.begin(); it != temp.end(); it++) { boxes.push(*it); } temp.clear(); return b; } unsigned PackagingMachine::packObjects() { unsigned counter = 0; vector<Object> vecObjects; while (!objects.empty()) { vecObjects.push_back(objects.top()); objects.pop(); } for (vector<Object>::iterator o = vecObjects.begin(); o != vecObjects.end(); o++) { Box b = searchBox(*o); if (b.getFree() == boxCapacity) { //otherwise it means we are packing on a box where has already been packed an object counter++; } b.addObject(*o); boxes.push(b); vecObjects.erase(o); //packed objects are removed from the queue o--; } for (vector<Object>::iterator o = vecObjects.begin(); o != vecObjects.end(); o++) { objects.push(*o); } vecObjects.clear(); return counter; } string PackagingMachine::printObjectsNotPacked() const { if (objects.empty()) { return "No objects!\n"; } stringstream out; HeapObj temp = objects; while (!temp.empty()) { out << temp.top() << '\n'; temp.pop(); } return out.str(); } Box PackagingMachine::boxWithMoreObjects() const { if (boxes.empty()) { throw MachineWithoutBoxes(); } HeapBox temp = boxes; Box res; while (!temp.empty()) { if (temp.top().getSize() > res.getSize()) { res = temp.top(); } temp.pop(); } return res; }<file_sep>/* * ReadingClub.cpp * * Created on: 11/12/2016 * Author: RRossetti */ #include "ReadingClub.h" ReadingClub::ReadingClub() : catalogItems(BookCatalogItem("", "", 0)) { //do nothing! } ReadingClub::ReadingClub(vector<Book *> books) : catalogItems(BookCatalogItem("", "", 0)) { this->books = books; } void ReadingClub::addBook(Book *book) { this->books.push_back(book); } void ReadingClub::addBooks(vector<Book *> books) { this->books = books; } vector<Book *> ReadingClub::getBooks() const { return this->books; } BookCatalogItem ReadingClub::getCatalogItem(string title, string author) { BookCatalogItem itemNotFound("", "", 0); BSTItrIn<BookCatalogItem> it(catalogItems); while (!it.isAtEnd()) { if (it.retrieve().getTitle() == title && it.retrieve().getAuthor() == author) { BookCatalogItem bci(it.retrieve().getTitle(), it.retrieve().getAuthor(), 0); bci.setItems(it.retrieve().getItems()); return bci; } it.advance(); } return itemNotFound; } void ReadingClub::addCatalogItem(Book *book) { BookCatalogItem itemNotFound("", "", 0); BookCatalogItem bci(book->getTitle(), book->getAuthor(), book->getYear()); BookCatalogItem bciX = catalogItems.find(bci); if (bciX == itemNotFound) { bci.addItems(book); this->catalogItems.insert(bci); } else { this->catalogItems.remove(bciX); bciX.addItems(book); this->catalogItems.insert(bciX); } books.push_back(book); } BST<BookCatalogItem> ReadingClub::getCatalogItems() const { return this->catalogItems; } vector <UserRecord> ReadingClub::getUserRecords() const { vector <UserRecord> records; HashTabUserRecord::const_iterator it1 = this->userRecords.begin(); HashTabUserRecord::const_iterator it2 = this->userRecords.end(); for (; it1 != it2; it1++) { records.push_back(*it1); } return records; } void ReadingClub::setUserRecords(vector <UserRecord> &urs) { for (int i = 0; i < urs.size(); i++) userRecords.insert(urs[i]); } priority_queue <User> ReadingClub::getBestReaderCandidates() const { return readerCandidates; } void ReadingClub::setBestReaderCandidates(priority_queue <User> &candidates) { readerCandidates = candidates; } // // TODO: Part I - BST // void ReadingClub::generateCatalog() { for (auto b = books.begin(); b != books.end(); b++) { BSTItrIn<BookCatalogItem> itr(catalogItems); BookCatalogItem newCatalog((*b)->getTitle(), (*b)->getAuthor(), (*b)->getYear()); while (!itr.isAtEnd()) { if (itr.retrieve().getTitle() == (*b)->getTitle() && itr.retrieve().getAuthor() == (*b)->getAuthor()) { newCatalog = itr.retrieve(); catalogItems.remove(itr.retrieve()); break; } } newCatalog.addItems((*b)); catalogItems.insert(newCatalog); } /* //original resolution from https://github.com/andrefmrocha BookCatalogItem null("", "", 0); for(auto i: this->books) { BookCatalogItem newCat(i->getTitle(), i->getAuthor(), i->getYear()); BookCatalogItem find = this->catalogItems.find(newCat); if(find == null) { newCat.addItems(i); this->catalogItems.insert(newCat); } else { find.addItems(i); this->catalogItems.remove(newCat); this->catalogItems.insert(find); } } */ } vector<Book *> ReadingClub::getAvailableItems(Book *book) const { BSTItrIn<BookCatalogItem> itr(catalogItems); vector < Book * > available; while (!itr.isAtEnd()) { if (itr.retrieve().getTitle() == book->getTitle() && itr.retrieve().getAuthor() == book->getAuthor()) { for (auto b = itr.retrieve().getItems().begin(); b != itr.retrieve().getItems().end(); b++) { if ((*b)->getReader() == NULL) { available.push_back((*b)); } } break; } } return available; /* //original resolution from https://github.com/andrefmrocha vector<Book*> temp; BSTItrIn<BookCatalogItem> it(this->catalogItems); while(!it.isAtEnd()) { if(it.retrieve().getAuthor() == book->getAuthor() && it.retrieve().getTitle() == book->getTitle()) { for(auto i: it.retrieve().getItems()) { if(i->getReader() == NULL) { temp.push_back(i); } } } it.advance(); } return temp; */ } bool ReadingClub::borrowBookFromCatalog(Book *book, User *reader) { BSTItrIn<BookCatalogItem> itr(catalogItems); vector < Book * > available; while (!itr.isAtEnd()) { if (itr.retrieve().getTitle() == book->getTitle() && itr.retrieve().getAuthor() == book->getAuthor()) { for (auto b = itr.retrieve().getItems().begin(); b != itr.retrieve().getItems().end(); b++) { if ((*b)->getReader() == NULL) { (*b)->setReader(reader); reader->addReading(book->getTitle(), book->getAuthor()); return true; } } } } return false; /* //original resolution from https://github.com/andrefmrocha vector<Book *> books = this->getAvailableItems(book); if(books.size() == 0) return false; reader->addReading(book->getTitle(), book->getAuthor()); books[0]->setReader(reader); return true; */ } // // TODO: Part II - Hash Table // void ReadingClub::addUserRecord(User *user) { this->userRecords.insert(user); } void ReadingClub::changeUserEMail(User *user, string newEMail) { userRecords.erase(user); user->setEMail(newEMail); userRecords.insert(user); /* //original resolution from https://github.com/andrefmrocha for(auto i: this->userRecords) { if(i.getEMail() == user->getEMail()) { this->userRecords.erase(i); user->setEMail(newEMail); this->addUserRecord(user); return; } } */ } // // TODO: Part III - Priority Queue // void ReadingClub::addBestReaderCandidates(const vector <User> &candidates, int min) { for (auto it = candidates.begin(); it != candidates.end(); it++) { if (it->getReadings().size() > min) { readerCandidates.push(it); } } /* //original resolution from https://github.com/andrefmrocha for(auto i: candidates) { if(i.getReadings().size() + 1>= min) this->readerCandidates.push(i); } */ } int ReadingClub::awardReaderChampion(User &champion) { if (readerCandidates.empty()) { return 0; } priority_queue <User> aux = readerCandidates; User winner = aux.top(); aux.pop(); if (aux.top().getReadings().size() == winner.getReadings().size()) { return 0; } champion = winner; return aux.size(); /* //original resolution from https://github.com/andrefmrocha if(this->readerCandidates.size() == 0) return 0; priority_queue<User> copy = this->readerCandidates; User champ = copy.top(); copy.pop(); if(champ.getReadings().size() == copy.top().getReadings().size()) return 0; champion = champ; return copy.size() + 1; */ } <file_sep>var searchData= [ ['employee_120',['Employee',['../class_employee.html',1,'']]], ['employeedoesnotexist_121',['EmployeeDoesNotExist',['../class_employee_does_not_exist.html',1,'']]], ['employeehasnotuncompletedtasks_122',['EmployeeHasNotUncompletedTasks',['../class_employee_has_not_uncompleted_tasks.html',1,'']]], ['employeeisbusy_123',['EmployeeIsBusy',['../class_employee_is_busy.html',1,'']]], ['employeenotassociatedtoclient_124',['EmployeeNotAssociatedToClient',['../class_employee_not_associated_to_client.html',1,'']]], ['entrepreneur_125',['Entrepreneur',['../class_entrepreneur.html',1,'']]] ]; <file_sep>#include "ThinTallBox.h" #include "WideFlatBox.h" #include <algorithm> ThinTallBox::ThinTallBox(double capacity) : Box(capacity) { } ThinTallBox::ThinTallBox(double capacity, stack<Object> objects, double content_size) : Box(capacity) { this->objects = objects; this->setContentSize(content_size); } stack<Object> ThinTallBox::getObjects() const { return objects; } void ThinTallBox::remove(Object object) { Object next_object = next(); if(!(next_object == object)) { throw InaccessibleObjectException(object); } else { setContentSize(getContentSize()-next_object.getSize()); objects.pop(); } } const Object& ThinTallBox::next() const { return objects.top(); } void ThinTallBox::insert(Object object) { if (getContentSize() + object.getSize() <= getCapacity()) { objects.push(object); setContentSize(getContentSize() + object.getSize()); } else { throw ObjectDoesNotFitException(); } } void ThinTallBox::sortObjects() { vector<Object> vec; while (!objects.empty()) { vec.push_back(objects.top()); objects.pop(); } sort(vec.begin(),vec.end()); for (vector<Object>::iterator it = vec.begin(); it != vec.end(); it++) { objects.push((*it)); } } <file_sep>var searchData= [ ['zoo_5',['Zoo',['../class_zoo.html',1,'']]] ]; <file_sep>#include "Warehouse.h" #include <algorithm> Warehouse::Warehouse() { } queue<ThinTallBox> Warehouse::getBoxes() { return boxes; } queue<Object> Warehouse::getObjects() { return objects; } void Warehouse::setBoxes(queue<ThinTallBox> q) { while (!q.empty()) { boxes.push(q.front()); q.pop(); } } void Warehouse::addObject(Object o1) { objects.push(o1); } int Warehouse::InsertObjectsInQueue(vector <Object> obj){ sort(obj.begin(), obj.end()); for (vector<Object>::iterator it = obj.begin(); it != obj.end(); it++) { objects.push((*it)); } obj.size(); } Object Warehouse::RemoveObjectQueue(int maxSize){ vector<Object> vec; Object obj("dummy", maxSize); bool first = true; while (!objects.empty()) { vec.push_back(objects.front()); objects.pop(); } for (vector<Object>::iterator it = vec.begin(); it != vec.end(); it++) { if ((*it).getSize() <= maxSize) { if (first) { obj = (*it); first = false; } else { objects.push((*it)); } } else { objects.push((*it)); } } return obj; } int Warehouse::addPackOfBoxes(vector <ThinTallBox> boV) { for (vector<ThinTallBox>::iterator it = boV.begin(); it != boV.end(); it++) { boxes.push((*it)); } return boxes.size(); } vector<ThinTallBox> Warehouse::DailyProcessBoxes(){ vector<ThinTallBox> vecBox; vector<ThinTallBox> dispatched; while (!boxes.empty()) { vecBox.push_back(boxes.front()); boxes.pop(); } for (vector<ThinTallBox>::iterator b = vecBox.begin(); b != vecBox.end(); b++) { if ((*b).full()) { //caixa cheia - despachada dispatched.push_back((*b)); } else if ((*b).getDays() == 0) { //data de envio expirou - processada e despachada if ((*b).full()) { dispatched.push_back((*b)); } else { vector<Object> vecObj; while (!objects.empty()) { vecObj.push_back(objects.front()); objects.pop(); } Object obj("dummy", 0); bool processed = false; for (vector<Object>::iterator o = vecObj.begin(); o != vecObj.end(); o++) { if ((*b).getContentSize() + (*o).getSize() <= (*b).getCapacity()) { if (!processed) { (*b).insert((*o)); (*b).setContentSize((*b).getContentSize() + (*o).getSize()); processed = true; } else { objects.push((*o)); } } else { objects.push((*o)); } } if (!processed) { (*b).insert(obj); } dispatched.push_back((*b)); } } else { //processada e movida para o final da fila, decrementando o prazo de envio vector<Object> vecObj; while (!objects.empty()) { vecObj.push_back(objects.front()); objects.pop(); } Object obj("dummy", 0); bool processed = false; for (vector<Object>::iterator o = vecObj.begin(); o != vecObj.end(); o++) { if ((*b).getContentSize() + (*o).getSize() <= (*b).getCapacity()) { if (!processed) { (*b).insert((*o)); (*b).setContentSize((*b).getContentSize() + (*o).getSize()); processed = true; } else { objects.push((*o)); } } else { objects.push((*o)); } } if (!processed) { (*b).insert(obj); } (*b).setDaysToSend((*b).getDays() - 1); boxes.push((*b)); } } return dispatched; }<file_sep>var searchData= [ ['employees_226',['employees',['../class_pitch.html#a61a22220780b39ac8ebbb8c709a498d2',1,'Pitch']]], ['employeesfile_227',['employeesFile',['../class_pitch.html#ab9c6d184cfe0d871af5052dfb5035a35',1,'Pitch']]] ]; <file_sep>var searchData= [ ['dog_8',['Dog',['../class_dog.html',1,'']]] ]; <file_sep>var indexSectionsWithContent = { 0: "acdegilmnoprstu", 1: "cdeilmnpstu", 2: "acgiloprst", 3: "celnt" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "functions", 3: "variables" }; var indexSectionLabels = { 0: "All", 1: "Classes", 2: "Functions", 3: "Variables" }; <file_sep>#ifndef PLAYER_H_ #define PLAYER_H_ #include "bet.h" #include <string> using namespace std; struct betHash { //the bets are hashed by the sum of their numbers //i could have defined any other hash function int operator() (const Bet& b) const { return b.getHash(); } bool operator() (const Bet& b1, const Bet& b2) const { if (b1.getHash() != b2.getHash()) { return false; //they are certainly not equal } //if the bets have the same hash number, they might be equal or not if (b1.getNumbers() == b2.getNumbers()) { return true; } } }; typedef unordered_set<Bet, betHash, betHash> tabHBet; class Player { tabHBet bets; string name; public: Player(string nm="anonymous") { name=nm; } void addBet(const Bet & ap); unsigned betsInNumber(unsigned num) const; tabHBet drawnBets(const tabHInt& draw) const; unsigned getNumBets() const { return bets.size(); } }; #endif <file_sep>#include "player.h" void Player::addBet(const Bet& b) { bets.insert(b); } unsigned Player::betsInNumber(unsigned num) const { unsigned int counter = 0; for (tabHBet::const_iterator it = bets.begin(); it != bets.end(); it++) { if ((*it).contains(num)) { counter++; } } return counter; } tabHBet Player::drawnBets(const tabHInt& draw) const { tabHBet awarded; for (tabHBet::const_iterator it = bets.begin(); it != bets.end(); it++) { if ((*it).countRights(draw) > 3) { awarded.insert(*it); } } return awarded; } <file_sep>#include "animal.h" #include <sstream> using namespace std; int Animal::youngest = 10000; int Animal::getYoungest() { return youngest; } Animal::Animal(string name, int age) { this->name = name; this->age = age; this->vet = 0; if (age < youngest) youngest = age; } Dog::Dog(string name, int age, string breed) : Animal(name, age) { this->breed = breed; } Flying::Flying(int maxv, int maxa) { maxAltitude = maxa; maxVelocity = maxv; } Bat::Bat(string name, int age, int maxv, int maxa) : Animal(name, age), Flying(maxv, maxa) { } string Animal::getName() const { return name; } int Animal::getAge() const { return age; } void Animal::setVeterinary(Veterinary *vet) { this->vet = vet; } Veterinary *Animal::getVeterinary() const { return vet; } bool Dog::isYoung() const { return age < 5; } bool Bat::isYoung() const { return age < 4; } string Animal::getInfo() const { stringstream info; info << name << ", " << age; if (vet != NULL) info << ", " << vet->getInfo(); return info.str(); } string Dog::getInfo() const { stringstream info; info << Animal::getInfo() << ", " << breed; return info.str(); } string Bat::getInfo() const { stringstream info; info << Animal::getInfo() << ", " << maxVelocity << maxAltitude; return info.str(); }<file_sep>var searchData= [ ['loadclients_181',['loadClients',['../class_pitch.html#a54d6dea506746ee78cceb4776bfbfc58',1,'Pitch']]], ['loademployees_182',['loadEmployees',['../class_pitch.html#a99247273e36e09d955c2021feab7bfff',1,'Pitch']]], ['loadlifts_183',['loadLifts',['../class_pitch.html#ad1d44612567d48d422beb436f1eb1052',1,'Pitch']]] ]; <file_sep>#include "zoo.h" #include <iostream> #include <sstream> #include <stdlib.h> using namespace std; unsigned Zoo::numAnimals() const { return animals.size(); } unsigned Zoo::numVeterinarians() const { return veterinarians.size();} void Zoo::addAnimal(Animal *a1) { animals.push_back(a1); } string Zoo::getInfo() const { stringstream info; string data = ""; for (unsigned int i = 0; i < numAnimals(); i++) { info << animals[i]->getInfo() << endl; } return info.str(); } bool Zoo::isYoung(string nameA) { for (unsigned int i = 0; i < numAnimals(); i++) { if (animals[i]->getName() == nameA) { return animals[i]->isYoung(); } } return false; } void Zoo::allocateVeterinarians(istream &isV) { string name, cod; while (!isV.eof()) { getline(isV, name); getline(isV, cod); long c = atoi(cod.c_str()); Veterinary *vet = new Veterinary(name, c); veterinarians.push_back(vet); } for (int i = 0; i < numAnimals(); i++) { animals[i]->setVeterinary(veterinarians[i % numVeterinarians()]); } } bool Zoo::removeVeterinary(string nameV) { for (unsigned int i = 0; i < numVeterinarians(); i++) { if (veterinarians[i]->getName() == nameV) { for (unsigned int j = 0; j < numAnimals(); j++) { if (animals[j]->getVeterinary() == veterinarians[i]) { animals[j]->setVeterinary(veterinarians[(i + 1) % veterinarians.size()]); } } veterinarians.erase(veterinarians.begin() + i); return true; } } return false; } bool Zoo::operator<(Zoo &zoo2) const { int agesZoo1 = 0, agesZoo2 = 0; for (int i = 0; i < numAnimals(); i++) { agesZoo1 += animals[i]->getAge(); } for (int i = 0; i < zoo2.numAnimals(); i++) { agesZoo2 += zoo2.animals[i]->getAge(); } return agesZoo1 < agesZoo2; }<file_sep>var searchData= [ ['client_7',['Client',['../class_client.html',1,'']]], ['clientdoesnotexist_8',['ClientDoesNotExist',['../class_client_does_not_exist.html',1,'']]], ['clientdoesnothaveanemployeeassociated_9',['ClientDoesNotHaveAnEmployeeAssociated',['../class_client_does_not_have_an_employee_associated.html',1,'']]], ['clients_10',['clients',['../class_pitch.html#a4f88464ae1447b4636af98f59ebda6ea',1,'Pitch']]], ['completeservicerequested_11',['completeServiceRequested',['../class_pitch.html#a6b9b714ef51fd9e62faec93ddc061ee9',1,'Pitch']]], ['completetask_12',['completeTask',['../class_service_provider.html#a156e8d34f4e6272f1bb0d4c526b64df2',1,'ServiceProvider']]], ['contractedemployee_13',['ContractedEmployee',['../class_contracted_employee.html',1,'']]] ]; <file_sep>/* * CinemaFinder.cpp */ #include "CinemaFinder.h" #include "Cinema.h" #include "Film.h" #include <algorithm> CinemaFinder::CinemaFinder() {} CinemaFinder::~CinemaFinder() {} void CinemaFinder::addFilm(Film *f1) { FilmPtr fp1; fp1.film = f1; films.insert(fp1); } void CinemaFinder::addCinema(const Cinema &c1) { cinemas.push(c1); } tabHFilm CinemaFinder::getFilms() const { return films; } priority_queue <Cinema> CinemaFinder::getCinemas() const { return cinemas; } // TODO //b1 list <string> CinemaFinder::filmsWithActor(string actorName) const { list <string> res; for (auto film : films) { for (auto actor : film->getActors()) { if (actor == actorName) { res.push_back(film->getTitle()); break; } } } return res; /* //original resolution from https://github.com/andrefmrocha list<string> res; for(auto i: this->films) { for(auto j: i.film->getActors()) { if(j == actorName) { res.push_back(i.film->getTitle()); break; } } } return res; */ } //b2 void CinemaFinder::addActor(string filmTitle, string actorName) { FilmPtr newFilm; newFilm.film = new Film(filmTitle); for (auto film : films) { if (film->getTitle() == filmTitle) { newFilm = film; films.erase(film); break; } } newFilm.film->addActor(actorName); filmes.insert(newFilm); /* //original resolution from https://github.com/andrefmrocha for(auto i: this->films) { if(i.film->getTitle() == filmTitle) { FilmPtr film = i; this->films.erase(i); film.film->addActor(actorName); this->films.insert(film); return; } } FilmPtr film; film.film = new Film(filmTitle); film.film->addActor(actorName); this->films.insert(film); */ } //c1 string CinemaFinder::nearestCinema(string service1) const { priority_queue <Cinema> aux = cinemas; while (!aux.empty()) { for (auto s = aux.top().getServices().begin(); s != aux.top().getServices().end(); s++) { if ((*s) == service1) { return aux.top().getName(); } } aux.pop(); } return ""; /* //original resolution from https://github.com/andrefmrocha priority_queue<Cinema> copy = this->cinemas; while(!copy.empty()) { for(auto i: copy.top().getServices()) { if(i == service1) return copy.top().getName(); } copy.pop(); } return ""; */ } //c2 void CinemaFinder::addServiceToNearestCinema(string service1, unsigned maxDistance) { if (cinemas.empty()) { throw CinemaNotFound(); } Cinema nearest = cinemas.top(); if (nearest.getDistance() > maxDistance) { throw CinemaNotFound(); } nearest.addService(service1); cinemas.pop(); cinemas.push(nearest); /* //original resolution from https://github.com/andrefmrocha if(this->cinemas.empty()) throw(CinemaNotFound()); Cinema nearest = this->cinemas.top(); if(nearest.getDistance() > maxDistance) throw(CinemaNotFound()); nearest.addService(service1); this->cinemas.pop(); this->cinemas.push(nearest); */ } <file_sep># CMAKE generated file: DO NOT EDIT! # Generated by "MinGW Makefiles" Generator, CMake Version 3.17 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Disable VCS-based implicit rules. % : %,v # Disable VCS-based implicit rules. % : RCS/% # Disable VCS-based implicit rules. % : RCS/%,v # Disable VCS-based implicit rules. % : SCCS/s.% # Disable VCS-based implicit rules. % : s.% .SUFFIXES: .hpux_make_needs_suffix_list # Command-line flag to silence nested $(MAKE). $(VERBOSE)MAKESILENT = -s # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. SHELL = cmd.exe # The CMake executable. CMAKE_COMMAND = "C:\Program Files\JetBrains\CLion 2020.2.3\bin\cmake\win\bin\cmake.exe" # The command to remove a file. RM = "C:\Program Files\JetBrains\CLion 2020.2.3\bin\cmake\win\bin\cmake.exe" -E rm -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = "C:\Users\<NAME>\Desktop\UNI - 2nd year, 1st semester\AEDA\aeda2021_p01" # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = "C:\Users\Margarida Viera\Desktop\UNI - 2nd year, 1st semester\AEDA\aeda2021_p01\cmake-build-debug" #============================================================================= # Targets provided globally by CMake. # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." "C:\Program Files\JetBrains\CLion 2020.2.3\bin\cmake\win\bin\cmake.exe" -E echo "No interactive CMake dialog available." .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." "C:\Program Files\JetBrains\CLion 2020.2.3\bin\cmake\win\bin\cmake.exe" --regenerate-during-build -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start "C:\Users\<NAME>\Desktop\UNI - 2nd year, 1st semester\AEDA\aeda2021_p01\cmake-build-debug\CMakeFiles" "C:\Users\<NAME>\Desktop\UNI - 2nd year, 1st semester\AEDA\aeda2021_p01\cmake-build-debug\CMakeFiles\progress.marks" $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start "C:\Users\<NAME>\Desktop\UNI - 2nd year, 1st semester\AEDA\aeda2021_p01\cmake-build-debug\CMakeFiles" 0 .PHONY : all # The main clean target clean: $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles\Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named aeda2021_p01 # Build rule for target. aeda2021_p01: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles\Makefile2 aeda2021_p01 .PHONY : aeda2021_p01 # fast build rule for target. aeda2021_p01/fast: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/build .PHONY : aeda2021_p01/fast Tests/parque.obj: Tests/parque.cpp.obj .PHONY : Tests/parque.obj # target to build an object file Tests/parque.cpp.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/Tests/parque.cpp.obj .PHONY : Tests/parque.cpp.obj Tests/parque.i: Tests/parque.cpp.i .PHONY : Tests/parque.i # target to preprocess a source file Tests/parque.cpp.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/Tests/parque.cpp.i .PHONY : Tests/parque.cpp.i Tests/parque.s: Tests/parque.cpp.s .PHONY : Tests/parque.s # target to generate assembly for a file Tests/parque.cpp.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/Tests/parque.cpp.s .PHONY : Tests/parque.cpp.s Tests/tests.obj: Tests/tests.cpp.obj .PHONY : Tests/tests.obj # target to build an object file Tests/tests.cpp.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/Tests/tests.cpp.obj .PHONY : Tests/tests.cpp.obj Tests/tests.i: Tests/tests.cpp.i .PHONY : Tests/tests.i # target to preprocess a source file Tests/tests.cpp.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/Tests/tests.cpp.i .PHONY : Tests/tests.cpp.i Tests/tests.s: Tests/tests.cpp.s .PHONY : Tests/tests.s # target to generate assembly for a file Tests/tests.cpp.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/Tests/tests.cpp.s .PHONY : Tests/tests.cpp.s lib/googletest-master/googlemock/src/gmock-all.obj: lib/googletest-master/googlemock/src/gmock-all.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-all.obj # target to build an object file lib/googletest-master/googlemock/src/gmock-all.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-all.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-all.cc.obj lib/googletest-master/googlemock/src/gmock-all.i: lib/googletest-master/googlemock/src/gmock-all.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-all.i # target to preprocess a source file lib/googletest-master/googlemock/src/gmock-all.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-all.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-all.cc.i lib/googletest-master/googlemock/src/gmock-all.s: lib/googletest-master/googlemock/src/gmock-all.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-all.s # target to generate assembly for a file lib/googletest-master/googlemock/src/gmock-all.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-all.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-all.cc.s lib/googletest-master/googlemock/src/gmock-cardinalities.obj: lib/googletest-master/googlemock/src/gmock-cardinalities.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-cardinalities.obj # target to build an object file lib/googletest-master/googlemock/src/gmock-cardinalities.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-cardinalities.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-cardinalities.cc.obj lib/googletest-master/googlemock/src/gmock-cardinalities.i: lib/googletest-master/googlemock/src/gmock-cardinalities.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-cardinalities.i # target to preprocess a source file lib/googletest-master/googlemock/src/gmock-cardinalities.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-cardinalities.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-cardinalities.cc.i lib/googletest-master/googlemock/src/gmock-cardinalities.s: lib/googletest-master/googlemock/src/gmock-cardinalities.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-cardinalities.s # target to generate assembly for a file lib/googletest-master/googlemock/src/gmock-cardinalities.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-cardinalities.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-cardinalities.cc.s lib/googletest-master/googlemock/src/gmock-internal-utils.obj: lib/googletest-master/googlemock/src/gmock-internal-utils.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-internal-utils.obj # target to build an object file lib/googletest-master/googlemock/src/gmock-internal-utils.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-internal-utils.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-internal-utils.cc.obj lib/googletest-master/googlemock/src/gmock-internal-utils.i: lib/googletest-master/googlemock/src/gmock-internal-utils.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-internal-utils.i # target to preprocess a source file lib/googletest-master/googlemock/src/gmock-internal-utils.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-internal-utils.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-internal-utils.cc.i lib/googletest-master/googlemock/src/gmock-internal-utils.s: lib/googletest-master/googlemock/src/gmock-internal-utils.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-internal-utils.s # target to generate assembly for a file lib/googletest-master/googlemock/src/gmock-internal-utils.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-internal-utils.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-internal-utils.cc.s lib/googletest-master/googlemock/src/gmock-matchers.obj: lib/googletest-master/googlemock/src/gmock-matchers.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-matchers.obj # target to build an object file lib/googletest-master/googlemock/src/gmock-matchers.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-matchers.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-matchers.cc.obj lib/googletest-master/googlemock/src/gmock-matchers.i: lib/googletest-master/googlemock/src/gmock-matchers.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-matchers.i # target to preprocess a source file lib/googletest-master/googlemock/src/gmock-matchers.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-matchers.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-matchers.cc.i lib/googletest-master/googlemock/src/gmock-matchers.s: lib/googletest-master/googlemock/src/gmock-matchers.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-matchers.s # target to generate assembly for a file lib/googletest-master/googlemock/src/gmock-matchers.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-matchers.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-matchers.cc.s lib/googletest-master/googlemock/src/gmock-spec-builders.obj: lib/googletest-master/googlemock/src/gmock-spec-builders.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-spec-builders.obj # target to build an object file lib/googletest-master/googlemock/src/gmock-spec-builders.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-spec-builders.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock-spec-builders.cc.obj lib/googletest-master/googlemock/src/gmock-spec-builders.i: lib/googletest-master/googlemock/src/gmock-spec-builders.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-spec-builders.i # target to preprocess a source file lib/googletest-master/googlemock/src/gmock-spec-builders.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-spec-builders.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock-spec-builders.cc.i lib/googletest-master/googlemock/src/gmock-spec-builders.s: lib/googletest-master/googlemock/src/gmock-spec-builders.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-spec-builders.s # target to generate assembly for a file lib/googletest-master/googlemock/src/gmock-spec-builders.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock-spec-builders.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock-spec-builders.cc.s lib/googletest-master/googlemock/src/gmock.obj: lib/googletest-master/googlemock/src/gmock.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock.obj # target to build an object file lib/googletest-master/googlemock/src/gmock.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock.cc.obj lib/googletest-master/googlemock/src/gmock.i: lib/googletest-master/googlemock/src/gmock.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock.i # target to preprocess a source file lib/googletest-master/googlemock/src/gmock.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock.cc.i lib/googletest-master/googlemock/src/gmock.s: lib/googletest-master/googlemock/src/gmock.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock.s # target to generate assembly for a file lib/googletest-master/googlemock/src/gmock.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock.cc.s lib/googletest-master/googlemock/src/gmock_main.obj: lib/googletest-master/googlemock/src/gmock_main.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock_main.obj # target to build an object file lib/googletest-master/googlemock/src/gmock_main.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock_main.cc.obj .PHONY : lib/googletest-master/googlemock/src/gmock_main.cc.obj lib/googletest-master/googlemock/src/gmock_main.i: lib/googletest-master/googlemock/src/gmock_main.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock_main.i # target to preprocess a source file lib/googletest-master/googlemock/src/gmock_main.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock_main.cc.i .PHONY : lib/googletest-master/googlemock/src/gmock_main.cc.i lib/googletest-master/googlemock/src/gmock_main.s: lib/googletest-master/googlemock/src/gmock_main.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock_main.s # target to generate assembly for a file lib/googletest-master/googlemock/src/gmock_main.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/src/gmock_main.cc.s .PHONY : lib/googletest-master/googlemock/src/gmock_main.cc.s lib/googletest-master/googlemock/test/gmock-actions_test.obj: lib/googletest-master/googlemock/test/gmock-actions_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-actions_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-actions_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-actions_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-actions_test.cc.obj lib/googletest-master/googlemock/test/gmock-actions_test.i: lib/googletest-master/googlemock/test/gmock-actions_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-actions_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-actions_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-actions_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-actions_test.cc.i lib/googletest-master/googlemock/test/gmock-actions_test.s: lib/googletest-master/googlemock/test/gmock-actions_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-actions_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-actions_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-actions_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-actions_test.cc.s lib/googletest-master/googlemock/test/gmock-cardinalities_test.obj: lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-cardinalities_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.obj lib/googletest-master/googlemock/test/gmock-cardinalities_test.i: lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-cardinalities_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.i lib/googletest-master/googlemock/test/gmock-cardinalities_test.s: lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-cardinalities_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-cardinalities_test.cc.s lib/googletest-master/googlemock/test/gmock-function-mocker_nc.obj: lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_nc.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.obj lib/googletest-master/googlemock/test/gmock-function-mocker_nc.i: lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_nc.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.i lib/googletest-master/googlemock/test/gmock-function-mocker_nc.s: lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_nc.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_nc.cc.s lib/googletest-master/googlemock/test/gmock-function-mocker_test.obj: lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.obj lib/googletest-master/googlemock/test/gmock-function-mocker_test.i: lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.i lib/googletest-master/googlemock/test/gmock-function-mocker_test.s: lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-function-mocker_test.cc.s lib/googletest-master/googlemock/test/gmock-generated-actions_test.obj: lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-generated-actions_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.obj lib/googletest-master/googlemock/test/gmock-generated-actions_test.i: lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-generated-actions_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.i lib/googletest-master/googlemock/test/gmock-generated-actions_test.s: lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-generated-actions_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-generated-actions_test.cc.s lib/googletest-master/googlemock/test/gmock-internal-utils_test.obj: lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-internal-utils_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.obj lib/googletest-master/googlemock/test/gmock-internal-utils_test.i: lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-internal-utils_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.i lib/googletest-master/googlemock/test/gmock-internal-utils_test.s: lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-internal-utils_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-internal-utils_test.cc.s lib/googletest-master/googlemock/test/gmock-matchers_test.obj: lib/googletest-master/googlemock/test/gmock-matchers_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-matchers_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-matchers_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-matchers_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-matchers_test.cc.obj lib/googletest-master/googlemock/test/gmock-matchers_test.i: lib/googletest-master/googlemock/test/gmock-matchers_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-matchers_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-matchers_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-matchers_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-matchers_test.cc.i lib/googletest-master/googlemock/test/gmock-matchers_test.s: lib/googletest-master/googlemock/test/gmock-matchers_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-matchers_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-matchers_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-matchers_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-matchers_test.cc.s lib/googletest-master/googlemock/test/gmock-more-actions_test.obj: lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-more-actions_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.obj lib/googletest-master/googlemock/test/gmock-more-actions_test.i: lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-more-actions_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.i lib/googletest-master/googlemock/test/gmock-more-actions_test.s: lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-more-actions_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-more-actions_test.cc.s lib/googletest-master/googlemock/test/gmock-nice-strict_test.obj: lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-nice-strict_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.obj lib/googletest-master/googlemock/test/gmock-nice-strict_test.i: lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-nice-strict_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.i lib/googletest-master/googlemock/test/gmock-nice-strict_test.s: lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-nice-strict_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-nice-strict_test.cc.s lib/googletest-master/googlemock/test/gmock-port_test.obj: lib/googletest-master/googlemock/test/gmock-port_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-port_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-port_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-port_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-port_test.cc.obj lib/googletest-master/googlemock/test/gmock-port_test.i: lib/googletest-master/googlemock/test/gmock-port_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-port_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-port_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-port_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-port_test.cc.i lib/googletest-master/googlemock/test/gmock-port_test.s: lib/googletest-master/googlemock/test/gmock-port_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-port_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-port_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-port_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-port_test.cc.s lib/googletest-master/googlemock/test/gmock-pp-string_test.obj: lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-pp-string_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.obj lib/googletest-master/googlemock/test/gmock-pp-string_test.i: lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-pp-string_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.i lib/googletest-master/googlemock/test/gmock-pp-string_test.s: lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-pp-string_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-pp-string_test.cc.s lib/googletest-master/googlemock/test/gmock-pp_test.obj: lib/googletest-master/googlemock/test/gmock-pp_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-pp_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-pp_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-pp_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-pp_test.cc.obj lib/googletest-master/googlemock/test/gmock-pp_test.i: lib/googletest-master/googlemock/test/gmock-pp_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-pp_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-pp_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-pp_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-pp_test.cc.i lib/googletest-master/googlemock/test/gmock-pp_test.s: lib/googletest-master/googlemock/test/gmock-pp_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-pp_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-pp_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-pp_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-pp_test.cc.s lib/googletest-master/googlemock/test/gmock-spec-builders_test.obj: lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-spec-builders_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.obj lib/googletest-master/googlemock/test/gmock-spec-builders_test.i: lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-spec-builders_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.i lib/googletest-master/googlemock/test/gmock-spec-builders_test.s: lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-spec-builders_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock-spec-builders_test.cc.s lib/googletest-master/googlemock/test/gmock_all_test.obj: lib/googletest-master/googlemock/test/gmock_all_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_all_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock_all_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_all_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_all_test.cc.obj lib/googletest-master/googlemock/test/gmock_all_test.i: lib/googletest-master/googlemock/test/gmock_all_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_all_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock_all_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_all_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_all_test.cc.i lib/googletest-master/googlemock/test/gmock_all_test.s: lib/googletest-master/googlemock/test/gmock_all_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_all_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock_all_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_all_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_all_test.cc.s lib/googletest-master/googlemock/test/gmock_ex_test.obj: lib/googletest-master/googlemock/test/gmock_ex_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_ex_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock_ex_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_ex_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_ex_test.cc.obj lib/googletest-master/googlemock/test/gmock_ex_test.i: lib/googletest-master/googlemock/test/gmock_ex_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_ex_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock_ex_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_ex_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_ex_test.cc.i lib/googletest-master/googlemock/test/gmock_ex_test.s: lib/googletest-master/googlemock/test/gmock_ex_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_ex_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock_ex_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_ex_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_ex_test.cc.s lib/googletest-master/googlemock/test/gmock_leak_test_.obj: lib/googletest-master/googlemock/test/gmock_leak_test_.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_leak_test_.obj # target to build an object file lib/googletest-master/googlemock/test/gmock_leak_test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_leak_test_.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_leak_test_.cc.obj lib/googletest-master/googlemock/test/gmock_leak_test_.i: lib/googletest-master/googlemock/test/gmock_leak_test_.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_leak_test_.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock_leak_test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_leak_test_.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_leak_test_.cc.i lib/googletest-master/googlemock/test/gmock_leak_test_.s: lib/googletest-master/googlemock/test/gmock_leak_test_.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_leak_test_.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock_leak_test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_leak_test_.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_leak_test_.cc.s lib/googletest-master/googlemock/test/gmock_link2_test.obj: lib/googletest-master/googlemock/test/gmock_link2_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_link2_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock_link2_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_link2_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_link2_test.cc.obj lib/googletest-master/googlemock/test/gmock_link2_test.i: lib/googletest-master/googlemock/test/gmock_link2_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_link2_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock_link2_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_link2_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_link2_test.cc.i lib/googletest-master/googlemock/test/gmock_link2_test.s: lib/googletest-master/googlemock/test/gmock_link2_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_link2_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock_link2_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_link2_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_link2_test.cc.s lib/googletest-master/googlemock/test/gmock_link_test.obj: lib/googletest-master/googlemock/test/gmock_link_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_link_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock_link_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_link_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_link_test.cc.obj lib/googletest-master/googlemock/test/gmock_link_test.i: lib/googletest-master/googlemock/test/gmock_link_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_link_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock_link_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_link_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_link_test.cc.i lib/googletest-master/googlemock/test/gmock_link_test.s: lib/googletest-master/googlemock/test/gmock_link_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_link_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock_link_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_link_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_link_test.cc.s lib/googletest-master/googlemock/test/gmock_output_test_.obj: lib/googletest-master/googlemock/test/gmock_output_test_.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_output_test_.obj # target to build an object file lib/googletest-master/googlemock/test/gmock_output_test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_output_test_.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_output_test_.cc.obj lib/googletest-master/googlemock/test/gmock_output_test_.i: lib/googletest-master/googlemock/test/gmock_output_test_.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_output_test_.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock_output_test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_output_test_.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_output_test_.cc.i lib/googletest-master/googlemock/test/gmock_output_test_.s: lib/googletest-master/googlemock/test/gmock_output_test_.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_output_test_.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock_output_test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_output_test_.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_output_test_.cc.s lib/googletest-master/googlemock/test/gmock_stress_test.obj: lib/googletest-master/googlemock/test/gmock_stress_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_stress_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock_stress_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_stress_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_stress_test.cc.obj lib/googletest-master/googlemock/test/gmock_stress_test.i: lib/googletest-master/googlemock/test/gmock_stress_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_stress_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock_stress_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_stress_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_stress_test.cc.i lib/googletest-master/googlemock/test/gmock_stress_test.s: lib/googletest-master/googlemock/test/gmock_stress_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_stress_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock_stress_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_stress_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_stress_test.cc.s lib/googletest-master/googlemock/test/gmock_test.obj: lib/googletest-master/googlemock/test/gmock_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_test.obj # target to build an object file lib/googletest-master/googlemock/test/gmock_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_test.cc.obj .PHONY : lib/googletest-master/googlemock/test/gmock_test.cc.obj lib/googletest-master/googlemock/test/gmock_test.i: lib/googletest-master/googlemock/test/gmock_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_test.i # target to preprocess a source file lib/googletest-master/googlemock/test/gmock_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_test.cc.i .PHONY : lib/googletest-master/googlemock/test/gmock_test.cc.i lib/googletest-master/googlemock/test/gmock_test.s: lib/googletest-master/googlemock/test/gmock_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_test.s # target to generate assembly for a file lib/googletest-master/googlemock/test/gmock_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googlemock/test/gmock_test.cc.s .PHONY : lib/googletest-master/googlemock/test/gmock_test.cc.s lib/googletest-master/googletest/samples/sample1.obj: lib/googletest-master/googletest/samples/sample1.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample1.obj # target to build an object file lib/googletest-master/googletest/samples/sample1.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample1.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample1.cc.obj lib/googletest-master/googletest/samples/sample1.i: lib/googletest-master/googletest/samples/sample1.cc.i .PHONY : lib/googletest-master/googletest/samples/sample1.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample1.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample1.cc.i .PHONY : lib/googletest-master/googletest/samples/sample1.cc.i lib/googletest-master/googletest/samples/sample1.s: lib/googletest-master/googletest/samples/sample1.cc.s .PHONY : lib/googletest-master/googletest/samples/sample1.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample1.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample1.cc.s .PHONY : lib/googletest-master/googletest/samples/sample1.cc.s lib/googletest-master/googletest/samples/sample10_unittest.obj: lib/googletest-master/googletest/samples/sample10_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample10_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample10_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample10_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample10_unittest.cc.obj lib/googletest-master/googletest/samples/sample10_unittest.i: lib/googletest-master/googletest/samples/sample10_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample10_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample10_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample10_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample10_unittest.cc.i lib/googletest-master/googletest/samples/sample10_unittest.s: lib/googletest-master/googletest/samples/sample10_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample10_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample10_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample10_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample10_unittest.cc.s lib/googletest-master/googletest/samples/sample1_unittest.obj: lib/googletest-master/googletest/samples/sample1_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample1_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample1_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample1_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample1_unittest.cc.obj lib/googletest-master/googletest/samples/sample1_unittest.i: lib/googletest-master/googletest/samples/sample1_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample1_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample1_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample1_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample1_unittest.cc.i lib/googletest-master/googletest/samples/sample1_unittest.s: lib/googletest-master/googletest/samples/sample1_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample1_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample1_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample1_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample1_unittest.cc.s lib/googletest-master/googletest/samples/sample2.obj: lib/googletest-master/googletest/samples/sample2.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample2.obj # target to build an object file lib/googletest-master/googletest/samples/sample2.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample2.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample2.cc.obj lib/googletest-master/googletest/samples/sample2.i: lib/googletest-master/googletest/samples/sample2.cc.i .PHONY : lib/googletest-master/googletest/samples/sample2.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample2.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample2.cc.i .PHONY : lib/googletest-master/googletest/samples/sample2.cc.i lib/googletest-master/googletest/samples/sample2.s: lib/googletest-master/googletest/samples/sample2.cc.s .PHONY : lib/googletest-master/googletest/samples/sample2.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample2.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample2.cc.s .PHONY : lib/googletest-master/googletest/samples/sample2.cc.s lib/googletest-master/googletest/samples/sample2_unittest.obj: lib/googletest-master/googletest/samples/sample2_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample2_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample2_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample2_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample2_unittest.cc.obj lib/googletest-master/googletest/samples/sample2_unittest.i: lib/googletest-master/googletest/samples/sample2_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample2_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample2_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample2_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample2_unittest.cc.i lib/googletest-master/googletest/samples/sample2_unittest.s: lib/googletest-master/googletest/samples/sample2_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample2_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample2_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample2_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample2_unittest.cc.s lib/googletest-master/googletest/samples/sample3_unittest.obj: lib/googletest-master/googletest/samples/sample3_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample3_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample3_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample3_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample3_unittest.cc.obj lib/googletest-master/googletest/samples/sample3_unittest.i: lib/googletest-master/googletest/samples/sample3_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample3_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample3_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample3_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample3_unittest.cc.i lib/googletest-master/googletest/samples/sample3_unittest.s: lib/googletest-master/googletest/samples/sample3_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample3_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample3_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample3_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample3_unittest.cc.s lib/googletest-master/googletest/samples/sample4.obj: lib/googletest-master/googletest/samples/sample4.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample4.obj # target to build an object file lib/googletest-master/googletest/samples/sample4.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample4.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample4.cc.obj lib/googletest-master/googletest/samples/sample4.i: lib/googletest-master/googletest/samples/sample4.cc.i .PHONY : lib/googletest-master/googletest/samples/sample4.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample4.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample4.cc.i .PHONY : lib/googletest-master/googletest/samples/sample4.cc.i lib/googletest-master/googletest/samples/sample4.s: lib/googletest-master/googletest/samples/sample4.cc.s .PHONY : lib/googletest-master/googletest/samples/sample4.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample4.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample4.cc.s .PHONY : lib/googletest-master/googletest/samples/sample4.cc.s lib/googletest-master/googletest/samples/sample4_unittest.obj: lib/googletest-master/googletest/samples/sample4_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample4_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample4_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample4_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample4_unittest.cc.obj lib/googletest-master/googletest/samples/sample4_unittest.i: lib/googletest-master/googletest/samples/sample4_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample4_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample4_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample4_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample4_unittest.cc.i lib/googletest-master/googletest/samples/sample4_unittest.s: lib/googletest-master/googletest/samples/sample4_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample4_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample4_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample4_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample4_unittest.cc.s lib/googletest-master/googletest/samples/sample5_unittest.obj: lib/googletest-master/googletest/samples/sample5_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample5_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample5_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample5_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample5_unittest.cc.obj lib/googletest-master/googletest/samples/sample5_unittest.i: lib/googletest-master/googletest/samples/sample5_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample5_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample5_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample5_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample5_unittest.cc.i lib/googletest-master/googletest/samples/sample5_unittest.s: lib/googletest-master/googletest/samples/sample5_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample5_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample5_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample5_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample5_unittest.cc.s lib/googletest-master/googletest/samples/sample6_unittest.obj: lib/googletest-master/googletest/samples/sample6_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample6_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample6_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample6_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample6_unittest.cc.obj lib/googletest-master/googletest/samples/sample6_unittest.i: lib/googletest-master/googletest/samples/sample6_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample6_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample6_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample6_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample6_unittest.cc.i lib/googletest-master/googletest/samples/sample6_unittest.s: lib/googletest-master/googletest/samples/sample6_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample6_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample6_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample6_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample6_unittest.cc.s lib/googletest-master/googletest/samples/sample7_unittest.obj: lib/googletest-master/googletest/samples/sample7_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample7_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample7_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample7_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample7_unittest.cc.obj lib/googletest-master/googletest/samples/sample7_unittest.i: lib/googletest-master/googletest/samples/sample7_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample7_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample7_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample7_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample7_unittest.cc.i lib/googletest-master/googletest/samples/sample7_unittest.s: lib/googletest-master/googletest/samples/sample7_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample7_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample7_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample7_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample7_unittest.cc.s lib/googletest-master/googletest/samples/sample8_unittest.obj: lib/googletest-master/googletest/samples/sample8_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample8_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample8_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample8_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample8_unittest.cc.obj lib/googletest-master/googletest/samples/sample8_unittest.i: lib/googletest-master/googletest/samples/sample8_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample8_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample8_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample8_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample8_unittest.cc.i lib/googletest-master/googletest/samples/sample8_unittest.s: lib/googletest-master/googletest/samples/sample8_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample8_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample8_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample8_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample8_unittest.cc.s lib/googletest-master/googletest/samples/sample9_unittest.obj: lib/googletest-master/googletest/samples/sample9_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample9_unittest.obj # target to build an object file lib/googletest-master/googletest/samples/sample9_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample9_unittest.cc.obj .PHONY : lib/googletest-master/googletest/samples/sample9_unittest.cc.obj lib/googletest-master/googletest/samples/sample9_unittest.i: lib/googletest-master/googletest/samples/sample9_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample9_unittest.i # target to preprocess a source file lib/googletest-master/googletest/samples/sample9_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample9_unittest.cc.i .PHONY : lib/googletest-master/googletest/samples/sample9_unittest.cc.i lib/googletest-master/googletest/samples/sample9_unittest.s: lib/googletest-master/googletest/samples/sample9_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample9_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/samples/sample9_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/samples/sample9_unittest.cc.s .PHONY : lib/googletest-master/googletest/samples/sample9_unittest.cc.s lib/googletest-master/googletest/src/gtest-all.obj: lib/googletest-master/googletest/src/gtest-all.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-all.obj # target to build an object file lib/googletest-master/googletest/src/gtest-all.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-all.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-all.cc.obj lib/googletest-master/googletest/src/gtest-all.i: lib/googletest-master/googletest/src/gtest-all.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-all.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest-all.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-all.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-all.cc.i lib/googletest-master/googletest/src/gtest-all.s: lib/googletest-master/googletest/src/gtest-all.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-all.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest-all.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-all.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-all.cc.s lib/googletest-master/googletest/src/gtest-death-test.obj: lib/googletest-master/googletest/src/gtest-death-test.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-death-test.obj # target to build an object file lib/googletest-master/googletest/src/gtest-death-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-death-test.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-death-test.cc.obj lib/googletest-master/googletest/src/gtest-death-test.i: lib/googletest-master/googletest/src/gtest-death-test.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-death-test.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest-death-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-death-test.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-death-test.cc.i lib/googletest-master/googletest/src/gtest-death-test.s: lib/googletest-master/googletest/src/gtest-death-test.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-death-test.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest-death-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-death-test.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-death-test.cc.s lib/googletest-master/googletest/src/gtest-filepath.obj: lib/googletest-master/googletest/src/gtest-filepath.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-filepath.obj # target to build an object file lib/googletest-master/googletest/src/gtest-filepath.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-filepath.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-filepath.cc.obj lib/googletest-master/googletest/src/gtest-filepath.i: lib/googletest-master/googletest/src/gtest-filepath.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-filepath.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest-filepath.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-filepath.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-filepath.cc.i lib/googletest-master/googletest/src/gtest-filepath.s: lib/googletest-master/googletest/src/gtest-filepath.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-filepath.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest-filepath.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-filepath.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-filepath.cc.s lib/googletest-master/googletest/src/gtest-matchers.obj: lib/googletest-master/googletest/src/gtest-matchers.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-matchers.obj # target to build an object file lib/googletest-master/googletest/src/gtest-matchers.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-matchers.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-matchers.cc.obj lib/googletest-master/googletest/src/gtest-matchers.i: lib/googletest-master/googletest/src/gtest-matchers.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-matchers.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest-matchers.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-matchers.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-matchers.cc.i lib/googletest-master/googletest/src/gtest-matchers.s: lib/googletest-master/googletest/src/gtest-matchers.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-matchers.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest-matchers.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-matchers.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-matchers.cc.s lib/googletest-master/googletest/src/gtest-port.obj: lib/googletest-master/googletest/src/gtest-port.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-port.obj # target to build an object file lib/googletest-master/googletest/src/gtest-port.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-port.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-port.cc.obj lib/googletest-master/googletest/src/gtest-port.i: lib/googletest-master/googletest/src/gtest-port.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-port.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest-port.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-port.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-port.cc.i lib/googletest-master/googletest/src/gtest-port.s: lib/googletest-master/googletest/src/gtest-port.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-port.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest-port.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-port.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-port.cc.s lib/googletest-master/googletest/src/gtest-printers.obj: lib/googletest-master/googletest/src/gtest-printers.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-printers.obj # target to build an object file lib/googletest-master/googletest/src/gtest-printers.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-printers.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-printers.cc.obj lib/googletest-master/googletest/src/gtest-printers.i: lib/googletest-master/googletest/src/gtest-printers.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-printers.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest-printers.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-printers.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-printers.cc.i lib/googletest-master/googletest/src/gtest-printers.s: lib/googletest-master/googletest/src/gtest-printers.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-printers.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest-printers.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-printers.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-printers.cc.s lib/googletest-master/googletest/src/gtest-test-part.obj: lib/googletest-master/googletest/src/gtest-test-part.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-test-part.obj # target to build an object file lib/googletest-master/googletest/src/gtest-test-part.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-test-part.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-test-part.cc.obj lib/googletest-master/googletest/src/gtest-test-part.i: lib/googletest-master/googletest/src/gtest-test-part.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-test-part.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest-test-part.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-test-part.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-test-part.cc.i lib/googletest-master/googletest/src/gtest-test-part.s: lib/googletest-master/googletest/src/gtest-test-part.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-test-part.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest-test-part.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-test-part.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-test-part.cc.s lib/googletest-master/googletest/src/gtest-typed-test.obj: lib/googletest-master/googletest/src/gtest-typed-test.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-typed-test.obj # target to build an object file lib/googletest-master/googletest/src/gtest-typed-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-typed-test.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest-typed-test.cc.obj lib/googletest-master/googletest/src/gtest-typed-test.i: lib/googletest-master/googletest/src/gtest-typed-test.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-typed-test.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest-typed-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-typed-test.cc.i .PHONY : lib/googletest-master/googletest/src/gtest-typed-test.cc.i lib/googletest-master/googletest/src/gtest-typed-test.s: lib/googletest-master/googletest/src/gtest-typed-test.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-typed-test.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest-typed-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest-typed-test.cc.s .PHONY : lib/googletest-master/googletest/src/gtest-typed-test.cc.s lib/googletest-master/googletest/src/gtest.obj: lib/googletest-master/googletest/src/gtest.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest.obj # target to build an object file lib/googletest-master/googletest/src/gtest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest.cc.obj lib/googletest-master/googletest/src/gtest.i: lib/googletest-master/googletest/src/gtest.cc.i .PHONY : lib/googletest-master/googletest/src/gtest.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest.cc.i .PHONY : lib/googletest-master/googletest/src/gtest.cc.i lib/googletest-master/googletest/src/gtest.s: lib/googletest-master/googletest/src/gtest.cc.s .PHONY : lib/googletest-master/googletest/src/gtest.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest.cc.s .PHONY : lib/googletest-master/googletest/src/gtest.cc.s lib/googletest-master/googletest/src/gtest_main.obj: lib/googletest-master/googletest/src/gtest_main.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest_main.obj # target to build an object file lib/googletest-master/googletest/src/gtest_main.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest_main.cc.obj .PHONY : lib/googletest-master/googletest/src/gtest_main.cc.obj lib/googletest-master/googletest/src/gtest_main.i: lib/googletest-master/googletest/src/gtest_main.cc.i .PHONY : lib/googletest-master/googletest/src/gtest_main.i # target to preprocess a source file lib/googletest-master/googletest/src/gtest_main.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest_main.cc.i .PHONY : lib/googletest-master/googletest/src/gtest_main.cc.i lib/googletest-master/googletest/src/gtest_main.s: lib/googletest-master/googletest/src/gtest_main.cc.s .PHONY : lib/googletest-master/googletest/src/gtest_main.s # target to generate assembly for a file lib/googletest-master/googletest/src/gtest_main.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/src/gtest_main.cc.s .PHONY : lib/googletest-master/googletest/src/gtest_main.cc.s lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.obj: lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.obj lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.i: lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.i lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.s: lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.cc.s lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.obj: lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.obj lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.i: lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.i lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.s: lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.cc.s lib/googletest-master/googletest/test/googletest-color-test_.obj: lib/googletest-master/googletest/test/googletest-color-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-color-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-color-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-color-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-color-test_.cc.obj lib/googletest-master/googletest/test/googletest-color-test_.i: lib/googletest-master/googletest/test/googletest-color-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-color-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-color-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-color-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-color-test_.cc.i lib/googletest-master/googletest/test/googletest-color-test_.s: lib/googletest-master/googletest/test/googletest-color-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-color-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-color-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-color-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-color-test_.cc.s lib/googletest-master/googletest/test/googletest-death-test-test.obj: lib/googletest-master/googletest/test/googletest-death-test-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-death-test-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-death-test-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-death-test-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-death-test-test.cc.obj lib/googletest-master/googletest/test/googletest-death-test-test.i: lib/googletest-master/googletest/test/googletest-death-test-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-death-test-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-death-test-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-death-test-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-death-test-test.cc.i lib/googletest-master/googletest/test/googletest-death-test-test.s: lib/googletest-master/googletest/test/googletest-death-test-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-death-test-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-death-test-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-death-test-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-death-test-test.cc.s lib/googletest-master/googletest/test/googletest-death-test_ex_test.obj: lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-death-test_ex_test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.obj lib/googletest-master/googletest/test/googletest-death-test_ex_test.i: lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-death-test_ex_test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.i lib/googletest-master/googletest/test/googletest-death-test_ex_test.s: lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-death-test_ex_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-death-test_ex_test.cc.s lib/googletest-master/googletest/test/googletest-env-var-test_.obj: lib/googletest-master/googletest/test/googletest-env-var-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-env-var-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-env-var-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-env-var-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-env-var-test_.cc.obj lib/googletest-master/googletest/test/googletest-env-var-test_.i: lib/googletest-master/googletest/test/googletest-env-var-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-env-var-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-env-var-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-env-var-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-env-var-test_.cc.i lib/googletest-master/googletest/test/googletest-env-var-test_.s: lib/googletest-master/googletest/test/googletest-env-var-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-env-var-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-env-var-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-env-var-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-env-var-test_.cc.s lib/googletest-master/googletest/test/googletest-failfast-unittest_.obj: lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-failfast-unittest_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.obj lib/googletest-master/googletest/test/googletest-failfast-unittest_.i: lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-failfast-unittest_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.i lib/googletest-master/googletest/test/googletest-failfast-unittest_.s: lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-failfast-unittest_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-failfast-unittest_.cc.s lib/googletest-master/googletest/test/googletest-filepath-test.obj: lib/googletest-master/googletest/test/googletest-filepath-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-filepath-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-filepath-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-filepath-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-filepath-test.cc.obj lib/googletest-master/googletest/test/googletest-filepath-test.i: lib/googletest-master/googletest/test/googletest-filepath-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-filepath-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-filepath-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-filepath-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-filepath-test.cc.i lib/googletest-master/googletest/test/googletest-filepath-test.s: lib/googletest-master/googletest/test/googletest-filepath-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-filepath-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-filepath-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-filepath-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-filepath-test.cc.s lib/googletest-master/googletest/test/googletest-filter-unittest_.obj: lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-filter-unittest_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.obj lib/googletest-master/googletest/test/googletest-filter-unittest_.i: lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-filter-unittest_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.i lib/googletest-master/googletest/test/googletest-filter-unittest_.s: lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-filter-unittest_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-filter-unittest_.cc.s lib/googletest-master/googletest/test/googletest-list-tests-unittest_.obj: lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-list-tests-unittest_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.obj lib/googletest-master/googletest/test/googletest-list-tests-unittest_.i: lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-list-tests-unittest_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.i lib/googletest-master/googletest/test/googletest-list-tests-unittest_.s: lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-list-tests-unittest_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-list-tests-unittest_.cc.s lib/googletest-master/googletest/test/googletest-listener-test.obj: lib/googletest-master/googletest/test/googletest-listener-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-listener-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-listener-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-listener-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-listener-test.cc.obj lib/googletest-master/googletest/test/googletest-listener-test.i: lib/googletest-master/googletest/test/googletest-listener-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-listener-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-listener-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-listener-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-listener-test.cc.i lib/googletest-master/googletest/test/googletest-listener-test.s: lib/googletest-master/googletest/test/googletest-listener-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-listener-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-listener-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-listener-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-listener-test.cc.s lib/googletest-master/googletest/test/googletest-message-test.obj: lib/googletest-master/googletest/test/googletest-message-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-message-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-message-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-message-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-message-test.cc.obj lib/googletest-master/googletest/test/googletest-message-test.i: lib/googletest-master/googletest/test/googletest-message-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-message-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-message-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-message-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-message-test.cc.i lib/googletest-master/googletest/test/googletest-message-test.s: lib/googletest-master/googletest/test/googletest-message-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-message-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-message-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-message-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-message-test.cc.s lib/googletest-master/googletest/test/googletest-options-test.obj: lib/googletest-master/googletest/test/googletest-options-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-options-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-options-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-options-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-options-test.cc.obj lib/googletest-master/googletest/test/googletest-options-test.i: lib/googletest-master/googletest/test/googletest-options-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-options-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-options-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-options-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-options-test.cc.i lib/googletest-master/googletest/test/googletest-options-test.s: lib/googletest-master/googletest/test/googletest-options-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-options-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-options-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-options-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-options-test.cc.s lib/googletest-master/googletest/test/googletest-output-test_.obj: lib/googletest-master/googletest/test/googletest-output-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-output-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-output-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-output-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-output-test_.cc.obj lib/googletest-master/googletest/test/googletest-output-test_.i: lib/googletest-master/googletest/test/googletest-output-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-output-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-output-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-output-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-output-test_.cc.i lib/googletest-master/googletest/test/googletest-output-test_.s: lib/googletest-master/googletest/test/googletest-output-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-output-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-output-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-output-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-output-test_.cc.s lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.obj: lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.obj lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.i: lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.i lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.s: lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.cc.s lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.obj: lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.obj lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.i: lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.i lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.s: lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.cc.s lib/googletest-master/googletest/test/googletest-param-test-test.obj: lib/googletest-master/googletest/test/googletest-param-test-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-param-test-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-param-test-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-param-test-test.cc.obj lib/googletest-master/googletest/test/googletest-param-test-test.i: lib/googletest-master/googletest/test/googletest-param-test-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-param-test-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-param-test-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-param-test-test.cc.i lib/googletest-master/googletest/test/googletest-param-test-test.s: lib/googletest-master/googletest/test/googletest-param-test-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-param-test-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-param-test-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-param-test-test.cc.s lib/googletest-master/googletest/test/googletest-param-test2-test.obj: lib/googletest-master/googletest/test/googletest-param-test2-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-param-test2-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-param-test2-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test2-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-param-test2-test.cc.obj lib/googletest-master/googletest/test/googletest-param-test2-test.i: lib/googletest-master/googletest/test/googletest-param-test2-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-param-test2-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-param-test2-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test2-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-param-test2-test.cc.i lib/googletest-master/googletest/test/googletest-param-test2-test.s: lib/googletest-master/googletest/test/googletest-param-test2-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-param-test2-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-param-test2-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-param-test2-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-param-test2-test.cc.s lib/googletest-master/googletest/test/googletest-port-test.obj: lib/googletest-master/googletest/test/googletest-port-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-port-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-port-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-port-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-port-test.cc.obj lib/googletest-master/googletest/test/googletest-port-test.i: lib/googletest-master/googletest/test/googletest-port-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-port-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-port-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-port-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-port-test.cc.i lib/googletest-master/googletest/test/googletest-port-test.s: lib/googletest-master/googletest/test/googletest-port-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-port-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-port-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-port-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-port-test.cc.s lib/googletest-master/googletest/test/googletest-printers-test.obj: lib/googletest-master/googletest/test/googletest-printers-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-printers-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-printers-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-printers-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-printers-test.cc.obj lib/googletest-master/googletest/test/googletest-printers-test.i: lib/googletest-master/googletest/test/googletest-printers-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-printers-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-printers-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-printers-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-printers-test.cc.i lib/googletest-master/googletest/test/googletest-printers-test.s: lib/googletest-master/googletest/test/googletest-printers-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-printers-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-printers-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-printers-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-printers-test.cc.s lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.obj: lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.obj lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.i: lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.i lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.s: lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.cc.s lib/googletest-master/googletest/test/googletest-shuffle-test_.obj: lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-shuffle-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.obj lib/googletest-master/googletest/test/googletest-shuffle-test_.i: lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-shuffle-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.i lib/googletest-master/googletest/test/googletest-shuffle-test_.s: lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-shuffle-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-shuffle-test_.cc.s lib/googletest-master/googletest/test/googletest-test-part-test.obj: lib/googletest-master/googletest/test/googletest-test-part-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-test-part-test.obj # target to build an object file lib/googletest-master/googletest/test/googletest-test-part-test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-test-part-test.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-test-part-test.cc.obj lib/googletest-master/googletest/test/googletest-test-part-test.i: lib/googletest-master/googletest/test/googletest-test-part-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-test-part-test.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-test-part-test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-test-part-test.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-test-part-test.cc.i lib/googletest-master/googletest/test/googletest-test-part-test.s: lib/googletest-master/googletest/test/googletest-test-part-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-test-part-test.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-test-part-test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-test-part-test.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-test-part-test.cc.s lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.obj: lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.obj lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.i: lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.i lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.s: lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.cc.s lib/googletest-master/googletest/test/googletest-uninitialized-test_.obj: lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-uninitialized-test_.obj # target to build an object file lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.obj .PHONY : lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.obj lib/googletest-master/googletest/test/googletest-uninitialized-test_.i: lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-uninitialized-test_.i # target to preprocess a source file lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.i .PHONY : lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.i lib/googletest-master/googletest/test/googletest-uninitialized-test_.s: lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-uninitialized-test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.s .PHONY : lib/googletest-master/googletest/test/googletest-uninitialized-test_.cc.s lib/googletest-master/googletest/test/gtest-typed-test2_test.obj: lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest-typed-test2_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.obj lib/googletest-master/googletest/test/gtest-typed-test2_test.i: lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest-typed-test2_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.i lib/googletest-master/googletest/test/gtest-typed-test2_test.s: lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest-typed-test2_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest-typed-test2_test.cc.s lib/googletest-master/googletest/test/gtest-typed-test_test.obj: lib/googletest-master/googletest/test/gtest-typed-test_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest-typed-test_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest-typed-test_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest-typed-test_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest-typed-test_test.cc.obj lib/googletest-master/googletest/test/gtest-typed-test_test.i: lib/googletest-master/googletest/test/gtest-typed-test_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest-typed-test_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest-typed-test_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest-typed-test_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest-typed-test_test.cc.i lib/googletest-master/googletest/test/gtest-typed-test_test.s: lib/googletest-master/googletest/test/gtest-typed-test_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest-typed-test_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest-typed-test_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest-typed-test_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest-typed-test_test.cc.s lib/googletest-master/googletest/test/gtest-unittest-api_test.obj: lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest-unittest-api_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.obj lib/googletest-master/googletest/test/gtest-unittest-api_test.i: lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest-unittest-api_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.i lib/googletest-master/googletest/test/gtest-unittest-api_test.s: lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest-unittest-api_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest-unittest-api_test.cc.s lib/googletest-master/googletest/test/gtest_all_test.obj: lib/googletest-master/googletest/test/gtest_all_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_all_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_all_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_all_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_all_test.cc.obj lib/googletest-master/googletest/test/gtest_all_test.i: lib/googletest-master/googletest/test/gtest_all_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_all_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_all_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_all_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_all_test.cc.i lib/googletest-master/googletest/test/gtest_all_test.s: lib/googletest-master/googletest/test/gtest_all_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_all_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_all_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_all_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_all_test.cc.s lib/googletest-master/googletest/test/gtest_assert_by_exception_test.obj: lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_assert_by_exception_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.obj lib/googletest-master/googletest/test/gtest_assert_by_exception_test.i: lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_assert_by_exception_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.i lib/googletest-master/googletest/test/gtest_assert_by_exception_test.s: lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_assert_by_exception_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_assert_by_exception_test.cc.s lib/googletest-master/googletest/test/gtest_environment_test.obj: lib/googletest-master/googletest/test/gtest_environment_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_environment_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_environment_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_environment_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_environment_test.cc.obj lib/googletest-master/googletest/test/gtest_environment_test.i: lib/googletest-master/googletest/test/gtest_environment_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_environment_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_environment_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_environment_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_environment_test.cc.i lib/googletest-master/googletest/test/gtest_environment_test.s: lib/googletest-master/googletest/test/gtest_environment_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_environment_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_environment_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_environment_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_environment_test.cc.s lib/googletest-master/googletest/test/gtest_help_test_.obj: lib/googletest-master/googletest/test/gtest_help_test_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_help_test_.obj # target to build an object file lib/googletest-master/googletest/test/gtest_help_test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_help_test_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_help_test_.cc.obj lib/googletest-master/googletest/test/gtest_help_test_.i: lib/googletest-master/googletest/test/gtest_help_test_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_help_test_.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_help_test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_help_test_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_help_test_.cc.i lib/googletest-master/googletest/test/gtest_help_test_.s: lib/googletest-master/googletest/test/gtest_help_test_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_help_test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_help_test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_help_test_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_help_test_.cc.s lib/googletest-master/googletest/test/gtest_list_output_unittest_.obj: lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_list_output_unittest_.obj # target to build an object file lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.obj lib/googletest-master/googletest/test/gtest_list_output_unittest_.i: lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_list_output_unittest_.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.i lib/googletest-master/googletest/test/gtest_list_output_unittest_.s: lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_list_output_unittest_.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_list_output_unittest_.cc.s lib/googletest-master/googletest/test/gtest_main_unittest.obj: lib/googletest-master/googletest/test/gtest_main_unittest.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_main_unittest.obj # target to build an object file lib/googletest-master/googletest/test/gtest_main_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_main_unittest.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_main_unittest.cc.obj lib/googletest-master/googletest/test/gtest_main_unittest.i: lib/googletest-master/googletest/test/gtest_main_unittest.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_main_unittest.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_main_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_main_unittest.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_main_unittest.cc.i lib/googletest-master/googletest/test/gtest_main_unittest.s: lib/googletest-master/googletest/test/gtest_main_unittest.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_main_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_main_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_main_unittest.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_main_unittest.cc.s lib/googletest-master/googletest/test/gtest_no_test_unittest.obj: lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_no_test_unittest.obj # target to build an object file lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.obj lib/googletest-master/googletest/test/gtest_no_test_unittest.i: lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_no_test_unittest.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.i lib/googletest-master/googletest/test/gtest_no_test_unittest.s: lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_no_test_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_no_test_unittest.cc.s lib/googletest-master/googletest/test/gtest_pred_impl_unittest.obj: lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_pred_impl_unittest.obj # target to build an object file lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.obj lib/googletest-master/googletest/test/gtest_pred_impl_unittest.i: lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_pred_impl_unittest.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.i lib/googletest-master/googletest/test/gtest_pred_impl_unittest.s: lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_pred_impl_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_pred_impl_unittest.cc.s lib/googletest-master/googletest/test/gtest_premature_exit_test.obj: lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_premature_exit_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.obj lib/googletest-master/googletest/test/gtest_premature_exit_test.i: lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_premature_exit_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.i lib/googletest-master/googletest/test/gtest_premature_exit_test.s: lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_premature_exit_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_premature_exit_test.cc.s lib/googletest-master/googletest/test/gtest_prod_test.obj: lib/googletest-master/googletest/test/gtest_prod_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_prod_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_prod_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_prod_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_prod_test.cc.obj lib/googletest-master/googletest/test/gtest_prod_test.i: lib/googletest-master/googletest/test/gtest_prod_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_prod_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_prod_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_prod_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_prod_test.cc.i lib/googletest-master/googletest/test/gtest_prod_test.s: lib/googletest-master/googletest/test/gtest_prod_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_prod_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_prod_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_prod_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_prod_test.cc.s lib/googletest-master/googletest/test/gtest_repeat_test.obj: lib/googletest-master/googletest/test/gtest_repeat_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_repeat_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_repeat_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_repeat_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_repeat_test.cc.obj lib/googletest-master/googletest/test/gtest_repeat_test.i: lib/googletest-master/googletest/test/gtest_repeat_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_repeat_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_repeat_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_repeat_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_repeat_test.cc.i lib/googletest-master/googletest/test/gtest_repeat_test.s: lib/googletest-master/googletest/test/gtest_repeat_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_repeat_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_repeat_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_repeat_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_repeat_test.cc.s lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.obj: lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.obj lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.i: lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.i lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.s: lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.cc.s lib/googletest-master/googletest/test/gtest_skip_test.obj: lib/googletest-master/googletest/test/gtest_skip_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_skip_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_skip_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_skip_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_skip_test.cc.obj lib/googletest-master/googletest/test/gtest_skip_test.i: lib/googletest-master/googletest/test/gtest_skip_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_skip_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_skip_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_skip_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_skip_test.cc.i lib/googletest-master/googletest/test/gtest_skip_test.s: lib/googletest-master/googletest/test/gtest_skip_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_skip_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_skip_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_skip_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_skip_test.cc.s lib/googletest-master/googletest/test/gtest_sole_header_test.obj: lib/googletest-master/googletest/test/gtest_sole_header_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_sole_header_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_sole_header_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_sole_header_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_sole_header_test.cc.obj lib/googletest-master/googletest/test/gtest_sole_header_test.i: lib/googletest-master/googletest/test/gtest_sole_header_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_sole_header_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_sole_header_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_sole_header_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_sole_header_test.cc.i lib/googletest-master/googletest/test/gtest_sole_header_test.s: lib/googletest-master/googletest/test/gtest_sole_header_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_sole_header_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_sole_header_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_sole_header_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_sole_header_test.cc.s lib/googletest-master/googletest/test/gtest_stress_test.obj: lib/googletest-master/googletest/test/gtest_stress_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_stress_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_stress_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_stress_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_stress_test.cc.obj lib/googletest-master/googletest/test/gtest_stress_test.i: lib/googletest-master/googletest/test/gtest_stress_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_stress_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_stress_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_stress_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_stress_test.cc.i lib/googletest-master/googletest/test/gtest_stress_test.s: lib/googletest-master/googletest/test/gtest_stress_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_stress_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_stress_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_stress_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_stress_test.cc.s lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.obj: lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.obj lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.i: lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.i lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.s: lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.cc.s lib/googletest-master/googletest/test/gtest_testbridge_test_.obj: lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_testbridge_test_.obj # target to build an object file lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.obj lib/googletest-master/googletest/test/gtest_testbridge_test_.i: lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_testbridge_test_.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.i lib/googletest-master/googletest/test/gtest_testbridge_test_.s: lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_testbridge_test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_testbridge_test_.cc.s lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.obj: lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.obj # target to build an object file lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.obj lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.i: lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.i lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.s: lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.cc.s lib/googletest-master/googletest/test/gtest_unittest.obj: lib/googletest-master/googletest/test/gtest_unittest.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_unittest.obj # target to build an object file lib/googletest-master/googletest/test/gtest_unittest.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_unittest.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_unittest.cc.obj lib/googletest-master/googletest/test/gtest_unittest.i: lib/googletest-master/googletest/test/gtest_unittest.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_unittest.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_unittest.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_unittest.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_unittest.cc.i lib/googletest-master/googletest/test/gtest_unittest.s: lib/googletest-master/googletest/test/gtest_unittest.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_unittest.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_unittest.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_unittest.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_unittest.cc.s lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.obj: lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.obj # target to build an object file lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.obj lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.i: lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.i lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.s: lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.cc.s lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.obj: lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.obj # target to build an object file lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.obj lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.i: lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.i lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.s: lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.cc.s lib/googletest-master/googletest/test/gtest_xml_output_unittest_.obj: lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_xml_output_unittest_.obj # target to build an object file lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.obj .PHONY : lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.obj lib/googletest-master/googletest/test/gtest_xml_output_unittest_.i: lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_xml_output_unittest_.i # target to preprocess a source file lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.i .PHONY : lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.i lib/googletest-master/googletest/test/gtest_xml_output_unittest_.s: lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_xml_output_unittest_.s # target to generate assembly for a file lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.s .PHONY : lib/googletest-master/googletest/test/gtest_xml_output_unittest_.cc.s lib/googletest-master/googletest/test/production.obj: lib/googletest-master/googletest/test/production.cc.obj .PHONY : lib/googletest-master/googletest/test/production.obj # target to build an object file lib/googletest-master/googletest/test/production.cc.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/production.cc.obj .PHONY : lib/googletest-master/googletest/test/production.cc.obj lib/googletest-master/googletest/test/production.i: lib/googletest-master/googletest/test/production.cc.i .PHONY : lib/googletest-master/googletest/test/production.i # target to preprocess a source file lib/googletest-master/googletest/test/production.cc.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/production.cc.i .PHONY : lib/googletest-master/googletest/test/production.cc.i lib/googletest-master/googletest/test/production.s: lib/googletest-master/googletest/test/production.cc.s .PHONY : lib/googletest-master/googletest/test/production.s # target to generate assembly for a file lib/googletest-master/googletest/test/production.cc.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/lib/googletest-master/googletest/test/production.cc.s .PHONY : lib/googletest-master/googletest/test/production.cc.s main.obj: main.cpp.obj .PHONY : main.obj # target to build an object file main.cpp.obj: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/main.cpp.obj .PHONY : main.cpp.obj main.i: main.cpp.i .PHONY : main.i # target to preprocess a source file main.cpp.i: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/main.cpp.i .PHONY : main.cpp.i main.s: main.cpp.s .PHONY : main.s # target to generate assembly for a file main.cpp.s: $(MAKE) $(MAKESILENT) -f CMakeFiles\aeda2021_p01.dir\build.make CMakeFiles/aeda2021_p01.dir/main.cpp.s .PHONY : main.cpp.s # Help Target help: @echo The following are some of the valid targets for this Makefile: @echo ... all (the default if no target is provided) @echo ... clean @echo ... depend @echo ... edit_cache @echo ... rebuild_cache @echo ... aeda2021_p01 @echo ... Tests/parque.obj @echo ... Tests/parque.i @echo ... Tests/parque.s @echo ... Tests/tests.obj @echo ... Tests/tests.i @echo ... Tests/tests.s @echo ... lib/googletest-master/googlemock/src/gmock-all.obj @echo ... lib/googletest-master/googlemock/src/gmock-all.i @echo ... lib/googletest-master/googlemock/src/gmock-all.s @echo ... lib/googletest-master/googlemock/src/gmock-cardinalities.obj @echo ... lib/googletest-master/googlemock/src/gmock-cardinalities.i @echo ... lib/googletest-master/googlemock/src/gmock-cardinalities.s @echo ... lib/googletest-master/googlemock/src/gmock-internal-utils.obj @echo ... lib/googletest-master/googlemock/src/gmock-internal-utils.i @echo ... lib/googletest-master/googlemock/src/gmock-internal-utils.s @echo ... lib/googletest-master/googlemock/src/gmock-matchers.obj @echo ... lib/googletest-master/googlemock/src/gmock-matchers.i @echo ... lib/googletest-master/googlemock/src/gmock-matchers.s @echo ... lib/googletest-master/googlemock/src/gmock-spec-builders.obj @echo ... lib/googletest-master/googlemock/src/gmock-spec-builders.i @echo ... lib/googletest-master/googlemock/src/gmock-spec-builders.s @echo ... lib/googletest-master/googlemock/src/gmock.obj @echo ... lib/googletest-master/googlemock/src/gmock.i @echo ... lib/googletest-master/googlemock/src/gmock.s @echo ... lib/googletest-master/googlemock/src/gmock_main.obj @echo ... lib/googletest-master/googlemock/src/gmock_main.i @echo ... lib/googletest-master/googlemock/src/gmock_main.s @echo ... lib/googletest-master/googlemock/test/gmock-actions_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-actions_test.i @echo ... lib/googletest-master/googlemock/test/gmock-actions_test.s @echo ... lib/googletest-master/googlemock/test/gmock-cardinalities_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-cardinalities_test.i @echo ... lib/googletest-master/googlemock/test/gmock-cardinalities_test.s @echo ... lib/googletest-master/googlemock/test/gmock-function-mocker_nc.obj @echo ... lib/googletest-master/googlemock/test/gmock-function-mocker_nc.i @echo ... lib/googletest-master/googlemock/test/gmock-function-mocker_nc.s @echo ... lib/googletest-master/googlemock/test/gmock-function-mocker_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-function-mocker_test.i @echo ... lib/googletest-master/googlemock/test/gmock-function-mocker_test.s @echo ... lib/googletest-master/googlemock/test/gmock-generated-actions_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-generated-actions_test.i @echo ... lib/googletest-master/googlemock/test/gmock-generated-actions_test.s @echo ... lib/googletest-master/googlemock/test/gmock-internal-utils_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-internal-utils_test.i @echo ... lib/googletest-master/googlemock/test/gmock-internal-utils_test.s @echo ... lib/googletest-master/googlemock/test/gmock-matchers_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-matchers_test.i @echo ... lib/googletest-master/googlemock/test/gmock-matchers_test.s @echo ... lib/googletest-master/googlemock/test/gmock-more-actions_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-more-actions_test.i @echo ... lib/googletest-master/googlemock/test/gmock-more-actions_test.s @echo ... lib/googletest-master/googlemock/test/gmock-nice-strict_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-nice-strict_test.i @echo ... lib/googletest-master/googlemock/test/gmock-nice-strict_test.s @echo ... lib/googletest-master/googlemock/test/gmock-port_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-port_test.i @echo ... lib/googletest-master/googlemock/test/gmock-port_test.s @echo ... lib/googletest-master/googlemock/test/gmock-pp-string_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-pp-string_test.i @echo ... lib/googletest-master/googlemock/test/gmock-pp-string_test.s @echo ... lib/googletest-master/googlemock/test/gmock-pp_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-pp_test.i @echo ... lib/googletest-master/googlemock/test/gmock-pp_test.s @echo ... lib/googletest-master/googlemock/test/gmock-spec-builders_test.obj @echo ... lib/googletest-master/googlemock/test/gmock-spec-builders_test.i @echo ... lib/googletest-master/googlemock/test/gmock-spec-builders_test.s @echo ... lib/googletest-master/googlemock/test/gmock_all_test.obj @echo ... lib/googletest-master/googlemock/test/gmock_all_test.i @echo ... lib/googletest-master/googlemock/test/gmock_all_test.s @echo ... lib/googletest-master/googlemock/test/gmock_ex_test.obj @echo ... lib/googletest-master/googlemock/test/gmock_ex_test.i @echo ... lib/googletest-master/googlemock/test/gmock_ex_test.s @echo ... lib/googletest-master/googlemock/test/gmock_leak_test_.obj @echo ... lib/googletest-master/googlemock/test/gmock_leak_test_.i @echo ... lib/googletest-master/googlemock/test/gmock_leak_test_.s @echo ... lib/googletest-master/googlemock/test/gmock_link2_test.obj @echo ... lib/googletest-master/googlemock/test/gmock_link2_test.i @echo ... lib/googletest-master/googlemock/test/gmock_link2_test.s @echo ... lib/googletest-master/googlemock/test/gmock_link_test.obj @echo ... lib/googletest-master/googlemock/test/gmock_link_test.i @echo ... lib/googletest-master/googlemock/test/gmock_link_test.s @echo ... lib/googletest-master/googlemock/test/gmock_output_test_.obj @echo ... lib/googletest-master/googlemock/test/gmock_output_test_.i @echo ... lib/googletest-master/googlemock/test/gmock_output_test_.s @echo ... lib/googletest-master/googlemock/test/gmock_stress_test.obj @echo ... lib/googletest-master/googlemock/test/gmock_stress_test.i @echo ... lib/googletest-master/googlemock/test/gmock_stress_test.s @echo ... lib/googletest-master/googlemock/test/gmock_test.obj @echo ... lib/googletest-master/googlemock/test/gmock_test.i @echo ... lib/googletest-master/googlemock/test/gmock_test.s @echo ... lib/googletest-master/googletest/samples/sample1.obj @echo ... lib/googletest-master/googletest/samples/sample1.i @echo ... lib/googletest-master/googletest/samples/sample1.s @echo ... lib/googletest-master/googletest/samples/sample10_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample10_unittest.i @echo ... lib/googletest-master/googletest/samples/sample10_unittest.s @echo ... lib/googletest-master/googletest/samples/sample1_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample1_unittest.i @echo ... lib/googletest-master/googletest/samples/sample1_unittest.s @echo ... lib/googletest-master/googletest/samples/sample2.obj @echo ... lib/googletest-master/googletest/samples/sample2.i @echo ... lib/googletest-master/googletest/samples/sample2.s @echo ... lib/googletest-master/googletest/samples/sample2_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample2_unittest.i @echo ... lib/googletest-master/googletest/samples/sample2_unittest.s @echo ... lib/googletest-master/googletest/samples/sample3_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample3_unittest.i @echo ... lib/googletest-master/googletest/samples/sample3_unittest.s @echo ... lib/googletest-master/googletest/samples/sample4.obj @echo ... lib/googletest-master/googletest/samples/sample4.i @echo ... lib/googletest-master/googletest/samples/sample4.s @echo ... lib/googletest-master/googletest/samples/sample4_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample4_unittest.i @echo ... lib/googletest-master/googletest/samples/sample4_unittest.s @echo ... lib/googletest-master/googletest/samples/sample5_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample5_unittest.i @echo ... lib/googletest-master/googletest/samples/sample5_unittest.s @echo ... lib/googletest-master/googletest/samples/sample6_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample6_unittest.i @echo ... lib/googletest-master/googletest/samples/sample6_unittest.s @echo ... lib/googletest-master/googletest/samples/sample7_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample7_unittest.i @echo ... lib/googletest-master/googletest/samples/sample7_unittest.s @echo ... lib/googletest-master/googletest/samples/sample8_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample8_unittest.i @echo ... lib/googletest-master/googletest/samples/sample8_unittest.s @echo ... lib/googletest-master/googletest/samples/sample9_unittest.obj @echo ... lib/googletest-master/googletest/samples/sample9_unittest.i @echo ... lib/googletest-master/googletest/samples/sample9_unittest.s @echo ... lib/googletest-master/googletest/src/gtest-all.obj @echo ... lib/googletest-master/googletest/src/gtest-all.i @echo ... lib/googletest-master/googletest/src/gtest-all.s @echo ... lib/googletest-master/googletest/src/gtest-death-test.obj @echo ... lib/googletest-master/googletest/src/gtest-death-test.i @echo ... lib/googletest-master/googletest/src/gtest-death-test.s @echo ... lib/googletest-master/googletest/src/gtest-filepath.obj @echo ... lib/googletest-master/googletest/src/gtest-filepath.i @echo ... lib/googletest-master/googletest/src/gtest-filepath.s @echo ... lib/googletest-master/googletest/src/gtest-matchers.obj @echo ... lib/googletest-master/googletest/src/gtest-matchers.i @echo ... lib/googletest-master/googletest/src/gtest-matchers.s @echo ... lib/googletest-master/googletest/src/gtest-port.obj @echo ... lib/googletest-master/googletest/src/gtest-port.i @echo ... lib/googletest-master/googletest/src/gtest-port.s @echo ... lib/googletest-master/googletest/src/gtest-printers.obj @echo ... lib/googletest-master/googletest/src/gtest-printers.i @echo ... lib/googletest-master/googletest/src/gtest-printers.s @echo ... lib/googletest-master/googletest/src/gtest-test-part.obj @echo ... lib/googletest-master/googletest/src/gtest-test-part.i @echo ... lib/googletest-master/googletest/src/gtest-test-part.s @echo ... lib/googletest-master/googletest/src/gtest-typed-test.obj @echo ... lib/googletest-master/googletest/src/gtest-typed-test.i @echo ... lib/googletest-master/googletest/src/gtest-typed-test.s @echo ... lib/googletest-master/googletest/src/gtest.obj @echo ... lib/googletest-master/googletest/src/gtest.i @echo ... lib/googletest-master/googletest/src/gtest.s @echo ... lib/googletest-master/googletest/src/gtest_main.obj @echo ... lib/googletest-master/googletest/src/gtest_main.i @echo ... lib/googletest-master/googletest/src/gtest_main.s @echo ... lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.obj @echo ... lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.i @echo ... lib/googletest-master/googletest/test/googletest-break-on-failure-unittest_.s @echo ... lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.i @echo ... lib/googletest-master/googletest/test/googletest-catch-exceptions-test_.s @echo ... lib/googletest-master/googletest/test/googletest-color-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-color-test_.i @echo ... lib/googletest-master/googletest/test/googletest-color-test_.s @echo ... lib/googletest-master/googletest/test/googletest-death-test-test.obj @echo ... lib/googletest-master/googletest/test/googletest-death-test-test.i @echo ... lib/googletest-master/googletest/test/googletest-death-test-test.s @echo ... lib/googletest-master/googletest/test/googletest-death-test_ex_test.obj @echo ... lib/googletest-master/googletest/test/googletest-death-test_ex_test.i @echo ... lib/googletest-master/googletest/test/googletest-death-test_ex_test.s @echo ... lib/googletest-master/googletest/test/googletest-env-var-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-env-var-test_.i @echo ... lib/googletest-master/googletest/test/googletest-env-var-test_.s @echo ... lib/googletest-master/googletest/test/googletest-failfast-unittest_.obj @echo ... lib/googletest-master/googletest/test/googletest-failfast-unittest_.i @echo ... lib/googletest-master/googletest/test/googletest-failfast-unittest_.s @echo ... lib/googletest-master/googletest/test/googletest-filepath-test.obj @echo ... lib/googletest-master/googletest/test/googletest-filepath-test.i @echo ... lib/googletest-master/googletest/test/googletest-filepath-test.s @echo ... lib/googletest-master/googletest/test/googletest-filter-unittest_.obj @echo ... lib/googletest-master/googletest/test/googletest-filter-unittest_.i @echo ... lib/googletest-master/googletest/test/googletest-filter-unittest_.s @echo ... lib/googletest-master/googletest/test/googletest-list-tests-unittest_.obj @echo ... lib/googletest-master/googletest/test/googletest-list-tests-unittest_.i @echo ... lib/googletest-master/googletest/test/googletest-list-tests-unittest_.s @echo ... lib/googletest-master/googletest/test/googletest-listener-test.obj @echo ... lib/googletest-master/googletest/test/googletest-listener-test.i @echo ... lib/googletest-master/googletest/test/googletest-listener-test.s @echo ... lib/googletest-master/googletest/test/googletest-message-test.obj @echo ... lib/googletest-master/googletest/test/googletest-message-test.i @echo ... lib/googletest-master/googletest/test/googletest-message-test.s @echo ... lib/googletest-master/googletest/test/googletest-options-test.obj @echo ... lib/googletest-master/googletest/test/googletest-options-test.i @echo ... lib/googletest-master/googletest/test/googletest-options-test.s @echo ... lib/googletest-master/googletest/test/googletest-output-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-output-test_.i @echo ... lib/googletest-master/googletest/test/googletest-output-test_.s @echo ... lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.i @echo ... lib/googletest-master/googletest/test/googletest-param-test-invalid-name1-test_.s @echo ... lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.i @echo ... lib/googletest-master/googletest/test/googletest-param-test-invalid-name2-test_.s @echo ... lib/googletest-master/googletest/test/googletest-param-test-test.obj @echo ... lib/googletest-master/googletest/test/googletest-param-test-test.i @echo ... lib/googletest-master/googletest/test/googletest-param-test-test.s @echo ... lib/googletest-master/googletest/test/googletest-param-test2-test.obj @echo ... lib/googletest-master/googletest/test/googletest-param-test2-test.i @echo ... lib/googletest-master/googletest/test/googletest-param-test2-test.s @echo ... lib/googletest-master/googletest/test/googletest-port-test.obj @echo ... lib/googletest-master/googletest/test/googletest-port-test.i @echo ... lib/googletest-master/googletest/test/googletest-port-test.s @echo ... lib/googletest-master/googletest/test/googletest-printers-test.obj @echo ... lib/googletest-master/googletest/test/googletest-printers-test.i @echo ... lib/googletest-master/googletest/test/googletest-printers-test.s @echo ... lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.i @echo ... lib/googletest-master/googletest/test/googletest-setuptestsuite-test_.s @echo ... lib/googletest-master/googletest/test/googletest-shuffle-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-shuffle-test_.i @echo ... lib/googletest-master/googletest/test/googletest-shuffle-test_.s @echo ... lib/googletest-master/googletest/test/googletest-test-part-test.obj @echo ... lib/googletest-master/googletest/test/googletest-test-part-test.i @echo ... lib/googletest-master/googletest/test/googletest-test-part-test.s @echo ... lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.i @echo ... lib/googletest-master/googletest/test/googletest-throw-on-failure-test_.s @echo ... lib/googletest-master/googletest/test/googletest-uninitialized-test_.obj @echo ... lib/googletest-master/googletest/test/googletest-uninitialized-test_.i @echo ... lib/googletest-master/googletest/test/googletest-uninitialized-test_.s @echo ... lib/googletest-master/googletest/test/gtest-typed-test2_test.obj @echo ... lib/googletest-master/googletest/test/gtest-typed-test2_test.i @echo ... lib/googletest-master/googletest/test/gtest-typed-test2_test.s @echo ... lib/googletest-master/googletest/test/gtest-typed-test_test.obj @echo ... lib/googletest-master/googletest/test/gtest-typed-test_test.i @echo ... lib/googletest-master/googletest/test/gtest-typed-test_test.s @echo ... lib/googletest-master/googletest/test/gtest-unittest-api_test.obj @echo ... lib/googletest-master/googletest/test/gtest-unittest-api_test.i @echo ... lib/googletest-master/googletest/test/gtest-unittest-api_test.s @echo ... lib/googletest-master/googletest/test/gtest_all_test.obj @echo ... lib/googletest-master/googletest/test/gtest_all_test.i @echo ... lib/googletest-master/googletest/test/gtest_all_test.s @echo ... lib/googletest-master/googletest/test/gtest_assert_by_exception_test.obj @echo ... lib/googletest-master/googletest/test/gtest_assert_by_exception_test.i @echo ... lib/googletest-master/googletest/test/gtest_assert_by_exception_test.s @echo ... lib/googletest-master/googletest/test/gtest_environment_test.obj @echo ... lib/googletest-master/googletest/test/gtest_environment_test.i @echo ... lib/googletest-master/googletest/test/gtest_environment_test.s @echo ... lib/googletest-master/googletest/test/gtest_help_test_.obj @echo ... lib/googletest-master/googletest/test/gtest_help_test_.i @echo ... lib/googletest-master/googletest/test/gtest_help_test_.s @echo ... lib/googletest-master/googletest/test/gtest_list_output_unittest_.obj @echo ... lib/googletest-master/googletest/test/gtest_list_output_unittest_.i @echo ... lib/googletest-master/googletest/test/gtest_list_output_unittest_.s @echo ... lib/googletest-master/googletest/test/gtest_main_unittest.obj @echo ... lib/googletest-master/googletest/test/gtest_main_unittest.i @echo ... lib/googletest-master/googletest/test/gtest_main_unittest.s @echo ... lib/googletest-master/googletest/test/gtest_no_test_unittest.obj @echo ... lib/googletest-master/googletest/test/gtest_no_test_unittest.i @echo ... lib/googletest-master/googletest/test/gtest_no_test_unittest.s @echo ... lib/googletest-master/googletest/test/gtest_pred_impl_unittest.obj @echo ... lib/googletest-master/googletest/test/gtest_pred_impl_unittest.i @echo ... lib/googletest-master/googletest/test/gtest_pred_impl_unittest.s @echo ... lib/googletest-master/googletest/test/gtest_premature_exit_test.obj @echo ... lib/googletest-master/googletest/test/gtest_premature_exit_test.i @echo ... lib/googletest-master/googletest/test/gtest_premature_exit_test.s @echo ... lib/googletest-master/googletest/test/gtest_prod_test.obj @echo ... lib/googletest-master/googletest/test/gtest_prod_test.i @echo ... lib/googletest-master/googletest/test/gtest_prod_test.s @echo ... lib/googletest-master/googletest/test/gtest_repeat_test.obj @echo ... lib/googletest-master/googletest/test/gtest_repeat_test.i @echo ... lib/googletest-master/googletest/test/gtest_repeat_test.s @echo ... lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.obj @echo ... lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.i @echo ... lib/googletest-master/googletest/test/gtest_skip_in_environment_setup_test.s @echo ... lib/googletest-master/googletest/test/gtest_skip_test.obj @echo ... lib/googletest-master/googletest/test/gtest_skip_test.i @echo ... lib/googletest-master/googletest/test/gtest_skip_test.s @echo ... lib/googletest-master/googletest/test/gtest_sole_header_test.obj @echo ... lib/googletest-master/googletest/test/gtest_sole_header_test.i @echo ... lib/googletest-master/googletest/test/gtest_sole_header_test.s @echo ... lib/googletest-master/googletest/test/gtest_stress_test.obj @echo ... lib/googletest-master/googletest/test/gtest_stress_test.i @echo ... lib/googletest-master/googletest/test/gtest_stress_test.s @echo ... lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.obj @echo ... lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.i @echo ... lib/googletest-master/googletest/test/gtest_test_macro_stack_footprint_test.s @echo ... lib/googletest-master/googletest/test/gtest_testbridge_test_.obj @echo ... lib/googletest-master/googletest/test/gtest_testbridge_test_.i @echo ... lib/googletest-master/googletest/test/gtest_testbridge_test_.s @echo ... lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.obj @echo ... lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.i @echo ... lib/googletest-master/googletest/test/gtest_throw_on_failure_ex_test.s @echo ... lib/googletest-master/googletest/test/gtest_unittest.obj @echo ... lib/googletest-master/googletest/test/gtest_unittest.i @echo ... lib/googletest-master/googletest/test/gtest_unittest.s @echo ... lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.obj @echo ... lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.i @echo ... lib/googletest-master/googletest/test/gtest_xml_outfile1_test_.s @echo ... lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.obj @echo ... lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.i @echo ... lib/googletest-master/googletest/test/gtest_xml_outfile2_test_.s @echo ... lib/googletest-master/googletest/test/gtest_xml_output_unittest_.obj @echo ... lib/googletest-master/googletest/test/gtest_xml_output_unittest_.i @echo ... lib/googletest-master/googletest/test/gtest_xml_output_unittest_.s @echo ... lib/googletest-master/googletest/test/production.obj @echo ... lib/googletest-master/googletest/test/production.i @echo ... lib/googletest-master/googletest/test/production.s @echo ... main.obj @echo ... main.i @echo ... main.s .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles\Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>var searchData= [ ['clients_225',['clients',['../class_pitch.html#a4f88464ae1447b4636af98f59ebda6ea',1,'Pitch']]] ]; <file_sep>var searchData= [ ['dog_2',['Dog',['../class_dog.html',1,'']]] ]; <file_sep>/* * Cinema.cpp */ #include "Cinema.h" Cinema::Cinema(string nm, unsigned d, unsigned nr) : name(nm), distance(d), numberOfRooms(nr), timetable(FilmTime(0, NULL, 0)) {} Cinema::Cinema(string nm, unsigned d, unsigned nr, list <string> ls) : name(nm), distance(d), numberOfRooms(nr), services(ls), timetable(FilmTime(0, NULL, 0)) {} Cinema::~Cinema() {} string Cinema::getName() const { return name; } unsigned Cinema::getDistance() const { return distance; } list <string> Cinema::getServices() const { return services; } BST<FilmTime> Cinema::getTimetable() const { return timetable; } void Cinema::addService(string service1) { services.push_back(service1); } void Cinema::addFilmTime(const FilmTime &ft1) { timetable.insert(ft1); } // TODO bool Cinema::operator<(const Cinema &cr) const { if (distance > cr.getDistance()) return true; else if (distance == cr.getDistance() && services.size() < cr.getServices().size()) return true; return false; /* //original resolution from https://github.com/andrefmrocha if(this->getDistance() == cr.getDistance()) return this->getServices().size() < cr.getServices().size(); return this->getDistance() > cr.getDistance(); */ } //a1 Film *Cinema::filmAtHour(unsigned &h1) const { BSTItrIn<FilmTime> itr(timetable); while (!itr.isAtEnd()) { FilmTime previous = itr.retrieve(); if (previous.getHour() > h1) { return NULL; } itr.advance(); if (previous.getHour() < h1 && itr.retrieve() > h1) { h1 = previous.getHour(); return previous.getFilm(); } if (itr.retrieve() == h1) { itr.retrieve().getFilm(); } } /* //original resolution from https://github.com/andrefmrocha BSTItrIn<FilmTime> it(this->timetable); FilmTime prev(h1, NULL, 0); unsigned counter = 0; while(!it.isAtEnd()) { counter ++; if(it.retrieve().getHour() == h1) return it.retrieve().getFilm(); if(it.retrieve().getHour() > h1) break; prev = it.retrieve(); it.advance(); } if(counter <=1) { return NULL; } h1 = prev.getHour(); return prev.getFilm(); */ } //a2 bool Cinema::modifyHour(unsigned h1, unsigned room1, unsigned h2) { BSTItrIn<FilmTime> itr(timetable); while (!itr.isAtEnd()) { if (itr.retrieve().getRoomID() == room1) { if (itr.retrieve().getHour() != h1) { //there is no movie to be exhibit at h1 in room1 } if (itr.retrieve().getHour() == h2) { //room1 is occupied at h2 return false; } FilmTime schedule = itr.retrieve(); timetable.remove(itr.retrieve()); schedule.setHour(h2); timetable.insert(schedule); return true; } itr.advance(); } return false; //there is not even a room 1 /* //original resolution from https://github.com/andrefmrocha FilmTime mov(h1, NULL, 0); BSTItrIn<FilmTime> it(this->timetable); while(!it.isAtEnd()) { if(it.retrieve().getRoomID() == room1 && it.retrieve().getHour() == h1) { mov = it.retrieve(); } if(it.retrieve().getRoomID() == room1 && it.retrieve().getHour() == h2) return false; it.advance(); } if(mov == FilmTime(h1, NULL, 0)) { return false; } this->timetable.remove(mov); mov.setHour(h2); this->timetable.insert(mov); return true; */ } //a3 unsigned Cinema::addFilm(Film *f1, unsigned h1) { //original resolution from https://github.com/andrefmrocha bool found = false; for (unsigned id = 1; id <= numberOfRooms; id++) { found = false; BSTItrIn<FilmTime> it(timetable); while (!it.isAtEnd()) { if (it.retrieve().getRoomID() == id && it.retrieve().getHour() == h1) { found = true; break; } it.advance(); } if (!found) { timetable.insert(FilmTime(h1, f1, id)); return id; } } return 0; } <file_sep>#include "Gallery.h" #include "Paint.h" #include <ostream> #include <algorithm> using namespace std; Gallery::Gallery(vector<Paint*> c): catalog(PaintCatalogItem("", "", 0, 0.00)), collection(c) { } vector<Paint*> Gallery::getCollection() const { return collection; } void Gallery::setCollection(vector<Paint*> c) { collection = c; } priority_queue<ExhibitionItem> Gallery::getPaintsToShow() const { return paintsToShow; } HashTableAuthorRecord Gallery::getAuthorRecords () const { return authorRecords; } void Gallery::addAuthorRecord(AuthorRecord ar) { authorRecords.insert(ar); } void Gallery::generateCatalog() { catalog.makeEmpty(); for(int i = 0; i < collection.size(); i++) { catalog.insert(collection[i]); } } BST<PaintCatalogItem> Gallery::getCatalog() const { return catalog; } void Gallery::prepareExhibition() { while( !paintsToShow.empty()) paintsToShow.pop(); for(int i = 0; i < collection.size(); i++) { ExhibitionItem ei(collection[i]); paintsToShow.push(ei); } } //------------------------------------------------------------------------------- //TODO vector<Paint*> Gallery::getPaintsBy(string a) const { vector<Paint*> res; BSTItrIn<PaintCatalogItem> itr(catalog); while (!itr.isAtEnd()) { if (itr.retrieve().getAuthor() == a) { res.push_back(itr.retrieve().getPaint()); } itr.advance(); } return res; } //TODO vector<Paint*> Gallery::getPaintsBetween(int y1, int y2) const { vector<Paint*> res; BSTItrIn<PaintCatalogItem> itr(catalog); while (!itr.isAtEnd()) { if (itr.retrieve().getYear() >= y1 && itr.retrieve().getYear() <= y2) { res.push_back(itr.retrieve().getPaint()); } itr.advance(); } return res; } //TODO bool Gallery::updateTitle(Paint* p, string tnew) { BSTItrIn<PaintCatalogItem> itr(catalog); while (!itr.isAtEnd()) { if (itr.retrieve() == p) { if (!catalog.remove(itr.retrieve())) { return false; } PaintCatalogItem updated(p->getAuthor(), tnew, p->getYear(), p->getPrice()); catalog.insert(updated); return true; } itr.advance(); } return false; /* if(!catalog.remove(PaintCatalogItem(p))) { return false; } PaintCatalogItem updated(p->getAuthor(), tnew, p->getYear(), p->getPrice()); catalog.insert(updated); return true; */ } //TODO int Gallery::recordAvailablePainters() { for (auto p = collection.begin(); p != collection.end(); p++) { bool found = false; for (auto ar = authorRecords.begin(); ar != authorRecords.end(); ar++) { if (ar->getAuthor() == (*p)->getAuthor()) { AuthorRecord newRecord(ar->getAuthor(), ar->getAvailablePaints() + 1, ar->getTotalSells()); authorRecords.erase(ar); authorRecords.insert(newRecord); found = true; break; } } if (!found) { AuthorRecord record((*p)->getAuthor(), 1, 0); authorRecords.insert(record); } } return authorRecords.size(); } //TODO double Gallery::sellPaint(string a, string t) { double transaction = 0; for (auto ar = authorRecords.begin(); ar != authorRecords.end(); ar++) { if (ar->getAuthor() == a) { for (auto p = collection.begin(); p != collection.end(); p++) { if ((*p)->getAuthor() == a && (*p)->getTitle() == t) { transaction = (*p)->getPrice(); //saves the transaction value in order to update the record collection.erase(p); //updates collection by removing the sold paint break; } } AuthorRecord author(ar->getAuthor(), ar->getAvailablePaints() - 1, ar->getTotalSells() + transaction); authorRecords.erase(ar); //removes old record from authorRecords authorRecords.insert(author); //inserts updated record in the authorRecords break; } } return transaction; } //TODO double Gallery::totalSells() const { double totalAmount = 0; for (auto ar = authorRecords.begin(); ar != authorRecords.end(); ar++) { totalAmount += ar->getTotalSells(); } return totalAmount; } //TODO int Gallery::itemExhibitionOrder(string a, string t) { priority_queue<ExhibitionItem> temp = paintsToShow; int order = 1; bool found = false; while (!temp.empty()) { if (temp.top().getAuthor() == a && temp.top().getTitle() == t) { found = true; break; } temp.pop(); order++; } if (found) return order; else return 0; } //TODO vector<Paint*> Gallery::nBestExhibition(int n, int maxPerYear) { vector<Paint*> exhibition; priority_queue<ExhibitionItem> aux; //keeps track of the paints that are not added to the exhibition int countYear = 0, currYear = paintsToShow.top().getYear(); while (true) { if (paintsToShow.empty()) { //there are no more paints that could potentially be added to the exhibition break; } else if (exhibition.size() == n && !paintsToShow.empty()) { //the paints left in the queue need to be transferred to the aux queue otherwise will get lost while (!paintsToShow.empty()) { aux.push(paintsToShow.top()); paintsToShow.pop(); } break; } if (paintsToShow.top().getYear() == currYear) { if (countYear == maxPerYear) { aux.push(paintsToShow.top()); } else { exhibition.push_back(paintsToShow.top().getPaint()); countYear++; } paintsToShow.pop(); } else { countYear = 0; currYear = paintsToShow.top().getYear(); } } paintsToShow = aux; return exhibition; } <file_sep>#include "veterinary.h" #include <sstream> using namespace std; Veterinary::Veterinary(string nome, int cod) { name = nome; codOrder = cod; } string Veterinary::getName() const { return name; } string Veterinary::getInfo() const { stringstream info; info << name << ", " << codOrder; return info.str(); } <file_sep>var searchData= [ ['isbusy_180',['isBusy',['../class_service_provider.html#a1d55c2846995532a8a387e885313d48c',1,'ServiceProvider']]] ]; <file_sep>#include "vehicle.h" #include <iostream> using namespace std; Vehicle::Vehicle(string b, int m, int y) { brand = b; month = m; year = y; } MotorVehicle::MotorVehicle(string b, int m, int y, string f, int cyl) : Vehicle(b, m, y) { fuel = f; cylinder = cyl; } Car::Car(string b, int m, int y, string f, int cyl) : MotorVehicle(b, m, y, f, cyl) { } Truck::Truck(string b, int m, int y, string f, int cyl, int ml) : MotorVehicle(b, m, y, f, cyl) { maximumLoad = ml; } Bicycle::Bicycle(string b, int m, int y, string t) :Vehicle(b, m, y) { type = t; } string MotorVehicle::getFuel() const { return fuel; } int Vehicle::getYear() const { return year; } string Vehicle::getBrand() const { return brand; } int Vehicle::info() const { return 3; } int MotorVehicle::info() const { return 5; } int MotorVehicle::info(ostream &o) const { o << year << "/" << month << " brand: " << brand << " fuel: " << fuel << " cylinder: " << cylinder << endl; return 5; } int Car::info() const { return 5; } int Car::info(ostream &o) const { o << year << "/" << month << " brand: " << brand << " fuel: " << fuel << " cylinder: " << cylinder << endl; return 5; } int Truck::info() const { return 6; } int Truck::info(ostream &o) const { o << year << "/" << month << ", brand: " << brand << ", fuel: " << fuel << ", cylinder: " << cylinder << ", maximum load: " << maximumLoad << endl; return 6; } int Bicycle::info() const { return 4; } int Bicycle::info(ostream &o) const { o << year << "/" << month << " brand: " << brand << " type: " << type << endl; return 6; } bool Vehicle::operator < (const Vehicle & v) const { if (year < v.year) return true; else if (year == v.year & month < v.month) return true; return false; } float MotorVehicle::calculateTax() const { if (fuel == "gas") { if (cylinder <= 1000) { if (year > 1995) return 14.56; else return 8.10; } else if (cylinder > 1000 & cylinder <= 1300) { if (year > 1995) return 29.06; else return 14.56; } else if (cylinder > 1300 & cylinder <= 1750) { if (year > 1995) return 45.15; else return 22.65; } else if (cylinder > 1750 & cylinder <= 2600) { if (year > 1995) return 113.98; else return 54.89; } else if (cylinder > 2600 & cylinder <= 3500) { if (year > 1995) return 181.17; else return 87.13; } else if (cylinder > 3500) { if (year > 1995) return 320.89; else return 148.37; } } else { if (cylinder <= 1500) { if (year > 1995) return 14.56; else return 8.10; } else if (cylinder > 1500 & cylinder <= 2000) { if (year > 1995) return 29.06; else return 14.56; } else if (cylinder > 2000 & cylinder <= 3000) { if (year > 1995) return 45.15; else return 22.65; } else if (cylinder > 3000) { if (year > 1995) return 113.98; else return 54.89; } } } float Bicycle::calculateTax() const { return 0; } <file_sep>var searchData= [ ['user_5finterface_140',['User_interface',['../class_user__interface.html',1,'']]] ]; <file_sep>#include "bet.h" #include <iostream> #include <sstream> using namespace std; bool Bet::contains(unsigned num) const { return (numbers.find(num) != numbers.end()); } void Bet::generateBet(const vector<unsigned>& values, unsigned n) { for (vector<unsigned>::const_iterator it = values.begin(); it != values.end(); it++) { if (numbers.size() < n) { if (numbers.find(*it) == numbers.end()) { //value does not yet exist numbers.insert(*it); } } else break; } } unsigned Bet::countRights(const tabHInt& draw) const { unsigned int counter = 0; for (tabHInt::const_iterator it = draw.begin(); it != draw.end(); it++) { if (numbers.find(*it) != numbers.end()) { counter++; } } return counter; } int Bet::getHash() const { int hash = 0; for (tabHInt::const_iterator it = numbers.begin(); it != numbers.end(); it++) { hash += *it; } return hash; }<file_sep>#include "carPark.h" #include "insertionSort.h" #include "sequentialSearch.h" #include <algorithm> #include <vector> using namespace std; CarPark::CarPark(unsigned cap, unsigned nMaxCli): capacity(cap), numMaxClients(nMaxCli) { freePlaces=cap; } vector<InfoCard> CarPark::getClients() const { return clients; } unsigned CarPark::getNumPlaces() const { return capacity; } unsigned CarPark::getNumOccupiedPlaces() const { return capacity-freePlaces; } unsigned CarPark::getNumMaxClients() const { return numMaxClients; } unsigned CarPark::getNumClients() const { return clients.size(); } int CarPark::clientPosition(const string & name) const { InfoCard temp; temp.name = name; return sequentialSearch(clients, temp); } unsigned CarPark::getFrequency(const string &name) const { int pos = clientPosition(name); if (pos == -1) throw ClientDoesNotExist(name); return clients[pos].frequency; } bool CarPark::addClient(const string & name) { if (clients.size() == numMaxClients) return false; if (clientPosition(name) != -1) return false; InfoCard info; info.name=name; info.present=false; info.frequency=0; clients.push_back(info); return true; } // TODO: to modify bool CarPark::removeClient(const string & name) { for (vector<InfoCard>::iterator it = clients.begin(); it != clients.end(); it++) if ( (*it).name == name ) { if ( (*it).present == false ) { clients.erase(it); return true; } else return false; } return false; } bool CarPark::enter(const string & name) { if (freePlaces == 0) return false; int pos = clientPosition(name); if (pos == -1) return false; if (clients[pos].present == true) return false; clients[pos].present = true; clients[pos].frequency++; freePlaces--; return true; } bool CarPark::leave(const string & name) { int pos = clientPosition(name); if (pos == -1) return false; if (clients[pos].present == false) return false; clients[pos].present = false; freePlaces++; return true; } InfoCard CarPark::getClientAtPos(unsigned p) const { if (p > getNumClients() || p < 0) throw PositionDoesNotExist(p); InfoCard info; info.name = clients[p].name; info.frequency = clients[p].frequency; info.present = clients[p].present; return info; } void CarPark::sortClientsByFrequency() { insertionSort(clients); } bool byName(InfoCard &ic1, InfoCard &ic2) { return (ic1.name < ic2.name); } void CarPark::sortClientsByName() { sort(clients.begin(), clients.end(), byName); } vector<string> CarPark::clientsBetween(unsigned f1, unsigned f2) { vector<string> names; sortClientsByFrequency(); for(int c = 0; c < getNumClients(); c++) { if (clients[c].frequency >= f1 & clients[c].frequency <= f2) { names.push_back(clients[c].name); } } return names; } ostream & operator<<(ostream & os, const CarPark & cp) { for (int c = 0; c < cp.getNumClients(); c++) { os << "name: " << cp.getClientAtPos(c).name << ", presence: " << cp.getClientAtPos(c).present << ", frequency: " << cp.getClientAtPos(c).frequency << endl; } return os; } bool InfoCard::operator==(InfoCard &ic) const { return (name == ic.name); } bool InfoCard::operator<(InfoCard &ic) const { if (frequency == ic.frequency) return (name < ic.name); else return (frequency > ic.frequency); } <file_sep>/* * ReadingClub.h * * Created on: 11/12/2016 * Author: RRossetti */ #ifndef SRC_READINGCLUB_H_ #define SRC_READINGCLUB_H_ #include "Book.h" #include "User.h" #include "BST.h" #include <vector> #include <tr1/unordered_set> #include <queue> using namespace std; struct userRecordHash { int operator()(const UserRecord &ur) const { int hash = 0; for (unsigned i = 0; i < ur.getEMail().length(); i++) { hash = 37 * hash + ur.getEMail()[i]; } return hash; /* //original resolution from https://github.com/andrefmrocha return (ur.getEMail().size() * ur.getName().size())%50; */ } bool operator()(const UserRecord &ur1, const UserRecord &ur2) const { return ur1.getEMail() == ur2.getEMail(); } }; typedef tr1::unordered_set <UserRecord, userRecordHash, userRecordHash> HashTabUserRecord; class ReadingClub { vector<Book *> books; BST<BookCatalogItem> catalogItems; HashTabUserRecord userRecords; priority_queue <User> readerCandidates; public: ReadingClub(); ReadingClub(vector<Book *> books); void addBook(Book *book); void addBooks(vector<Book *> books); vector<Book *> getBooks() const; // Part I - BST BookCatalogItem getCatalogItem(string title, string author); void addCatalogItem(Book *book); BST<BookCatalogItem> getCatalogItems() const; // Part II - Hash Table vector <UserRecord> getUserRecords() const; void setUserRecords(vector <UserRecord> &urs); // Part III - Piority Queue priority_queue <User> getBestReaderCandidates() const; void setBestReaderCandidates(priority_queue <User> &candidates); // TODO: Implement methods below... // Part I - BST /* A */ void generateCatalog(); /* B */ vector<Book *> getAvailableItems(Book *book) const; /* C */ bool borrowBookFromCatalog(Book *book, User *reader); // Part II - Hash Table /* D */ void addUserRecord(User *user); /* E */ void changeUserEMail(User *user, string newEMail); // Part III - Piority Queue /* F */ void addBestReaderCandidates(const vector <User> &candidates, int min); /* G */ int awardReaderChampion(User &champion); }; #endif /* SRC_READINGCLUB_H_ */ <file_sep>var searchData= [ ['employee_15',['Employee',['../class_employee.html',1,'']]], ['employeedoesnotexist_16',['EmployeeDoesNotExist',['../class_employee_does_not_exist.html',1,'']]], ['employeehasnotuncompletedtasks_17',['EmployeeHasNotUncompletedTasks',['../class_employee_has_not_uncompleted_tasks.html',1,'']]], ['employeeisbusy_18',['EmployeeIsBusy',['../class_employee_is_busy.html',1,'']]], ['employeenotassociatedtoclient_19',['EmployeeNotAssociatedToClient',['../class_employee_not_associated_to_client.html',1,'']]], ['employees_20',['employees',['../class_pitch.html#a61a22220780b39ac8ebbb8c709a498d2',1,'Pitch']]], ['employeesfile_21',['employeesFile',['../class_pitch.html#ab9c6d184cfe0d871af5052dfb5035a35',1,'Pitch']]], ['entrepreneur_22',['Entrepreneur',['../class_entrepreneur.html',1,'']]] ]; <file_sep>var searchData= [ ['completeservicerequested_148',['completeServiceRequested',['../class_pitch.html#a6b9b714ef51fd9e62faec93ddc061ee9',1,'Pitch']]], ['completetask_149',['completeTask',['../class_service_provider.html#a156e8d34f4e6272f1bb0d4c526b64df2',1,'ServiceProvider']]] ]; <file_sep>#include <iostream> #include <vector> using namespace std; template <class N, class E> class Edge; template <class N, class E> class Node { public: N info; vector< Edge<N,E> > edges; Node(N inf) { info = inf; } }; template <class N, class E> class Edge { public: E value; Node<N,E> *destination; Edge(Node<N,E> *dest, E val) { value = val; destination = dest; } }; template <class N, class E> class Graph { vector< Node<N,E> *> nodes; public: Graph() = default; ~Graph(); Graph & addNode(const N &inf); Graph & addEdge(const N &begin, const N &end, const E &val); Graph & removeEdge(const N &begin, const N &end); E & edgeValue(const N &begin, const N &end); unsigned numEdges(void) const; unsigned numNodes(void) const; void print(std::ostream &os) const; }; template <class N, class E> std::ostream & operator<<(std::ostream &out, const Graph<N,E> &g); // exception NodeAlreadyExists template <class N> class NodeAlreadyExists { public: N info; NodeAlreadyExists(N inf) { info=inf; } }; template <class N> std::ostream & operator<<(std::ostream &out, const NodeAlreadyExists<N> &no) { out << "Node already exists: " << no.info; return out; } // exception NodeDoesNotExist template <class N> class NodeDoesNotExist { public: N info; NodeDoesNotExist(N inf) { info = inf; } }; template <class N> std::ostream & operator<<(std::ostream &out, const NodeDoesNotExist<N> &no) { out << "Node does not exist: " << no.info; return out; } // exception EdgeAlreadyExists template <class N> class EdgeAlreadyExists { public: N begin; N end; EdgeAlreadyExists(N b, N e) { begin = b; end = e; } }; template <class N> std::ostream & operator<<(std::ostream &out, const EdgeAlreadyExists<N> &ed) { out << "Edge already exists: " << ed.begin << " , " << ed.end; return out; } // exception EdgeDoesNotExist template <class N> class EdgeDoesNotExist { public: N begin; N end; EdgeDoesNotExist(N b, N e) { begin = b; end = e; } }; template <class N> std::ostream & operator<<(std::ostream &out, const EdgeDoesNotExist<N> &ed) { out << "Edge does not exist: " << ed.begin << " , " << ed.end; return out; } template <class N, class E> Graph<N, E>::~Graph() { for (unsigned i = 0; i < numNodes(); i++) { delete nodes[i]; } } template <class N, class E> Graph<N,E> & Graph<N, E>::addNode(const N &inf) { for (unsigned i = 0; i < numNodes(); i++) { if (nodes[i]->info == inf) { throw NodeAlreadyExists<N>(inf); } } Node<N, E> *newNode = new Node<N, E>(inf); nodes.push_back(newNode); return *this; } template <class N, class E> Graph<N,E> & Graph<N, E>::addEdge(const N &begin, const N &end, const E &val) { for (unsigned d = 0; d < numNodes(); d++) { if (nodes[d]->info == end) { // i found the destination node, i.e. nodes[d] for (unsigned s = 0; s < numNodes(); s++) { if (nodes[s]->info == begin) { // i found the source node, i.e. nodes[s] for (size_t e = 0; e < nodes[s]->edges.size(); e++) { if (nodes[s]->edges[e].destination->info == end) { throw EdgeAlreadyExists<N>(begin, end); // if the edge connected to the source node has the same destination node // it means that the edge i am trying to add already exists } } Edge<N, E> newEdge(nodes[d], val); // the new edge has, as destination node, the one i found previously nodes[s]->edges.push_back(newEdge); return *this; } } } } throw NodeDoesNotExist<N>(begin); // since i haven't found neither the source nor the destination nodes } template <class N, class E> Graph<N,E> & Graph<N, E>::removeEdge(const N &begin, const N &end) { for (unsigned n = 0; n < numNodes(); n++) { if (nodes[n]->info == begin) { for (unsigned e = 0; e < nodes[n]->edges.size(); e++) { if (nodes[n]->edges[e].destination->info == end) { nodes[n]->edges.erase(nodes[n]->edges.begin() + e); return *this; } } throw EdgeDoesNotExist<N>(begin, end); } } throw NodeDoesNotExist<N>(begin); } template <class N, class E> E & Graph<N, E>::edgeValue(const N &begin, const N &end) { for (unsigned n = 0; n < numNodes(); n++) { if (nodes[n]->info == begin) { for (unsigned e = 0; e < nodes[n]->edges.size(); e++) { if (nodes[n]->edges[e].destination->info == end) { return nodes[n]->edges[e].value; } } throw EdgeDoesNotExist<N>(begin, end); } } throw NodeDoesNotExist<N>(begin); } template <class N, class E> unsigned Graph<N, E>::numNodes(void) const { return nodes.size(); } template <class N, class E> unsigned Graph<N, E>::numEdges(void) const { unsigned numEdges = 0; for (unsigned i = 0; i < numNodes(); i++) { numEdges += nodes[i]->edges.size(); } return numEdges; } template <class N, class E> void Graph<N, E>::print(std::ostream &os) const { for (unsigned n = 0; n < numNodes(); n++) { os << "( " << nodes[n]->info; for (unsigned e = 0; e < nodes[n]->edges.size(); e++) { os << "[ " << nodes[n]->edges[e].destination->info << " " << nodes[n]->edges[e].value << "] "; } os << ") "; } } template <class N, class E> std::ostream & operator<<(std::ostream &out, const Graph<N,E> &g) { g.print(out); return out; } <file_sep>#ifndef _DIC #define _DIC #include <string> #include <fstream> #include "bst.h" class WordMeaning { string word; string meaning; public: WordMeaning(string w, string m) : word(w), meaning(m) {} string getWord() const { return word; } string getMeaning() const { return meaning; } void setWord(string w) { word = w; } void setMeaning(string m) { meaning = m; } bool operator<(const WordMeaning &wm1) const; }; class Dictionary { BST<WordMeaning> words; public: Dictionary() : words(WordMeaning("", "")) {}; BST<WordMeaning> getWords() const; void readDictionary(ifstream &f); string searchFor(string word) const; bool correct(string word, string newMeaning); void print() const; }; //TODO class WordInexistent { private: string wordBefore, meanBefore, wordAfter, meanAfter; public: WordInexistent(string wordBefore, string meanBefore, string wordAfter, string meanAfter) { this->wordBefore = wordBefore; this->meanBefore = meanBefore; this->wordAfter = wordAfter; this->meanAfter = meanAfter; } string getWordBefore() const { return wordBefore; } string getMeaningBefore() const { return meanBefore; } string getWordAfter() const { return wordAfter; } string getMeaningAfter() const { return meanAfter; } }; #endif<file_sep>/* * Bank.cpp */ #include "Bank.h" #include <algorithm> #include <string> Bank::Bank() {} void Bank::addAccount(Account *a) { accounts.push_back(a); } void Bank::addBankOfficer(BankOfficer b){ bankOfficers.push_back(b); } const BankOfficer & Bank::addAccountToBankOfficer(Account *ac, string name) { for (vector<BankOfficer>::iterator it = bankOfficers.begin(); it != bankOfficers.end(); it++) { if ((*it).getName() == name) { (*it).addAccount(ac); return (*it); } } throw NoBankOfficerException(name); } vector<BankOfficer> Bank::getBankOfficers() const { return bankOfficers; } vector<Account *> Bank::getAccounts() const { return accounts; } double Bank::getWithdraw(string cod1) const{ double total = 0; for (vector<Account*>::const_iterator it = accounts.begin(); it != accounts.end(); it++) { if ((*it)->getCodH() == cod1) { total += (*it)->getWithdraw(); } } return total; } vector<Account *> Bank::removeBankOfficer(string name){ vector<Account *> res; for (vector<BankOfficer>::const_iterator it = bankOfficers.begin(); it != bankOfficers.end(); it++) { if ((*it).getName() == name) { res = (*it).getAccounts(); bankOfficers.erase(it); break; } } return res; } bool compAcc(Account* c1, Account* c2) { if (c1->getWithdraw() < c2->getWithdraw()) return true; else if (c1->getWithdraw() == c2->getWithdraw() && c1->getCodIBAN() < c2->getCodIBAN()) return true; else return false; } void Bank::sortAccounts() { sort(accounts.begin(), accounts.end(), compAcc); } NoBankOfficerException::NoBankOfficerException(string name) { this->name = name; } string NoBankOfficerException::getName() { return name; } <file_sep>var searchData= [ ['flying_9',['Flying',['../class_flying.html',1,'']]] ]; <file_sep>var searchData= [ ['particularclient_135',['ParticularClient',['../class_particular_client.html',1,'']]], ['pitch_136',['Pitch',['../class_pitch.html',1,'']]] ];
d9eaf76f06c3fb28bab0673a6c6e30c981666864
[ "JavaScript", "Makefile", "C++" ]
56
JavaScript
margaridav27/feup-aeda
b410abed808d861c97c930bb88d8d4cfa61c3869
ccb9662be8f86f324ab37d42f8ef4710443fc7f7
refs/heads/master
<file_sep>import addAppToHosts from 'Helpers/addAppToHosts'; import removeAppFromHosts from 'Helpers/removeAppFromHosts'; import getAllHosts from 'Helpers/getAllHosts'; import getAppsByHost from 'Helpers/getAppsByHost'; import { IApp } from 'Types'; import request from 'request'; let appWithHosts: IApp; let appWithoutHosts: IApp; let apps: IApp[]; beforeEach(() => { appWithHosts = { name:"Small Fresh Pants - Kautzer - Boyer, and Sons", contributors:["<NAME>","<NAME>","<NAME>","<NAME>","<NAME> Sr."], version:7, apdex:68, host:[ "7e6272f7-098e.dakota.biz", "9a450527-cdd9.kareem.info", "e7bf58af-f0be.dallas.biz" ] }; appWithoutHosts = { name:"Small Fresh Pants - Kautzer - Boyer, and Sons", contributors:["<NAME>","<NAME>","<NAME>","<NAME>","<NAME> Sr."], version:7, apdex:68, host:[] } apps = [ { name:"Small Fresh Pants - Kautzer - Boyer, and Sons", contributors:["<NAME>","<NAME>","<NAME>","<NAME>","<NAME> Sr."], version:7, apdex:68, host:[ "7e6272f7-098e.dakota.biz", "9a450527-cdd9.kareem.info", "e7bf58af-f0be.dallas.biz" ] }, { name:"Apple, Inc", contributors:["<NAME>"], version:7, apdex:99, host:[] }, { name:"Google, Inc", contributors:["<NAME>"], version:10, apdex:99, host:[ "100e.dakota.biz", "87362.kareem.info", "987978.california.biz" ] } ] }); describe("addAppToHost()", () => { it("returns a app with an added host", () => { const modifiedApp: IApp = addAppToHosts(appWithHosts, ['test-f0be.test.biz']); expect(modifiedApp).toEqual({ name:"Small Fresh Pants - Kautzer - Boyer, and Sons", contributors:["<NAME>","<NAME>","<NAME>","<NAME>","<NAME> Sr."], version:7, apdex:68, host:[ "7e6272f7-098e.dakota.biz", "9a450527-cdd9.kareem.info", "e7bf58af-f0be.dallas.biz", "test-f0be.test.biz" ] }); }); it("returns a app with an added host, if no hosts exist", () => { const modifiedApp: IApp = addAppToHosts(appWithoutHosts, ['test-f0be.test.biz']); expect(modifiedApp).toEqual({ name:"Small Fresh Pants - Kautzer - Boyer, and Sons", contributors:["<NAME>","<NAME>","<NAME>","<NAME>","<NAME> Sr."], version:7, apdex:68, host:["test-f0be.test.biz"] }); }); }); describe("removeAppFromHosts()", () => { it("returns an app with the specific host removed", () => { const modifiedApp: IApp = removeAppFromHosts(appWithHosts, ['e7bf58af-f0be.dallas.biz']); expect(modifiedApp).toEqual({ name:"Small Fresh Pants - Kautzer - Boyer, and Sons", contributors:["<NAME>","<NAME>","<NAME>","<NAME>","<NAME> Sr."], version:7, apdex:68, host:[ "7e6272f7-098e.dakota.biz", "9a450527-cdd9.kareem.info", ] }); }); it("returns an app with all hosts removed", () => { const modifiedApp: IApp = removeAppFromHosts(appWithHosts, [ "7e6272f7-098e.dakota.biz", "9a450527-cdd9.kareem.info", "e7bf58af-f0be.dallas.biz" ]); expect(modifiedApp).toEqual({ name:"Small Fresh Pants - Kautzer - Boyer, and Sons", contributors:["<NAME>","<NAME>","<NAME>","<NAME>","<NAME> Sr."], version:7, apdex:68, host:[] }); }); }); describe("getAllHosts()", () => { it("returns all the available hosts in a list containing a single app of type IApp[]", () => { const availableHosts: string[] = getAllHosts([appWithHosts]); expect(availableHosts).toEqual([ "7e6272f7-098e.dakota.biz", "9a450527-cdd9.kareem.info", "e7bf58af-f0be.dallas.biz" ]); }); it("returns all the available hosts in a list of apps of type IApp[]", () => { const availableHosts: string[] = getAllHosts(apps); expect(availableHosts).toEqual([ "7e6272f7-098e.dakota.biz", "9a450527-cdd9.kareem.info", "e7bf58af-f0be.dallas.biz", "100e.dakota.biz", "87362.kareem.info", "987978.california.biz" ]); }); }); describe("getAppsByHost()", () => { xit("should return the top 25 apps ordered by apdex for a specific host", () => { const fetch = jest.fn(() => new Promise(resolve => resolve())); fetch('/data').then(res => res.json()).then((apps: IApp[]) => { const topSatisfiedApps = getAppsByHost('e7bf58af-f0be.dallas.biz', apps); expect(topSatisfiedApps).toHaveLength(25); }); }); }); <file_sep>/** * Returns all the available hosts without duplicates */ import { IApp } from 'Types'; function getAllHosts(apps: IApp[]) { var hosts: any[] = []; // Complexity: O(n^2) apps.forEach((app: IApp) => { const availableHosts = app.host; availableHosts.forEach((host) => { !hosts.includes(host) && hosts.push(host); }); }); return hosts; } export default getAllHosts; <file_sep>const webpack = require('webpack'); const config = require('./webpack.config.js'); webpack(config, (err, stats) => { if (err || stats.hasErrors()) { console.log(err); console.log(stats.hasErrors()); console.log(stats.toString({colors: true})); return; } console.log(stats.toString({colors: true, exclude: ['~'], maxModules: 5})); }); <file_sep>import { IApp } from 'Types'; function removeAppFromHosts(app: IApp, hosts: string[]): IApp { const availableHosts = app.host; let newHosts: string[] = []; hosts.forEach((hostName: string) => { const hosts = newHosts.length > 0 ? newHosts : availableHosts; newHosts = hosts.filter((host: string) => host !== hostName); }); delete app.host; app.host = newHosts; return app; } export default removeAppFromHosts; <file_sep># Test app ## Getting started This app does not come with any included `node_modules` or `compiled js` To get setup all you need to do is run ```bash yarn && yarn start ``` OR ```bash npm i && npm run start ``` Depending on your preference, my preference is `yarn` ## Project organazation This project is 2 main parts - `dist`: This is where all the compiled code lives. This will be generated by `webpack` - `src`: This is where the source code lives. The `src` dir is split into - `build`: This is where all the webpack configuration lives - `client`: This is where all the client side code lives - `data`: This is where the `host-app-data.json` will be served from when a request for this file is made - `server`: This is where all the server code lives - `views`: This is where the html template lives The `client` dir is divided into - `components`: The logic is to put all the reusable pieces of UI code here. - `helpers`: This is where all the helpers for the project live. I believe that these are functions that provide help by modifying the data provided to them in a specific way and returning them back, in a sense providing `help` to the person calling them. For example all the methods `getAppsByHost`, `addAppToHosts`, `removeAppFromHosts` live here. This probably could've done in another way, but i prefer to think of them as helper functions. - `styles`: Simple CSS file with all styles - `types`: Place for all the types for the project # Build This project uses the webpack Node API to create bundles. When developing, the `yarn dev` command will run only one script: - `webpack.js` uses `webpack.config.js` This in return produces a `client.bundle.js` file in the `dist` folder ## Uglify Currently, `uglify-webpack-plugin` uses the `uglify-js` engine which does not support minification of code above ES5. The beta version uses a different minification engine, `uglify-es` which has better support for new language features. During minification, a minifier supporting dead code elimination will reduce all of this `doSomething()` to something similar to ```js d(); // renamed doSomething() ``` # TypeScript TypeScript is a strict syntactical superset of JavaScript, and adds optional static typing to the language. The entire clients side of the project is build on TypeScript ## Matching Webpack's aliases to TypeScript's Webpack and TypeScript's module resolution have been manually matched to ensure that aliases resolve to the same modules with both tools. TypeScript is set to produce `"ESNext"` modules. `"ESNext"` allows for dynamic or lazy importing. This does not mean that it leaves any `import` statements untouched: it will perform module resolution on import statements, and fully resolves the import path in the generated code. Here is an example from the [typesctipt website](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html) ```ts async function getZipFile(name: string, files: File[]): Promise<File> { const zipUtil = await import("./utils/create-zip-file"); const zipContents = await zipUtil.getContentAsBlob(files); return new File(zipContents, name); } ``` For the resolution to succeed, a valid file must eventually be found. webpack then reads the resolved paths, and should resolve to the same module. # Code I want to touch on 2 methods specifically `addAppToHosts` and `removeAppFromHosts`. > **These methods should > update the list of applications with higher Apdex whenever any of these methods is called** First, lets try to clarify somethings. **What does this mean to add an app to a host?** If you refer the construction of the `application` object, it looks like this ```ts export interface IApp { apdex: number; host: string[]; name: string; contributors: string[]; version: number; } ``` Each of the applications has in it an array of hosts that it is available on. Now that we know this fact, what do we need to do in order to add an `application to hosts`? It is as simple as adding all the hosts that the application needs to be deployed on into this array `host`. If you now refer my implementation of `addAppToHosts` you will see that all the hosts are added to this `hosts` array and a modified application object is returned. This object now can be used for any purpose. **What does this mean to remove an app from a host?** Again this is just as simple as removing the array of hosts you provided from the `host` array of the application object. Now lets take a look at the implementations of the methods. `addAppToHosts`: Simply takes in an `app` of type `IApp` that you are interested in adding to given hosts and an array of hosts that this apps needs to be added to. For each of the given hosts the app will be added and a modified application object is returned. ```ts import { IApp } from "Types"; function addAppToHosts(app: IApp, hosts: string[]): IApp { const availableHosts = app.host; hosts.forEach((host: string) => availableHosts.push(host)); return app; } export default addAppToHosts; ``` `removeAppFromHosts`: Takes in an `app` that you are interested in removing from given hosts and a list of hosts that you want this app to be removed from. For each of the given hosts, I am checking if this hosts exists in the `host` array in the application object. If it exists then im making a new array called `newHosts` where all the specified hosts are removed and im reassigning this new array to the original `app.host` array by overwriting it and returning the modified application object. ```ts import { IApp } from "Types"; function removeAppFromHosts(app: IApp, hosts: string[]): IApp { const availableHosts = app.host; let newHosts: string[] = []; hosts.forEach((hostName: string) => { const hosts = newHosts.length > 0 ? newHosts : availableHosts; newHosts = hosts.filter((host: string) => host !== hostName); }); delete app.host; app.host = newHosts; return app; } export default removeAppFromHosts; ``` # Big O I think that the total Complexity of the algorithm is `O(n^2) + O(n^2) + O(n log(n)) + O(n)`. For large values of `n` its safe to assume that `n >> log(n) && n^2 >> n`. By this assumption we can reduce the Complexity to `O(2n^2) + O(2n)` OR `O(n^2) + O(n)` by safely removing the smaller terms and constants. This leaves us with `O(n^2)` as the Complexity of the algorithm. # Testing All the `unit testing` in the project is done using `jest` For example have a look at `client/helpers/__test__`. To run the test simply run this command in the terminal: ```bash yarn test ``` OR ```bash npm run test ``` <file_sep>/** * Returns the top 25 apps for given hostName */ import { IApp } from 'Types'; function getAppsByHost(hostName: string, apps: IApp[]) { var topApps: any[] = []; // Apps sorted by apdex largest to smallest // Array.prototype.sort() is a MergeSort. Complexity: O(n log(n)). var sortedApps: IApp[] = apps.sort((a, b) => b.apdex - a.apdex); // Complexity: O(n^2) sortedApps.forEach((app: IApp, index, arr) => { const appHosts: string[] = app.host; appHosts.forEach((host: string) => { if (topApps.length < 25 && (hostName === host)) { topApps.push(app); } }); }); return topApps; } export default getAppsByHost; <file_sep>import { IApp } from 'Types'; class Card { private hostName: string; private apps: any[]; constructor(host: string, apps: any[]) { this.hostName = host; this.apps = apps; } public create() { this.createNodes(); // Complexity: O(n) for (let i = 0; i < this.apps.length; i++) { const app: IApp = this.apps[i]; if (i > 5) break; this.fillNodes(app); } } private createNodes() { const root = document.getElementById('root'); const card = document.createElement('div'); const cardHeader = document.createElement('div'); const cardBody = document.createElement('div'); const input = document.getElementById('input-checkbox'); const eventHandler = () => { if ( card.className.indexOf('inline') !== -1 ) { card.className = card.className.replace('inline', ''); } else { card.className += ' inline'; } }; card.className = 'card inline'; card.id = 'card'; cardHeader.className = 'card-header'; cardBody.className = 'card-body'; cardBody.id = `card-${this.hostName}`; cardHeader.innerHTML = this.hostName; // Remove any existing event listners input.removeEventListener('click', eventHandler); input.addEventListener('click', eventHandler); card.appendChild(cardBody); card.insertBefore(cardHeader, cardBody); root.appendChild(card); } private fillNodes(app: IApp) { const cardBody = document.getElementById(`card-${this.hostName}`); const div = document.createElement('div'); const p1 = document.createElement('p'); const p2 = document.createElement('p'); p1.className = 'apdex'; p2.className = 'app-name'; div.appendChild(p1).innerHTML = app.apdex.toString(); div.appendChild(p2).innerHTML = app.name; div.addEventListener('click', () => { alert(`Release Version: ${app.version}`); }); cardBody.appendChild(div); } } export default Card; <file_sep>import { IApp } from 'Types'; function addAppToHosts(app: IApp, hosts: string[]): IApp { const availableHosts = app.host; hosts.forEach((host: string) => availableHosts.push(host)); return app; } export default addAppToHosts; <file_sep>const express = require('express'); const http = require('http'); const bodyParser = require('body-parser'); const path = require('path'); const router = require('./router'); const port = 4000; const app = express(); app.use('/', router); const httpServer = http.createServer(app); httpServer.listen(port, () => { console.log(`Please navigate to http://localhost:${port} on your browser`); }); <file_sep>import getAllHosts from 'Helpers/getAllHosts'; import getAppsByHost from 'Helpers/getAppsByHost'; import Card from './components/Card'; import { IApp } from 'Types'; // fetch('/data').then(res => res.json()).then((apps: IApp[]) => { // // Complexity: O(n^2) // const availableHosts = getAllHosts(apps); // // // Complexity: O(n) // availableHosts.forEach((host: string) => { // // Make a new card for every host // // Complexity: O(n^2) + O(n log(n)). // const topSatisfiedApps = getAppsByHost(host, apps); // const card = new Card(host, topSatisfiedApps); // // Complexity: O(n), because it uses `topSatisfiedApps` // card.create(); // }); // }); // ASYNC: Returns a promise that needs to be resolved // In this case since the function doesnt return anything its ok // Can also be done with generators // async function fetchData() { // const response = await fetch('/data'); // const apps: IApp[] = await response.json(); // const availableHosts = getAllHosts(apps); // // availableHosts.forEach((host: string) => { // const topSatisfiedApps = getAppsByHost(host, apps); // const card = new Card(host, topSatisfiedApps); // card.create(); // }); // }; // // fetchData(); // GENERATORS: The same can be accomplished with generators as well run(function* fetchData() { const response = yield fetch('/data'); const apps: IApp[] = yield response.json(); const availableHosts = getAllHosts(apps); availableHosts.forEach((host: string) => { const topSatisfiedApps = getAppsByHost(host, apps); const card = new Card(host, topSatisfiedApps); card.create(); }); }); function run(generator) { const iterator = generator(); function iterate(iteration) { if (iteration.done) return iteration.value; const promise = iteration.value; return promise.then(res => iterate(iterator.next(res))); } // Can return this value if you want to call `.then()` on the `run()` iterate(iterator.next()); }
173034a2f6b546f152176cc8b381f9f47e930e47
[ "JavaScript", "TypeScript", "Markdown" ]
10
TypeScript
vinaykukke/with-data-processing
ca9acc25d849d52bcaacfbcc820acdfe21a44e34
f398d28b3e03bfdcbf69a06463dac4825427177f
refs/heads/master
<file_sep>import json import datetime import shlex import os import urllib import urllib2 import urlparse import random import string import logging import pprint import distutils.version import sqlalchemy from sqlalchemy.exc import (ProgrammingError, IntegrityError, DBAPIError, DataError) import psycopg2.extras import ckan.lib.cli as cli import ckan.plugins.toolkit as toolkit log = logging.getLogger(__name__) if not os.environ.get('DATASTORE_LOAD'): import paste.deploy.converters as converters ValidationError = toolkit.ValidationError else: log.warn("Running datastore without CKAN") class ValidationError(Exception): def __init__(self, error_dict): pprint.pprint(error_dict) _pg_types = {} _type_names = set() _engines = {} _TIMEOUT = 60000 # milliseconds # See http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html _PG_ERR_CODE = { 'unique_violation': '23505', 'query_canceled': '57014', 'undefined_object': '42704', 'syntax_error': '42601', 'permission_denied': '42501', 'duplicate_table': '42P07', 'duplicate_alias': '42712', } _DATE_FORMATS = ['%Y-%m-%d', '%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%SZ', '%d/%m/%Y', '%m/%d/%Y', '%d-%m-%Y', '%m-%d-%Y'] _INSERT = 'insert' _UPSERT = 'upsert' _UPDATE = 'update' def _strip(input): if isinstance(input, basestring) and len(input) and input[0] == input[-1]: return input.strip().strip('"') return input def _pluck(field, arr): return [x[field] for x in arr] def _get_list(input, strip=True): '''Transforms a string or list to a list''' if input is None: return if input == '': return [] l = converters.aslist(input, ',', True) if strip: return [_strip(x) for x in l] else: return l def _is_valid_field_name(name): ''' Check that field name is valid: * can't start with underscore * can't contain double quote (") * can't be empty ''' return name.strip() and not name.startswith('_') and not '"' in name def _is_valid_table_name(name): if '%' in name: return False return _is_valid_field_name(name) def _validate_int(i, field_name, non_negative=False): try: i = int(i) except ValueError: raise ValidationError({ field_name: ['{0} is not an integer'.format(i)] }) if non_negative and i < 0: raise ValidationError({ field_name: ['{0} is not a non-negative integer'.format(i)] }) def _get_engine(data_dict): '''Get either read or write engine.''' connection_url = data_dict['connection_url'] engine = _engines.get(connection_url) if not engine: engine = sqlalchemy.create_engine(connection_url) _engines[connection_url] = engine return engine def _cache_types(context): if not _pg_types: connection = context['connection'] results = connection.execute( 'SELECT oid, typname FROM pg_type;' ) for result in results: _pg_types[result[0]] = result[1] _type_names.add(result[1]) if 'nested' not in _type_names: native_json = _pg_version_is_at_least(connection, '9.2') log.info("Create nested type. Native JSON: {0}".format( native_json)) import pylons data_dict = { 'connection_url': pylons.config['ckan.datastore.write_url']} engine = _get_engine(data_dict) with engine.begin() as connection: connection.execute( 'CREATE TYPE "nested" AS (json {0}, extra text)'.format( 'json' if native_json else 'text')) _pg_types.clear() ## redo cache types with json now available. return _cache_types(context) psycopg2.extras.register_composite('nested', connection.connection, True) def _pg_version_is_at_least(connection, version): try: v = distutils.version.LooseVersion(version) pg_version = connection.execute('select version();').fetchone() pg_version_number = pg_version[0].split()[1] pv = distutils.version.LooseVersion(pg_version_number) return v <= pv except ValueError: return False def _is_valid_pg_type(context, type_name): if type_name in _type_names: return True else: connection = context['connection'] try: connection.execute('SELECT %s::regtype', type_name) except ProgrammingError, e: if e.orig.pgcode in [_PG_ERR_CODE['undefined_object'], _PG_ERR_CODE['syntax_error']]: return False raise else: return True def _get_type(context, oid): _cache_types(context) return _pg_types[oid] def _rename_json_field(data_dict): '''Rename json type to a corresponding type for the datastore since pre 9.2 postgres versions do not support native json''' return _rename_field(data_dict, 'json', 'nested') def _unrename_json_field(data_dict): return _rename_field(data_dict, 'nested', 'json') def _rename_field(data_dict, term, replace): fields = data_dict.get('fields', []) for i, field in enumerate(fields): if 'type' in field and field['type'] == term: data_dict['fields'][i]['type'] = replace return data_dict def _guess_type(field): '''Simple guess type of field, only allowed are integer, numeric and text''' data_types = set([int, float]) if isinstance(field, (dict, list)): return 'nested' if isinstance(field, int): return 'int' if isinstance(field, float): return 'float' for data_type in list(data_types): try: data_type(field) except (TypeError, ValueError): data_types.discard(data_type) if not data_types: break if int in data_types: return 'integer' elif float in data_types: return 'numeric' ##try iso dates for format in _DATE_FORMATS: try: datetime.datetime.strptime(field, format) return 'timestamp' except (ValueError, TypeError): continue return 'text' def _get_fields(context, data_dict): fields = [] all_fields = context['connection'].execute( u'SELECT * FROM "{0}" LIMIT 1'.format(data_dict['resource_id']) ) for field in all_fields.cursor.description: if not field[0].startswith('_'): fields.append({ 'id': field[0].decode('utf-8'), 'type': _get_type(context, field[1]) }) return fields def json_get_values(obj, current_list=None): if current_list is None: current_list = [] if isinstance(obj, basestring): current_list.append(obj) if isinstance(obj, list): for item in obj: json_get_values(item, current_list) if isinstance(obj, dict): for item in obj.values(): json_get_values(item, current_list) return current_list def check_fields(context, fields): '''Check if field types are valid.''' for field in fields: if field.get('type') and not _is_valid_pg_type(context, field['type']): raise ValidationError({ 'fields': ['"{0}" is not a valid field type'.format( field['type'])] }) elif not _is_valid_field_name(field['id']): raise ValidationError({ 'fields': ['"{0}" is not a valid field name'.format( field['id'])] }) def convert(data, type_name): if data is None: return None if type_name == 'nested': return json.loads(data[0]) # array type if type_name.startswith('_'): sub_type = type_name[1:] return [convert(item, sub_type) for item in data] if type_name == 'tsvector': return unicode(data, 'utf-8') if isinstance(data, datetime.datetime): return data.isoformat() if isinstance(data, (int, float)): return data return unicode(data) def create_table(context, data_dict): '''Create table from combination of fields and first row of data.''' datastore_fields = [ {'id': '_id', 'type': 'serial primary key'}, {'id': '_full_text', 'type': 'tsvector'}, ] # check first row of data for additional fields extra_fields = [] supplied_fields = data_dict.get('fields', []) check_fields(context, supplied_fields) field_ids = _pluck('id', supplied_fields) records = data_dict.get('records') # if type is field is not given try and guess or throw an error for field in supplied_fields: if 'type' not in field: if not records or field['id'] not in records[0]: raise ValidationError({ 'fields': ['"{0}" type not guessable'.format(field['id'])] }) field['type'] = _guess_type(records[0][field['id']]) if records: # check record for sanity if not isinstance(records[0], dict): raise ValidationError({ 'records': ['The first row is not a json object'] }) supplied_field_ids = records[0].keys() for field_id in supplied_field_ids: if not field_id in field_ids: extra_fields.append({ 'id': field_id, 'type': _guess_type(records[0][field_id]) }) fields = datastore_fields + supplied_fields + extra_fields sql_fields = u", ".join([u'"{0}" {1}'.format( f['id'], f['type']) for f in fields]) sql_string = u'CREATE TABLE "{0}" ({1});'.format( data_dict['resource_id'], sql_fields ) context['connection'].execute(sql_string.replace('%', '%%')) def _get_aliases(context, data_dict): '''Get a list of aliases for a resource.''' res_id = data_dict['resource_id'] alias_sql = sqlalchemy.text( u'SELECT name FROM "_table_metadata" WHERE alias_of = :id') results = context['connection'].execute(alias_sql, id=res_id).fetchall() return [x[0] for x in results] def _get_resources(context, alias): '''Get a list of resources for an alias. There could be more than one alias in a resource_dict.''' alias_sql = sqlalchemy.text( u'''SELECT alias_of FROM "_table_metadata" WHERE name = :alias AND alias_of IS NOT NULL''') results = context['connection'].execute(alias_sql, alias=alias).fetchall() return [x[0] for x in results] def create_alias(context, data_dict): aliases = _get_list(data_dict.get('aliases')) if aliases is not None: # delete previous aliases previous_aliases = _get_aliases(context, data_dict) for alias in previous_aliases: sql_alias_drop_string = u'DROP VIEW "{0}"'.format(alias) context['connection'].execute(sql_alias_drop_string) try: for alias in aliases: sql_alias_string = u'''CREATE VIEW "{alias}" AS SELECT * FROM "{main}"'''.format( alias=alias, main=data_dict['resource_id'] ) res_ids = _get_resources(context, alias) if res_ids: raise ValidationError({ 'alias': [(u'The alias "{0}" already exists.').format( alias)] }) context['connection'].execute(sql_alias_string) except DBAPIError, e: if e.orig.pgcode in [_PG_ERR_CODE['duplicate_table'], _PG_ERR_CODE['duplicate_alias']]: raise ValidationError({ 'alias': ['"{0}" already exists'.format(alias)] }) def create_indexes(context, data_dict): indexes = _get_list(data_dict.get('indexes')) # primary key is not a real primary key # it's just a unique key primary_key = _get_list(data_dict.get('primary_key')) # index and primary key could be [], # which means that indexes should be deleted if indexes is None and primary_key is None: return sql_index_tmpl = u'CREATE {unique} INDEX {name} ON "{res_id}"' sql_index_string_method = sql_index_tmpl + u' USING {method}({fields})' sql_index_string = sql_index_tmpl + u' ({fields})' sql_index_strings = [] fields = _get_fields(context, data_dict) field_ids = _pluck('id', fields) json_fields = [x['id'] for x in fields if x['type'] == 'nested'] def generate_index_name(): # pg 9.0+ do not require an index name if _pg_version_is_at_least(context['connection'], '9.0'): return '' else: src = string.ascii_letters + string.digits random_string = ''.join([random.choice(src) for n in xrange(10)]) return 'idx_' + random_string if indexes is not None: _drop_indexes(context, data_dict, False) # create index for faster full text search (indexes: gin or gist) sql_index_strings.append(sql_index_string_method.format( res_id=data_dict['resource_id'], unique='', name=generate_index_name(), method='gist', fields='_full_text')) else: indexes = [] if primary_key is not None: _drop_indexes(context, data_dict, True) indexes.append(primary_key) for index in indexes: if not index: continue index_fields = _get_list(index) for field in index_fields: if field not in field_ids: raise ValidationError({ 'index': [ ('The field "{0}" is not a valid column name.').format( index)] }) fields_string = u', '.join( ['(("{0}").json::text)'.format(field) if field in json_fields else '"%s"' % field for field in index_fields]) sql_index_strings.append(sql_index_string.format( res_id=data_dict['resource_id'], unique='unique' if index == primary_key else '', name=generate_index_name(), fields=fields_string)) sql_index_strings = map(lambda x: x.replace('%', '%%'), sql_index_strings) map(context['connection'].execute, sql_index_strings) def _drop_indexes(context, data_dict, unique=False): sql_drop_index = u'DROP INDEX "{0}" CASCADE' sql_get_index_string = u""" SELECT i.relname AS index_name FROM pg_class t, pg_class i, pg_index idx WHERE t.oid = idx.indrelid AND i.oid = idx.indexrelid AND t.relkind = 'r' AND idx.indisunique = {unique} AND idx.indisprimary = false AND t.relname = %s """.format(unique='true' if unique else 'false') indexes_to_drop = context['connection'].execute( sql_get_index_string, data_dict['resource_id']).fetchall() for index in indexes_to_drop: context['connection'].execute( sql_drop_index.format(index[0]).replace('%', '%%')) def alter_table(context, data_dict): '''alter table from combination of fields and first row of data return: all fields of the resource table''' supplied_fields = data_dict.get('fields', []) current_fields = _get_fields(context, data_dict) if not supplied_fields: supplied_fields = current_fields check_fields(context, supplied_fields) field_ids = _pluck('id', supplied_fields) records = data_dict.get('records') new_fields = [] for num, field in enumerate(supplied_fields): # check to see if field definition is the same or and # extension of current fields if num < len(current_fields): if field['id'] != current_fields[num]['id']: raise ValidationError({ 'fields': [('Supplied field "{0}" not ' 'present or in wrong order').format( field['id'])] }) ## no need to check type as field already defined. continue if 'type' not in field: if not records or field['id'] not in records[0]: raise ValidationError({ 'fields': ['"{0}" type not guessable'.format(field['id'])] }) field['type'] = _guess_type(records[0][field['id']]) new_fields.append(field) if records: # check record for sanity as they have not been # checked during validation if not isinstance(records, list): raise ValidationError({ 'records': ['Records has to be a list of dicts'] }) if not isinstance(records[0], dict): raise ValidationError({ 'records': ['The first row is not a json object'] }) supplied_field_ids = records[0].keys() for field_id in supplied_field_ids: if not field_id in field_ids: new_fields.append({ 'id': field_id, 'type': _guess_type(records[0][field_id]) }) for field in new_fields: sql = 'ALTER TABLE "{0}" ADD "{1}" {2}'.format( data_dict['resource_id'], field['id'], field['type']) context['connection'].execute(sql.replace('%', '%%')) def insert_data(context, data_dict): data_dict['method'] = _INSERT return upsert_data(context, data_dict) def upsert_data(context, data_dict): '''insert all data from records''' if not data_dict.get('records'): return method = data_dict.get('method', _UPSERT) fields = _get_fields(context, data_dict) field_names = _pluck('id', fields) records = data_dict['records'] sql_columns = ", ".join(['"%s"' % name.replace( '%', '%%') for name in field_names] + ['"_full_text"']) if method == _INSERT: rows = [] for num, record in enumerate(records): _validate_record(record, num, field_names) row = [] for field in fields: value = record.get(field['id']) if value and field['type'].lower() == 'nested': ## a tuple with an empty second value value = (json.dumps(value), '') row.append(value) row.append(_to_full_text(fields, record)) rows.append(row) sql_string = u'''INSERT INTO "{res_id}" ({columns}) VALUES ({values}, to_tsvector(%s));'''.format( res_id=data_dict['resource_id'], columns=sql_columns, values=', '.join(['%s' for field in field_names]) ) context['connection'].execute(sql_string, rows) elif method in [_UPDATE, _UPSERT]: unique_keys = _get_unique_key(context, data_dict) if len(unique_keys) < 1: raise ValidationError({ 'table': [u'table does not have a unique key defined'] }) for num, record in enumerate(records): # all key columns have to be defined missing_fields = [field for field in unique_keys if field not in record] if missing_fields: raise ValidationError({ 'key': [u'''fields "{fields}" are missing but needed as key'''.format( fields=', '.join(missing_fields))] }) for field in fields: value = record.get(field['id']) if value and field['type'].lower() == 'nested': ## a tuple with an empty second value record[field['id']] = (json.dumps(value), '') non_existing_filed_names = [field for field in record if field not in field_names] if non_existing_filed_names: raise ValidationError({ 'fields': [u'fields "{0}" do not exist'.format( ', '.join(missing_fields))] }) unique_values = [record[key] for key in unique_keys] used_fields = [field for field in fields if field['id'] in record] used_field_names = _pluck('id', used_fields) used_values = [record[field] for field in used_field_names] full_text = _to_full_text(fields, record) if method == _UPDATE: sql_string = u''' UPDATE "{res_id}" SET ({columns}, "_full_text") = ({values}, to_tsvector(%s)) WHERE ({primary_key}) = ({primary_value}); '''.format( res_id=data_dict['resource_id'], columns=u', '.join( [u'"{0}"'.format(field) for field in used_field_names]), values=u', '.join( ['%s' for _ in used_field_names]), primary_key=u','.join( [u'"{0}"'.format(part) for part in unique_keys]), primary_value=u','.join(["%s"] * len(unique_keys)) ) results = context['connection'].execute( sql_string, used_values + [full_text] + unique_values) # validate that exactly one row has been updated if results.rowcount != 1: raise ValidationError({ 'key': [u'key "{0}" not found'.format(unique_values)] }) elif method == _UPSERT: sql_string = u''' UPDATE "{res_id}" SET ({columns}, "_full_text") = ({values}, to_tsvector(%s)) WHERE ({primary_key}) = ({primary_value}); INSERT INTO "{res_id}" ({columns}, "_full_text") SELECT {values}, to_tsvector(%s) WHERE NOT EXISTS (SELECT 1 FROM "{res_id}" WHERE ({primary_key}) = ({primary_value})); '''.format( res_id=data_dict['resource_id'], columns=u', '.join([u'"{0}"'.format(field) for field in used_field_names]), values=u', '.join(['%s::nested' if field['type'] == 'nested' else '%s' for field in used_fields]), primary_key=u','.join([u'"{0}"'.format(part) for part in unique_keys]), primary_value=u','.join(["%s"] * len(unique_keys)) ) context['connection'].execute( sql_string, (used_values + [full_text] + unique_values) * 2) def _get_unique_key(context, data_dict): sql_get_unique_key = ''' SELECT a.attname AS column_names FROM pg_class t, pg_index idx, pg_attribute a WHERE t.oid = idx.indrelid AND a.attrelid = t.oid AND a.attnum = ANY(idx.indkey) AND t.relkind = 'r' AND idx.indisunique = true AND idx.indisprimary = false AND t.relname = %s ''' key_parts = context['connection'].execute(sql_get_unique_key, data_dict['resource_id']) return [x[0] for x in key_parts] def _validate_record(record, num, field_names): # check record for sanity if not isinstance(record, dict): raise ValidationError({ 'records': [u'row "{0}" is not a json object'.format(num)] }) ## check for extra fields in data extra_keys = set(record.keys()) - set(field_names) if extra_keys: raise ValidationError({ 'records': [u'row "{0}" has extra keys "{1}"'.format( num + 1, ', '.join(list(extra_keys)) )] }) def _to_full_text(fields, record): full_text = [] for field in fields: value = record.get(field['id']) if field['type'].lower() == 'nested' and value: full_text.extend(json_get_values(value)) elif field['type'].lower() == 'text' and value: full_text.append(value) return ' '.join(full_text) def _where(field_ids, data_dict): '''Return a SQL WHERE clause from data_dict filters and q''' filters = data_dict.get('filters', {}) if not isinstance(filters, dict): raise ValidationError({ 'filters': ['Not a json object']} ) where_clauses = [] values = [] for field, value in filters.iteritems(): if field not in field_ids: raise ValidationError({ 'filters': ['field "{0}" not in table'.format(field)]} ) where_clauses.append(u'"{0}" = %s'.format(field)) values.append(value) # add full-text search where clause if data_dict.get('q'): where_clauses.append(u'_full_text @@ query') where_clause = u' AND '.join(where_clauses) if where_clause: where_clause = u'WHERE ' + where_clause return where_clause, values def _textsearch_query(data_dict): q = data_dict.get('q') lang = data_dict.get(u'language', u'english') if q: if data_dict.get('plain', True): statement = u", plainto_tsquery('{lang}', '{query}') query" else: statement = u", to_tsquery('{lang}', '{query}') query" rank_column = u', ts_rank(_full_text, query, 32) AS rank' return statement.format(lang=lang, query=q), rank_column return '', '' def _sort(context, data_dict, field_ids): sort = data_dict.get('sort') if not sort: if data_dict.get('q'): return u'ORDER BY rank' else: return u'' clauses = _get_list(sort, False) clause_parsed = [] for clause in clauses: clause = clause.encode('utf-8') if clause.endswith(' asc'): field, sort = clause[:-4], 'asc' elif clause.endswith(' desc'): field, sort = clause[:-5], 'desc' else: field, sort = clause, 'asc' field, sort = unicode(field, 'utf-8'), unicode(sort, 'utf-8') if field not in field_ids: raise ValidationError({ 'sort': [u'field "{0}" not in table'.format( field)] }) if sort.lower() not in ('asc', 'desc'): raise ValidationError({ 'sort': ['sorting can only be asc or desc'] }) clause_parsed.append(u'"{0}" {1}'.format( field, sort) ) if clause_parsed: return "order by " + ", ".join(clause_parsed) def _insert_links(data_dict, limit, offset): '''Adds link to the next/prev part (same limit, offset=offset+limit) and the resource page.''' data_dict['_links'] = {} # get the url from the request try: urlstring = toolkit.request.environ['CKAN_CURRENT_URL'] except TypeError: return # no links required for local actions # change the offset in the url parsed = list(urlparse.urlparse(urlstring)) query = urllib2.unquote(parsed[4]) arguments = dict(urlparse.parse_qsl(query)) arguments_start = dict(arguments) arguments_prev = dict(arguments) arguments_next = dict(arguments) if 'offset' in arguments_start: arguments_start.pop('offset') arguments_next['offset'] = int(offset) + int(limit) arguments_prev['offset'] = int(offset) - int(limit) parsed_start = parsed[:] parsed_prev = parsed[:] parsed_next = parsed[:] parsed_start[4] = urllib.urlencode(arguments_start) parsed_next[4] = urllib.urlencode(arguments_next) parsed_prev[4] = urllib.urlencode(arguments_prev) # add the links to the data dict data_dict['_links']['start'] = urlparse.urlunparse(parsed_start) data_dict['_links']['next'] = urlparse.urlunparse(parsed_next) if int(offset) - int(limit) > 0: data_dict['_links']['prev'] = urlparse.urlunparse(parsed_prev) def delete_data(context, data_dict): fields = _get_fields(context, data_dict) field_ids = set([field['id'] for field in fields]) where_clause, where_values = _where(field_ids, data_dict) context['connection'].execute( u'DELETE FROM "{0}" {1}'.format( data_dict['resource_id'], where_clause ), where_values ) def search_data(context, data_dict): all_fields = _get_fields(context, data_dict) all_field_ids = _pluck('id', all_fields) all_field_ids.insert(0, '_id') fields = data_dict.get('fields') if fields: field_ids = _get_list(fields) for field in field_ids: if not field in all_field_ids: raise ValidationError({ 'fields': [u'field "{0}" not in table'.format(field)]} ) else: field_ids = all_field_ids select_columns = ', '.join([u'"{0}"'.format(field_id) for field_id in field_ids]) ts_query, rank_column = _textsearch_query(data_dict) where_clause, where_values = _where(all_field_ids, data_dict) limit = data_dict.get('limit', 100) offset = data_dict.get('offset', 0) _validate_int(limit, 'limit', non_negative=True) _validate_int(offset, 'offset', non_negative=True) if 'limit' in data_dict: data_dict['limit'] = int(limit) if 'offset' in data_dict: data_dict['offset'] = int(offset) sort = _sort(context, data_dict, field_ids) sql_string = u'''SELECT {select}, count(*) over() AS "_full_count" {rank} FROM "{resource}" {ts_query} {where} {sort} LIMIT {limit} OFFSET {offset}'''.format( select=select_columns, rank=rank_column, resource=data_dict['resource_id'], ts_query=ts_query, where='{where}', sort=sort, limit=limit, offset=offset) sql_string = sql_string.replace('%', '%%') results = context['connection'].execute( sql_string.format(where=where_clause), [where_values]) _insert_links(data_dict, limit, offset) return format_results(context, results, data_dict) def format_results(context, results, data_dict): result_fields = [] for field in results.cursor.description: result_fields.append({ 'id': field[0].decode('utf-8'), 'type': _get_type(context, field[1]) }) if len(result_fields) and result_fields[-1]['id'] == '_full_count': result_fields.pop() # remove _full_count records = [] for row in results: converted_row = {} if '_full_count' in row: data_dict['total'] = row['_full_count'] for field in result_fields: converted_row[field['id']] = convert(row[field['id']], field['type']) records.append(converted_row) data_dict['records'] = records data_dict['fields'] = result_fields return _unrename_json_field(data_dict) def _is_single_statement(sql): return not ';' in sql.strip(';') def create(context, data_dict): ''' The first row will be used to guess types not in the fields and the guessed types will be added to the headers permanently. Consecutive rows have to conform to the field definitions. rows can be empty so that you can just set the fields. fields are optional but needed if you want to do type hinting or add extra information for certain columns or to explicitly define ordering. eg: [{"id": "dob", "type": "timestamp"}, {"id": "name", "type": "text"}] A header items values can not be changed after it has been defined nor can the ordering of them be changed. They can be extended though. Any error results in total failure! For now pass back the actual error. Should be transactional. ''' engine = _get_engine(data_dict) context['connection'] = engine.connect() timeout = context.get('query_timeout', _TIMEOUT) _cache_types(context) _rename_json_field(data_dict) trans = context['connection'].begin() try: # check if table already existes context['connection'].execute( u'SET LOCAL statement_timeout TO {0}'.format(timeout)) result = context['connection'].execute( u'SELECT * FROM pg_tables WHERE tablename = %s', data_dict['resource_id'] ).fetchone() if not result: create_table(context, data_dict) else: alter_table(context, data_dict) insert_data(context, data_dict) create_indexes(context, data_dict) create_alias(context, data_dict) if data_dict.get('private'): _change_privilege(context, data_dict, 'REVOKE') trans.commit() return _unrename_json_field(data_dict) except IntegrityError, e: if e.orig.pgcode == _PG_ERR_CODE['unique_violation']: raise ValidationError({ 'constraints': ['Cannot insert records or create index because' ' of uniqueness constraint'], 'info': { 'orig': str(e.orig), 'pgcode': e.orig.pgcode } }) raise except DataError, e: raise ValidationError({ 'data': e.message, 'info': { 'orig': [str(e.orig)] }}) except DBAPIError, e: if e.orig.pgcode == _PG_ERR_CODE['query_canceled']: raise ValidationError({ 'query': ['Query took too long'] }) raise except Exception, e: trans.rollback() raise finally: context['connection'].close() def upsert(context, data_dict): ''' This method combines upsert insert and update on the datastore. The method that will be used is defined in the mehtod variable. Any error results in total failure! For now pass back the actual error. Should be transactional. ''' engine = _get_engine(data_dict) context['connection'] = engine.connect() timeout = context.get('query_timeout', _TIMEOUT) trans = context['connection'].begin() try: # check if table already existes context['connection'].execute( u'SET LOCAL statement_timeout TO {0}'.format(timeout)) upsert_data(context, data_dict) trans.commit() return _unrename_json_field(data_dict) except IntegrityError, e: if e.orig.pgcode == _PG_ERR_CODE['unique_violation']: raise ValidationError({ 'constraints': ['Cannot insert records or create index because' ' of uniqueness constraint'], 'info': { 'orig': str(e.orig), 'pgcode': e.orig.pgcode } }) raise except DataError, e: raise ValidationError({ 'data': e.message, 'info': { 'orig': [str(e.orig)] }}) except DBAPIError, e: if e.orig.pgcode == _PG_ERR_CODE['query_canceled']: raise ValidationError({ 'query': ['Query took too long'] }) raise except Exception, e: trans.rollback() raise finally: context['connection'].close() def delete(context, data_dict): engine = _get_engine(data_dict) context['connection'] = engine.connect() _cache_types(context) trans = context['connection'].begin() try: # check if table exists if not 'filters' in data_dict: context['connection'].execute( u'DROP TABLE "{0}" CASCADE'.format(data_dict['resource_id']) ) else: delete_data(context, data_dict) trans.commit() return _unrename_json_field(data_dict) except Exception: trans.rollback() raise finally: context['connection'].close() def search(context, data_dict): engine = _get_engine(data_dict) context['connection'] = engine.connect() timeout = context.get('query_timeout', _TIMEOUT) _cache_types(context) try: context['connection'].execute( u'SET LOCAL statement_timeout TO {0}'.format(timeout)) return search_data(context, data_dict) except DBAPIError, e: if e.orig.pgcode == _PG_ERR_CODE['query_canceled']: raise ValidationError({ 'query': ['Search took too long'] }) raise ValidationError({ 'query': ['Invalid query'], 'info': { 'statement': [e.statement], 'params': [e.params], 'orig': [str(e.orig)] } }) finally: context['connection'].close() def search_sql(context, data_dict): engine = _get_engine(data_dict) context['connection'] = engine.connect() timeout = context.get('query_timeout', _TIMEOUT) _cache_types(context) try: context['connection'].execute( u'SET LOCAL statement_timeout TO {0}'.format(timeout)) results = context['connection'].execute( data_dict['sql'].replace('%', '%%') ) return format_results(context, results, data_dict) except ProgrammingError, e: if e.orig.pgcode == _PG_ERR_CODE['permission_denied']: raise toolkit.NotAuthorized({ 'permissions': ['Not authorized to read resource.'] }) raise ValidationError({ 'query': [str(e)], 'info': { 'statement': [e.statement], 'params': [e.params], 'orig': [str(e.orig)] } }) except DBAPIError, e: if e.orig.pgcode == _PG_ERR_CODE['query_canceled']: raise ValidationError({ 'query': ['Query took too long'] }) raise finally: context['connection'].close() def _get_read_only_user(data_dict): parsed = cli.parse_db_config('ckan.datastore.read_url') return parsed['db_user'] def _change_privilege(context, data_dict, what): ''' We need a transaction for this code to work ''' read_only_user = _get_read_only_user(data_dict) if what == 'REVOKE': sql = u'REVOKE SELECT ON TABLE "{0}" FROM "{1}"'.format( data_dict['resource_id'], read_only_user) elif what == 'GRANT': sql = u'GRANT SELECT ON TABLE "{0}" TO "{1}"'.format( data_dict['resource_id'], read_only_user) else: raise ValidationError({ 'privileges': 'Can only GRANT or REVOKE but not {0}'.format(what)}) try: context['connection'].execute(sql) except ProgrammingError, e: log.critical("Error making resource private. {0}".format(e.message)) raise ValidationError({ 'privileges': [u'cannot make "{0}" private'.format( data_dict['resource_id'])], 'info': { 'orig': str(e.orig), 'pgcode': e.orig.pgcode } }) def make_private(context, data_dict): log.info('Making resource {0} private'.format( data_dict['resource_id'])) engine = _get_engine(data_dict) context['connection'] = engine.connect() trans = context['connection'].begin() try: _change_privilege(context, data_dict, 'REVOKE') trans.commit() finally: context['connection'].close() def make_public(context, data_dict): log.info('Making resource {0} public'.format( data_dict['resource_id'])) engine = _get_engine(data_dict) context['connection'] = engine.connect() trans = context['connection'].begin() try: _change_privilege(context, data_dict, 'GRANT') trans.commit() finally: context['connection'].close() <file_sep>'''API functions for searching for and getting data from CKAN.''' import uuid import logging import json import datetime import socket from pylons import config import sqlalchemy import ckan.lib.dictization import ckan.logic as logic import ckan.logic.action import ckan.logic.schema import ckan.lib.dictization.model_dictize as model_dictize import ckan.lib.navl.dictization_functions import ckan.model as model import ckan.model.misc as misc import ckan.plugins as plugins import ckan.lib.search as search import ckan.lib.plugins as lib_plugins import ckan.lib.activity_streams as activity_streams import ckan.new_authz as new_authz from ckan.common import _ log = logging.getLogger('ckan.logic') # Define some shortcuts # Ensure they are module-private so that they don't get loaded as available # actions in the action API. _validate = ckan.lib.navl.dictization_functions.validate _table_dictize = ckan.lib.dictization.table_dictize _check_access = logic.check_access NotFound = logic.NotFound ValidationError = logic.ValidationError _get_or_bust = logic.get_or_bust _select = sqlalchemy.sql.select _aliased = sqlalchemy.orm.aliased _or_ = sqlalchemy.or_ _and_ = sqlalchemy.and_ _func = sqlalchemy.func _desc = sqlalchemy.desc _case = sqlalchemy.case _text = sqlalchemy.text def _package_list_with_resources(context, package_revision_list): package_list = [] for package in package_revision_list: result_dict = model_dictize.package_dictize(package,context) package_list.append(result_dict) return package_list def site_read(context,data_dict=None): '''Return ``True``. :rtype: boolean ''' _check_access('site_read',context,data_dict) return True @logic.validate(logic.schema.default_pagination_schema) def package_list(context, data_dict): '''Return a list of the names of the site's datasets (packages). :param limit: if given, the list of datasets will be broken into pages of at most ``limit`` datasets per page and only one page will be returned at a time (optional) :type limit: int :param offset: when ``limit`` is given, the offset to start returning packages from :type offset: int :rtype: list of strings ''' model = context["model"] api = context.get("api_version", 1) _check_access('package_list', context, data_dict) package_revision_table = model.package_revision_table col = (package_revision_table.c.id if api == 2 else package_revision_table.c.name) query = _select([col]) query = query.where(_and_( package_revision_table.c.state=='active', package_revision_table.c.current==True, package_revision_table.c.private==False, )) query = query.order_by(col) limit = data_dict.get('limit') if limit: query = query.limit(limit) offset = data_dict.get('offset') if offset: query = query.offset(offset) ## Returns the first field in each result record return [r[0] for r in query.execute()] @logic.validate(logic.schema.default_package_list_schema) def current_package_list_with_resources(context, data_dict): '''Return a list of the site's datasets (packages) and their resources. The list is sorted most-recently-modified first. :param limit: if given, the list of datasets will be broken into pages of at most ``limit`` datasets per page and only one page will be returned at a time (optional) :type limit: int :param offset: when ``limit`` is given, the offset to start returning packages from :type offset: int :param page: when ``limit`` is given, which page to return, Deprecated use ``offset`` :type page: int :rtype: list of dictionaries ''' model = context["model"] limit = data_dict.get('limit') offset = data_dict.get('offset', 0) if not 'offset' in data_dict and 'page' in data_dict: log.warning('"page" parameter is deprecated. ' 'Use the "offset" parameter instead') page = data_dict['page'] if limit: offset = (page - 1) * limit else: offset = 0 _check_access('current_package_list_with_resources', context, data_dict) query = model.Session.query(model.PackageRevision) query = query.filter(model.PackageRevision.state=='active') query = query.filter(model.PackageRevision.current==True) query = query.order_by(model.package_revision_table.c.revision_timestamp.desc()) if limit is not None: query = query.limit(limit) query = query.offset(offset) pack_rev = query.all() return _package_list_with_resources(context, pack_rev) def revision_list(context, data_dict): '''Return a list of the IDs of the site's revisions. :rtype: list of strings ''' model = context['model'] _check_access('revision_list', context, data_dict) revs = model.Session.query(model.Revision).all() return [rev.id for rev in revs] def package_revision_list(context, data_dict): '''Return a dataset (package)'s revisions as a list of dictionaries. :param id: the id or name of the dataset :type id: string ''' model = context["model"] id = _get_or_bust(data_dict, "id") pkg = model.Package.get(id) if pkg is None: raise NotFound _check_access('package_revision_list',context, data_dict) revision_dicts = [] for revision, object_revisions in pkg.all_related_revisions: revision_dicts.append(model.revision_as_dict(revision, include_packages=False, include_groups=False)) return revision_dicts def related_show(context, data_dict=None): '''Return a single related item. :param id: the id of the related item to show :type id: string :rtype: dictionary ''' model = context['model'] id = _get_or_bust(data_dict, 'id') related = model.Related.get(id) context['related'] = related if related is None: raise NotFound _check_access('related_show',context, data_dict) schema = context.get('schema') or ckan.logic.schema.default_related_schema() related_dict = model_dictize.related_dictize(related, context) related_dict, errors = _validate(related_dict, schema, context=context) return related_dict def related_list(context, data_dict=None): '''Return a dataset's related items. :param id: id or name of the dataset (optional) :type id: string :param dataset: dataset dictionary of the dataset (optional) :type dataset: dictionary :param type_filter: the type of related item to show (optional, default: None, show all items) :type type_filter: string :param sort: the order to sort the related items in, possible values are 'view_count_asc', 'view_count_desc', 'created_asc' or 'created_desc' (optional) :type sort: string :param featured: whether or not to restrict the results to only featured related items (optional, default: False) :type featured: bool :rtype: list of dictionaries ''' model = context['model'] dataset = data_dict.get('dataset', None) if not dataset: dataset = model.Package.get(data_dict.get('id')) _check_access('related_show',context, data_dict) related_list = [] if not dataset: related_list = model.Session.query(model.Related) filter_on_type = data_dict.get('type_filter', None) if filter_on_type: related_list = related_list.filter(model.Related.type == filter_on_type) sort = data_dict.get('sort', None) if sort: sortables = { 'view_count_asc' : model.Related.view_count.asc, 'view_count_desc': model.Related.view_count.desc, 'created_asc' : model.Related.created.asc, 'created_desc': model.Related.created.desc, } s = sortables.get(sort, None) if s: related_list = related_list.order_by( s() ) if data_dict.get('featured', False): related_list = related_list.filter(model.Related.featured == 1) related_items = related_list.all() context['sorted'] = True else: relateds = model.Related.get_for_dataset(dataset, status='active') related_items = (r.related for r in relateds) related_list = model_dictize.related_list_dictize( related_items, context) return related_list def member_list(context, data_dict=None): '''Return the members of a group. The user must have permission to 'get' the group. :param id: the id or name of the group :type id: string :param object_type: restrict the members returned to those of a given type, e.g. ``'user'`` or ``'package'`` (optional, default: ``None``) :type object_type: string :param capacity: restrict the members returned to those with a given capacity, e.g. ``'member'``, ``'editor'``, ``'admin'``, ``'public'``, ``'private'`` (optional, default: ``None``) :type capacity: string :rtype: list of (id, type, capacity) tuples :raises: :class:`ckan.logic.NotFound`: if the group doesn't exist ''' model = context['model'] group = model.Group.get(_get_or_bust(data_dict, 'id')) if not group: raise NotFound obj_type = data_dict.get('object_type', None) capacity = data_dict.get('capacity', None) # User must be able to update the group to remove a member from it _check_access('group_show', context, data_dict) q = model.Session.query(model.Member).\ filter(model.Member.group_id == group.id).\ filter(model.Member.state == "active") if obj_type: q = q.filter(model.Member.table_name == obj_type) if capacity: q = q.filter(model.Member.capacity == capacity) trans = new_authz.roles_trans() def translated_capacity(capacity): try: return trans[capacity] except KeyError: return capacity return [(m.table_id, m.table_name, translated_capacity(m.capacity)) for m in q.all()] def _group_or_org_list(context, data_dict, is_org=False): model = context['model'] user = context['user'] api = context.get('api_version') groups = data_dict.get('groups') ref_group_by = 'id' if api == 2 else 'name' sort = data_dict.get('sort', 'name') q = data_dict.get('q') # order_by deprecated in ckan 1.8 # if it is supplied and sort isn't use order_by and raise a warning order_by = data_dict.get('order_by', '') if order_by: log.warn('`order_by` deprecated please use `sort`') if not data_dict.get('sort'): sort = order_by # if the sort is packages and no sort direction is supplied we want to do a # reverse sort to maintain compatibility. if sort.strip() == 'packages': sort = 'packages desc' sort_info = _unpick_search(sort, allowed_fields=['name', 'packages'], total=1) all_fields = data_dict.get('all_fields', None) query = model.Session.query(model.Group).join(model.GroupRevision) query = query.filter(model.GroupRevision.state=='active') query = query.filter(model.GroupRevision.current==True) if groups: query = query.filter(model.GroupRevision.name.in_(groups)) if q: q = u'%{0}%'.format(q) query = query.filter(_or_( model.GroupRevision.name.ilike(q), model.GroupRevision.title.ilike(q), model.GroupRevision.description.ilike(q), )) query = query.filter(model.GroupRevision.is_organization==is_org) groups = query.all() group_list = model_dictize.group_list_dictize(groups, context, lambda x:x[sort_info[0][0]], sort_info[0][1] == 'desc') if not all_fields: group_list = [group[ref_group_by] for group in group_list] return group_list def group_list(context, data_dict): '''Return a list of the names of the site's groups. :param order_by: the field to sort the list by, must be ``'name'`` or ``'packages'`` (optional, default: ``'name'``) Deprecated use sort. :type order_by: string :param sort: sorting of the search results. Optional. Default: "name asc" string of field name and sort-order. The allowed fields are 'name' and 'packages' :type sort: string :param groups: a list of names of the groups to return, if given only groups whose names are in this list will be returned (optional) :type groups: list of strings :param all_fields: return full group dictionaries instead of just names (optional, default: ``False``) :type all_fields: boolean :rtype: list of strings ''' _check_access('group_list', context, data_dict) data_dict['type'] = 'group' return _group_or_org_list(context, data_dict) def organization_list(context, data_dict): '''Return a list of the names of the site's organizations. :param order_by: the field to sort the list by, must be ``'name'`` or ``'packages'`` (optional, default: ``'name'``) Deprecated use sort. :type order_by: string :param sort: sorting of the search results. Optional. Default: "name asc" string of field name and sort-order. The allowed fields are 'name' and 'packages' :type sort: string :param organizations: a list of names of the groups to return, if given only groups whose names are in this list will be returned (optional) :type organizations: list of strings :param all_fields: return full group dictionaries instead of just names (optional, default: ``False``) :type all_fields: boolean :rtype: list of strings ''' _check_access('organization_list', context, data_dict) data_dict['groups'] = data_dict.pop('organizations', []) data_dict['type'] = 'organization' return _group_or_org_list(context, data_dict, is_org=True) def group_list_authz(context, data_dict): '''Return the list of groups that the user is authorized to edit. :param available_only: remove the existing groups in the package (optional, default: ``False``) :type available_only: boolean :param am_member: if True return only the groups the logged-in user is a member of, otherwise return all groups that the user is authorized to edit (for example, sysadmin users are authorized to edit all groups) (optional, default: False) :type am-member: boolean :returns: list of dictized groups that the user is authorized to edit :rtype: list of dicts ''' model = context['model'] user = context['user'] available_only = data_dict.get('available_only', False) am_member = data_dict.get('am_member', False) _check_access('group_list_authz',context, data_dict) sysadmin = new_authz.is_sysadmin(user) roles = ckan.new_authz.get_roles_with_permission('manage_group') if not roles: return [] user_id = new_authz.get_user_id_for_username(user, allow_none=True) if not user_id: return [] if not sysadmin or am_member: q = model.Session.query(model.Member) \ .filter(model.Member.table_name == 'user') \ .filter(model.Member.capacity.in_(roles)) \ .filter(model.Member.table_id == user_id) group_ids = [] for row in q.all(): group_ids.append(row.group_id) if not group_ids: return [] q = model.Session.query(model.Group) \ .filter(model.Group.is_organization == False) \ .filter(model.Group.state == 'active') if not sysadmin or am_member: q = q.filter(model.Group.id.in_(group_ids)) groups = q.all() if available_only: package = context.get('package') if package: groups = set(groups) - set(package.get_groups()) group_list = model_dictize.group_list_dictize(groups, context) return group_list def organization_list_for_user(context, data_dict): '''Return the list of organizations that the user is a member of. :param permission: the permission the user has against the returned organizations (optional, default: ``edit_group``) :type permission: string :returns: list of dictized organizations that the user is authorized to edit :rtype: list of dicts ''' model = context['model'] user = context['user'] _check_access('organization_list_for_user',context, data_dict) sysadmin = new_authz.is_sysadmin(user) orgs_q = model.Session.query(model.Group) \ .filter(model.Group.is_organization == True) \ .filter(model.Group.state == 'active') if not sysadmin: # for non-Sysadmins check they have the required permission permission = data_dict.get('permission', 'edit_group') roles = ckan.new_authz.get_roles_with_permission(permission) if not roles: return [] user_id = new_authz.get_user_id_for_username(user, allow_none=True) if not user_id: return [] q = model.Session.query(model.Member) \ .filter(model.Member.table_name == 'user') \ .filter(model.Member.capacity.in_(roles)) \ .filter(model.Member.table_id == user_id) group_ids = [] for row in q.all(): group_ids.append(row.group_id) if not group_ids: return [] orgs_q = orgs_q.filter(model.Group.id.in_(group_ids)) orgs_list = model_dictize.group_list_dictize(orgs_q.all(), context) return orgs_list def _group_or_org_revision_list(context, data_dict): '''Return a group's revisions. :param id: the name or id of the group :type id: string :rtype: list of dictionaries ''' model = context['model'] id = _get_or_bust(data_dict, 'id') group = model.Group.get(id) if group is None: raise NotFound revision_dicts = [] for revision, object_revisions in group.all_related_revisions: revision_dicts.append(model.revision_as_dict(revision, include_packages=False, include_groups=False)) return revision_dicts def group_revision_list(context, data_dict): '''Return a group's revisions. :param id: the name or id of the group :type id: string :rtype: list of dictionaries ''' _check_access('group_revision_list',context, data_dict) return _group_or_org_revision_list(context, data_dict) def organization_revision_list(context, data_dict): '''Return an organization's revisions. :param id: the name or id of the organization :type id: string :rtype: list of dictionaries ''' _check_access('organization_revision_list',context, data_dict) return _group_or_org_revision_list(context, data_dict) def license_list(context, data_dict): '''Return the list of licenses available for datasets on the site. :rtype: list of dictionaries ''' model = context["model"] _check_access('license_list',context, data_dict) license_register = model.Package.get_license_register() licenses = license_register.values() licenses = [l.as_dict() for l in licenses] return licenses def tag_list(context, data_dict): '''Return a list of the site's tags. By default only free tags (tags that don't belong to a vocabulary) are returned. If the ``vocabulary_id`` argument is given then only tags belonging to that vocabulary will be returned instead. :param query: a tag name query to search for, if given only tags whose names contain this string will be returned (optional) :type query: string :param vocabulary_id: the id or name of a vocabulary, if give only tags that belong to this vocabulary will be returned (optional) :type vocabulary_id: string :param all_fields: return full tag dictionaries instead of just names (optional, default: ``False``) :type all_fields: boolean :rtype: list of dictionaries ''' model = context['model'] vocab_id_or_name = data_dict.get('vocabulary_id') query = data_dict.get('query') or data_dict.get('q') if query: query = query.strip() all_fields = data_dict.get('all_fields', None) _check_access('tag_list', context, data_dict) if query: tags, count = _tag_search(context, data_dict) else: tags = model.Tag.all(vocab_id_or_name) if tags: if all_fields: tag_list = model_dictize.tag_list_dictize(tags, context) else: tag_list = [tag.name for tag in tags] else: tag_list = [] return tag_list def user_list(context, data_dict): '''Return a list of the site's user accounts. :param q: restrict the users returned to those whose names contain a string (optional) :type q: string :param order_by: which field to sort the list by (optional, default: ``'name'``) :type order_by: string :rtype: list of dictionaries ''' model = context['model'] _check_access('user_list',context, data_dict) q = data_dict.get('q','') order_by = data_dict.get('order_by','name') query = model.Session.query( model.User, model.User.name.label('name'), model.User.fullname.label('fullname'), model.User.about.label('about'), model.User.about.label('email'), model.User.created.label('created'), _select([_func.count(model.Revision.id)], _or_( model.Revision.author==model.User.name, model.Revision.author==model.User.openid ) ).label('number_of_edits'), _select([_func.count(model.UserObjectRole.id)], _and_( model.UserObjectRole.user_id==model.User.id, model.UserObjectRole.context=='Package', model.UserObjectRole.role=='admin' ) ).label('number_administered_packages') ) if q: query = model.User.search(q, query, user_name=context.get('user')) if order_by == 'edits': query = query.order_by(_desc( _select([_func.count(model.Revision.id)], _or_( model.Revision.author==model.User.name, model.Revision.author==model.User.openid )) )) else: query = query.order_by( _case([(_or_(model.User.fullname == None, model.User.fullname == ''), model.User.name)], else_=model.User.fullname) ) # Filter deleted users query = query.filter(model.User.state != model.State.DELETED) ## hack for pagination if context.get('return_query'): return query users_list = [] for user in query.all(): result_dict = model_dictize.user_dictize(user[0], context) users_list.append(result_dict) return users_list def package_relationships_list(context, data_dict): '''Return a dataset (package)'s relationships. :param id: the id or name of the first package :type id: string :param id2: the id or name of the second package :type id: string :param rel: relationship as string see :func:`ckan.logic.action.create.package_relationship_create()` for the relationship types (optional) :rtype: list of dictionaries ''' ##TODO needs to work with dictization layer model = context['model'] api = context.get('api_version') id = _get_or_bust(data_dict, "id") id2 = data_dict.get("id2") rel = data_dict.get("rel") ref_package_by = 'id' if api == 2 else 'name' pkg1 = model.Package.get(id) pkg2 = None if not pkg1: raise NotFound('First package named in request was not found.') if id2: pkg2 = model.Package.get(id2) if not pkg2: raise NotFound('Second package named in address was not found.') if rel == 'relationships': rel = None _check_access('package_relationships_list',context, data_dict) # TODO: How to handle this object level authz? # Currently we don't care relationships = pkg1.get_relationships(with_package=pkg2, type=rel) if rel and not relationships: raise NotFound('Relationship "%s %s %s" not found.' % (id, rel, id2)) relationship_dicts = [rel.as_dict(pkg1, ref_package_by=ref_package_by) for rel in relationships] return relationship_dicts def package_show(context, data_dict): '''Return the metadata of a dataset (package) and its resources. :param id: the id or name of the dataset :type id: string :param use_default_schema: use default package schema instead of a custom schema defined with an IDatasetForm plugin (default: False) :type use_default_schema: bool :rtype: dictionary ''' model = context['model'] context['session'] = model.Session name_or_id = data_dict.get("id") or _get_or_bust(data_dict, 'name_or_id') pkg = model.Package.get(name_or_id) if pkg is None: raise NotFound context['package'] = pkg _check_access('package_show', context, data_dict) if data_dict.get('use_default_schema', False): context['schema'] = ckan.logic.schema.default_show_package_schema() package_dict = None use_cache = (context.get('use_cache', True) and not 'revision_id' in context and not 'revision_date' in context) if use_cache: try: search_result = search.show(name_or_id) except (search.SearchError, socket.error): pass else: use_validated_cache = 'schema' not in context if use_validated_cache and 'validated_data_dict' in search_result: package_dict = json.loads(search_result['validated_data_dict']) package_dict_validated = True else: package_dict = json.loads(search_result['data_dict']) package_dict_validated = False metadata_modified = pkg.metadata_modified.isoformat() search_metadata_modified = search_result['metadata_modified'] # solr stores less precice datetime, # truncate to 22 charactors to get good enough match if metadata_modified[:22] != search_metadata_modified[:22]: package_dict = None if not package_dict: package_dict = model_dictize.package_dictize(pkg, context) package_dict_validated = False # Add page-view tracking summary data to the package dict. # If the package_dict came from the Solr cache then it will already have a # potentially outdated tracking_summary, this will overwrite it with a # current one. package_dict['tracking_summary'] = model.TrackingSummary.get_for_package( package_dict['id']) # Add page-view tracking summary data to the package's resource dicts. # If the package_dict came from the Solr cache then each resource dict will # already have a potentially outdated tracking_summary, this will overwrite # it with a current one. for resource_dict in package_dict['resources']: _add_tracking_summary_to_resource_dict(resource_dict, model) if context.get('for_view'): for item in plugins.PluginImplementations(plugins.IPackageController): package_dict = item.before_view(package_dict) for item in plugins.PluginImplementations(plugins.IPackageController): item.read(pkg) for resource_dict in package_dict['resources']: for item in plugins.PluginImplementations(plugins.IResourceController): resource_dict = item.before_show(resource_dict) if not package_dict_validated: package_plugin = lib_plugins.lookup_package_plugin(package_dict['type']) if 'schema' in context: schema = context['schema'] else: schema = package_plugin.show_package_schema() if schema and context.get('validate', True): package_dict, errors = _validate(package_dict, schema, context=context) for item in plugins.PluginImplementations(plugins.IPackageController): item.after_show(context, package_dict) return package_dict def _add_tracking_summary_to_resource_dict(resource_dict, model): '''Add page-view tracking summary data to the given resource dict. ''' tracking_summary = model.TrackingSummary.get_for_resource( resource_dict['url']) resource_dict['tracking_summary'] = tracking_summary def resource_show(context, data_dict): '''Return the metadata of a resource. :param id: the id of the resource :type id: string :rtype: dictionary ''' model = context['model'] id = _get_or_bust(data_dict, 'id') resource = model.Resource.get(id) context['resource'] = resource if not resource: raise NotFound _check_access('resource_show', context, data_dict) resource_dict = model_dictize.resource_dictize(resource, context) _add_tracking_summary_to_resource_dict(resource_dict, model) for item in plugins.PluginImplementations(plugins.IResourceController): if('for_edit' in context and context['for_edit']): resource_dict = item.before_edit(resource_dict) else: resource_dict = item.before_show(resource_dict) return resource_dict def resource_status_show(context, data_dict): '''Return the statuses of a resource's tasks. :param id: the id of the resource :type id: string :rtype: list of (status, date_done, traceback, task_status) dictionaries ''' try: import ckan.lib.celery_app as celery_app except ImportError: return {'message': 'queue is not installed on this instance'} model = context['model'] id = _get_or_bust(data_dict, 'id') _check_access('resource_status_show', context, data_dict) # needs to be text query as celery tables are not in our model q = _text("""select status, date_done, traceback, task_status.* from task_status left join celery_taskmeta on task_status.value = celery_taskmeta.task_id and key = 'celery_task_id' where entity_id = :entity_id """) result = model.Session.connection().execute(q, entity_id=id) result_list = [_table_dictize(row, context) for row in result] return result_list @logic.auth_audit_exempt def revision_show(context, data_dict): '''Return the details of a revision. :param id: the id of the revision :type id: string :rtype: dictionary ''' model = context['model'] api = context.get('api_version') id = _get_or_bust(data_dict, 'id') ref_package_by = 'id' if api == 2 else 'name' rev = model.Session.query(model.Revision).get(id) if rev is None: raise NotFound rev_dict = model.revision_as_dict(rev, include_packages=True, ref_package_by=ref_package_by) return rev_dict def _group_or_org_show(context, data_dict, is_org=False): model = context['model'] id = _get_or_bust(data_dict, 'id') group = model.Group.get(id) context['group'] = group include_datasets = data_dict.get('include_datasets', True) if isinstance(include_datasets, basestring): include_datasets = (include_datasets.lower() in ('true', '1')) context['include_datasets'] = include_datasets if group is None: raise NotFound if is_org and not group.is_organization: raise NotFound if not is_org and group.is_organization: raise NotFound if is_org: _check_access('organization_show',context, data_dict) else: _check_access('group_show',context, data_dict) group_dict = model_dictize.group_dictize(group, context) if is_org: plugin_type = plugins.IOrganizationController else: plugin_type = plugins.IGroupController for item in plugins.PluginImplementations(plugin_type): item.read(group) group_plugin = lib_plugins.lookup_group_plugin(group_dict['type']) try: schema = group_plugin.db_to_form_schema_options({ 'type':'show', 'api': 'api_version' in context, 'context': context }) except AttributeError: schema = group_plugin.db_to_form_schema() group_dict['num_followers'] = logic.get_action('group_follower_count')( {'model': model, 'session': model.Session}, {'id': group_dict['id']}) if schema: group_dict, errors = _validate(group_dict, schema, context=context) return group_dict def group_show(context, data_dict): '''Return the details of a group. :param id: the id or name of the group :type id: string :param include_datasets: include a list of the group's datasets (optional, default: ``True``) :type id: boolean :rtype: dictionary .. note:: Only its first 1000 datasets are returned ''' return _group_or_org_show(context, data_dict) def organization_show(context, data_dict): '''Return the details of a organization. :param id: the id or name of the organization :type id: string :param include_datasets: include a list of the organization's datasets (optional, default: ``True``) :type id: boolean :rtype: dictionary .. note:: Only its first 1000 datasets are returned ''' return _group_or_org_show(context, data_dict, is_org=True) def group_package_show(context, data_dict): '''Return the datasets (packages) of a group. :param id: the id or name of the group :type id: string :param limit: the maximum number of datasets to return (optional) :type limit: int :rtype: list of dictionaries ''' model = context['model'] group_id = _get_or_bust(data_dict, 'id') # FIXME: What if limit is not an int? Schema and validation needed. limit = data_dict.get('limit') group = model.Group.get(group_id) context['group'] = group if group is None: raise NotFound _check_access('group_show', context, data_dict) result = [] for pkg_rev in group.packages(limit=limit, return_query=context.get('return_query')): result.append(model_dictize.package_dictize(pkg_rev, context)) return result def tag_show(context, data_dict): '''Return the details of a tag and all its datasets. :param id: the name or id of the tag :type id: string :returns: the details of the tag, including a list of all of the tag's datasets and their details :rtype: dictionary ''' model = context['model'] id = _get_or_bust(data_dict, 'id') tag = model.Tag.get(id) context['tag'] = tag if tag is None: raise NotFound _check_access('tag_show',context, data_dict) return model_dictize.tag_dictize(tag,context) def user_show(context, data_dict): '''Return a user account. Either the ``id`` or the ``user_obj`` parameter must be given. :param id: the id or name of the user (optional) :type id: string :param user_obj: the user dictionary of the user (optional) :type user_obj: user dictionary :rtype: dictionary ''' model = context['model'] id = data_dict.get('id',None) provided_user = data_dict.get('user_obj',None) if id: user_obj = model.User.get(id) context['user_obj'] = user_obj if user_obj is None: raise NotFound elif provided_user: context['user_obj'] = user_obj = provided_user else: raise NotFound _check_access('user_show',context, data_dict) user_dict = model_dictize.user_dictize(user_obj,context) if context.get('return_minimal'): return user_dict revisions_q = model.Session.query(model.Revision ).filter_by(author=user_obj.name) revisions_list = [] for revision in revisions_q.limit(20).all(): revision_dict = logic.get_action('revision_show')(context,{'id':revision.id}) revision_dict['state'] = revision.state revisions_list.append(revision_dict) user_dict['activity'] = revisions_list user_dict['datasets'] = [] dataset_q = model.Session.query(model.Package).join(model.PackageRole ).filter_by(user=user_obj, role=model.Role.ADMIN ).limit(50) for dataset in dataset_q: try: dataset_dict = logic.get_action('package_show')(context, {'id': dataset.id}) except logic.NotAuthorized: continue user_dict['datasets'].append(dataset_dict) user_dict['num_followers'] = logic.get_action('user_follower_count')( {'model': model, 'session': model.Session}, {'id': user_dict['id']}) return user_dict def package_show_rest(context, data_dict): _check_access('package_show_rest',context, data_dict) logic.get_action('package_show')(context, data_dict) pkg = context['package'] package_dict = model_dictize.package_to_api(pkg, context) return package_dict def group_show_rest(context, data_dict): _check_access('group_show_rest',context, data_dict) logic.get_action('group_show')(context, data_dict) group = context['group'] group_dict = model_dictize.group_to_api(group, context) return group_dict def tag_show_rest(context, data_dict): _check_access('tag_show_rest',context, data_dict) logic.get_action('tag_show')(context, data_dict) tag = context['tag'] tag_dict = model_dictize.tag_to_api(tag, context) return tag_dict @logic.validate(logic.schema.default_autocomplete_schema) def package_autocomplete(context, data_dict): '''Return a list of datasets (packages) that match a string. Datasets with names or titles that contain the query string will be returned. :param q: the string to search for :type q: string :param limit: the maximum number of resource formats to return (optional, default: 10) :type limit: int :rtype: list of dictionaries ''' model = context['model'] _check_access('package_autocomplete', context, data_dict) limit = data_dict.get('limit', 10) q = data_dict['q'] like_q = u"%s%%" % q query = model.Session.query(model.PackageRevision) query = query.filter(model.PackageRevision.state=='active') query = query.filter(model.PackageRevision.current==True) query = query.filter(_or_(model.PackageRevision.name.ilike(like_q), model.PackageRevision.title.ilike(like_q))) query = query.limit(limit) q_lower = q.lower() pkg_list = [] for package in query: if package.name.startswith(q_lower): match_field = 'name' match_displayed = package.name else: match_field = 'title' match_displayed = '%s (%s)' % (package.title, package.name) result_dict = {'name':package.name, 'title':package.title, 'match_field':match_field, 'match_displayed':match_displayed} pkg_list.append(result_dict) return pkg_list @logic.validate(logic.schema.default_autocomplete_schema) def format_autocomplete(context, data_dict): '''Return a list of resource formats whose names contain a string. :param q: the string to search for :type q: string :param limit: the maximum number of resource formats to return (optional, default: 5) :type limit: int :rtype: list of strings ''' model = context['model'] session = context['session'] _check_access('format_autocomplete', context, data_dict) q = data_dict['q'] limit = data_dict.get('limit', 5) like_q = u'%' + q + u'%' query = session.query(model.ResourceRevision.format, _func.count(model.ResourceRevision.format).label('total'))\ .filter(_and_( model.ResourceRevision.state == 'active', model.ResourceRevision.current == True ))\ .filter(model.ResourceRevision.format.ilike(like_q))\ .group_by(model.ResourceRevision.format)\ .order_by('total DESC')\ .limit(limit) return [resource.format.lower() for resource in query] @logic.validate(logic.schema.default_autocomplete_schema) def user_autocomplete(context, data_dict): '''Return a list of user names that contain a string. :param q: the string to search for :type q: string :param limit: the maximum number of user names to return (optional, default: 20) :type limit: int :rtype: a list of user dictionaries each with keys ``'name'``, ``'fullname'``, and ``'id'`` ''' model = context['model'] user = context['user'] _check_access('user_autocomplete', context, data_dict) q = data_dict['q'] limit = data_dict.get('limit', 20) query = model.User.search(q) query = query.filter(model.User.state != model.State.DELETED) query = query.limit(limit) user_list = [] for user in query.all(): result_dict = {} for k in ['id', 'name', 'fullname']: result_dict[k] = getattr(user,k) user_list.append(result_dict) return user_list def package_search(context, data_dict): ''' Searches for packages satisfying a given search criteria. This action accepts solr search query parameters (details below), and returns a dictionary of results, including dictized datasets that match the search criteria, a search count and also facet information. **Solr Parameters:** For more in depth treatment of each paramter, please read the `Solr Documentation <http://wiki.apache.org/solr/CommonQueryParameters>`_. This action accepts a *subset* of solr's search query parameters: :param q: the solr query. Optional. Default: `"*:*"` :type q: string :param fq: any filter queries to apply. Note: `+site_id:{ckan_site_id}` is added to this string prior to the query being executed. :type fq: string :param sort: sorting of the search results. Optional. Default: 'relevance asc, metadata_modified desc'. As per the solr documentation, this is a comma-separated string of field names and sort-orderings. :type sort: string :param rows: the number of matching rows to return. :type rows: int :param start: the offset in the complete result for where the set of returned datasets should begin. :type start: int :param facet: whether to enable faceted results. Default: "true". :type facet: string :param facet.mincount: the minimum counts for facet fields should be included in the results. :type facet.mincount: int :param facet.limit: the maximum number of values the facet fields return. A negative value means unlimited. This can be set instance-wide with the :ref:`search.facets.limit` config option. Default is 50. :type facet.limit: int :param facet.field: the fields to facet upon. Default empty. If empty, then the returned facet information is empty. :type facet.field: list of strings The following advanced Solr parameters are supported as well. Note that some of these are only available on particular Solr versions. See Solr's `dismax`_ and `edismax`_ documentation for further details on them: ``qf``, ``wt``, ``bf``, ``boost``, ``tie``, ``defType``, ``mm`` .. _dismax: http://wiki.apache.org/solr/DisMaxQParserPlugin .. _edismax: http://wiki.apache.org/solr/ExtendedDisMax **Results:** The result of this action is a dict with the following keys: :rtype: A dictionary with the following keys :param count: the number of results found. Note, this is the total number of results found, not the total number of results returned (which is affected by limit and row parameters used in the input). :type count: int :param results: ordered list of datasets matching the query, where the ordering defined by the sort parameter used in the query. :type results: list of dictized datasets. :param facets: DEPRECATED. Aggregated information about facet counts. :type facets: DEPRECATED dict :param search_facets: aggregated information about facet counts. The outer dict is keyed by the facet field name (as used in the search query). Each entry of the outer dict is itself a dict, with a "title" key, and an "items" key. The "items" key's value is a list of dicts, each with "count", "display_name" and "name" entries. The display_name is a form of the name that can be used in titles. :type search_facets: nested dict of dicts. :param use_default_schema: use default package schema instead of a custom schema defined with an IDatasetForm plugin (default: False) :type use_default_schema: bool An example result: :: {'count': 2, 'results': [ { <snip> }, { <snip> }], 'search_facets': {u'tags': {'items': [{'count': 1, 'display_name': u'tolstoy', 'name': u'tolstoy'}, {'count': 2, 'display_name': u'russian', 'name': u'russian'} ] } } } **Limitations:** The full solr query language is not exposed, including. fl The parameter that controls which fields are returned in the solr query cannot be changed. CKAN always returns the matched datasets as dictionary objects. ''' # sometimes context['schema'] is None schema = (context.get('schema') or logic.schema.default_package_search_schema()) data_dict, errors = _validate(data_dict, schema, context) # put the extras back into the data_dict so that the search can # report needless parameters data_dict.update(data_dict.get('__extras', {})) data_dict.pop('__extras', None) if errors: raise ValidationError(errors) model = context['model'] session = context['session'] _check_access('package_search', context, data_dict) # Move ext_ params to extras and remove them from the root of the search # params, so they don't cause and error data_dict['extras'] = data_dict.get('extras', {}) for key in [key for key in data_dict.keys() if key.startswith('ext_')]: data_dict['extras'][key] = data_dict.pop(key) # check if some extension needs to modify the search params for item in plugins.PluginImplementations(plugins.IPackageController): data_dict = item.before_search(data_dict) # the extension may have decided that it is not necessary to perform # the query abort = data_dict.get('abort_search', False) if data_dict.get('sort') in (None, 'rank'): data_dict['sort'] = 'score desc, metadata_modified desc' results = [] if not abort: data_source = 'data_dict' if data_dict.get('use_default_schema', False) else 'validated_data_dict' # return a list of package ids data_dict['fl'] = 'id {0}'.format(data_source) # If this query hasn't come from a controller that has set this flag # then we should remove any mention of capacity from the fq and # instead set it to only retrieve public datasets fq = data_dict.get('fq', '') if not context.get('ignore_capacity_check', False): fq = ' '.join(p for p in fq.split(' ') if not 'capacity:' in p) data_dict['fq'] = fq + ' capacity:"public"' # Pop these ones as Solr does not need them extras = data_dict.pop('extras', None) query = search.query_for(model.Package) query.run(data_dict) # Add them back so extensions can use them on after_search data_dict['extras'] = extras for package in query.results: # get the package object package, package_dict = package['id'], package.get(data_source) pkg_query = session.query(model.PackageRevision)\ .filter(model.PackageRevision.id == package)\ .filter(_and_( model.PackageRevision.state == u'active', model.PackageRevision.current == True )) pkg = pkg_query.first() ## if the index has got a package that is not in ckan then ## ignore it. if not pkg: log.warning('package %s in index but not in database' % package) continue ## use data in search index if there if package_dict: ## the package_dict still needs translating when being viewed package_dict = json.loads(package_dict) if context.get('for_view'): for item in plugins.PluginImplementations( plugins.IPackageController): package_dict = item.before_view(package_dict) results.append(package_dict) else: results.append(model_dictize.package_dictize(pkg,context)) count = query.count facets = query.facets else: count = 0 facets = {} results = [] search_results = { 'count': count, 'facets': facets, 'results': results, 'sort': data_dict['sort'] } # Transform facets into a more useful data structure. restructured_facets = {} for key, value in facets.items(): restructured_facets[key] = { 'title': key, 'items': [] } for key_, value_ in value.items(): new_facet_dict = {} new_facet_dict['name'] = key_ if key in ('groups', 'organization'): group = model.Group.get(key_) if group: new_facet_dict['display_name'] = group.display_name else: new_facet_dict['display_name'] = key_ elif key == 'license_id': license = model.Package.get_license_register().get(key_) if license: new_facet_dict['display_name'] = license.title else: new_facet_dict['display_name'] = key_ else: new_facet_dict['display_name'] = key_ new_facet_dict['count'] = value_ restructured_facets[key]['items'].append(new_facet_dict) search_results['search_facets'] = restructured_facets # check if some extension needs to modify the search results for item in plugins.PluginImplementations(plugins.IPackageController): search_results = item.after_search(search_results,data_dict) # After extensions have had a chance to modify the facets, sort them by # display name. for facet in search_results['search_facets']: search_results['search_facets'][facet]['items'] = sorted( search_results['search_facets'][facet]['items'], key=lambda facet: facet['display_name'], reverse=True) return search_results @logic.validate(logic.schema.default_resource_search_schema) def resource_search(context, data_dict): ''' Searches for resources satisfying a given search criteria. It returns a dictionary with 2 fields: ``count`` and ``results``. The ``count`` field contains the total number of Resources found without the limit or query parameters having an effect. The ``results`` field is a list of dictized Resource objects. The 'query' parameter is a required field. It is a string of the form ``{field}:{term}`` or a list of strings, each of the same form. Within each string, ``{field}`` is a field or extra field on the Resource domain object. If ``{field}`` is ``"hash"``, then an attempt is made to match the `{term}` as a *prefix* of the ``Resource.hash`` field. If ``{field}`` is an extra field, then an attempt is made to match against the extra fields stored against the Resource. Note: The search is limited to search against extra fields declared in the config setting ``ckan.extra_resource_fields``. Note: Due to a Resource's extra fields being stored as a json blob, the match is made against the json string representation. As such, false positives may occur: If the search criteria is: :: query = "field1:term1" Then a json blob with the string representation of: :: {"field1": "foo", "field2": "term1"} will match the search criteria! This is a known short-coming of this approach. All matches are made ignoring case; and apart from the ``"hash"`` field, a term matches if it is a substring of the field's value. Finally, when specifying more than one search criteria, the criteria are AND-ed together. The ``order`` parameter is used to control the ordering of the results. Currently only ordering one field is available, and in ascending order only. The ``fields`` parameter is deprecated as it is not compatible with calling this action with a GET request to the action API. The context may contain a flag, `search_query`, which if True will make this action behave as if being used by the internal search api. ie - the results will not be dictized, and SearchErrors are thrown for bad search queries (rather than ValidationErrors). :param query: The search criteria. See above for description. :type query: string or list of strings of the form "{field}:{term1}" :param fields: Deprecated :type fields: dict of fields to search terms. :param order_by: A field on the Resource model that orders the results. :type order_by: string :param offset: Apply an offset to the query. :type offset: int :param limit: Apply a limit to the query. :type limit: int :returns: A dictionary with a ``count`` field, and a ``results`` field. :rtype: dict ''' model = context['model'] # Allow either the `query` or `fields` parameter to be given, but not both. # Once `fields` parameter is dropped, this can be made simpler. # The result of all this gumpf is to populate the local `fields` variable # with mappings from field names to list of search terms, or a single # search-term string. query = data_dict.get('query') fields = data_dict.get('fields') if query is None and fields is None: raise ValidationError({'query': _('Missing value')}) elif query is not None and fields is not None: raise ValidationError( {'fields': _('Do not specify if using "query" parameter')}) elif query is not None: if isinstance(query, basestring): query = [query] try: fields = dict(pair.split(":", 1) for pair in query) except ValueError: raise ValidationError( {'query': _('Must be <field>:<value> pair(s)')}) else: log.warning('Use of the "fields" parameter in resource_search is ' 'deprecated. Use the "query" parameter instead') # The legacy fields paramter splits string terms. # So maintain that behaviour split_terms = {} for field, terms in fields.items(): if isinstance(terms, basestring): terms = terms.split() split_terms[field] = terms fields = split_terms order_by = data_dict.get('order_by') offset = data_dict.get('offset') limit = data_dict.get('limit') q = model.Session.query(model.Resource).join(model.ResourceGroup).join(model.Package) q = q.filter(model.Package.state == 'active') q = q.filter(model.Package.private == False) q = q.filter(model.Resource.state == 'active') resource_fields = model.Resource.get_columns() for field, terms in fields.items(): if isinstance(terms, basestring): terms = [terms] if field not in resource_fields: msg = _('Field "{field}" not recognised in resource_search.')\ .format(field=field) # Running in the context of the internal search api. if context.get('search_query', False): raise search.SearchError(msg) # Otherwise, assume we're in the context of an external api # and need to provide meaningful external error messages. raise ValidationError({'query': msg}) for term in terms: # prevent pattern injection term = misc.escape_sql_like_special_characters(term) model_attr = getattr(model.Resource, field) # Treat the has field separately, see docstring. if field == 'hash': q = q.filter(model_attr.ilike(unicode(term) + '%')) # Resource extras are stored in a json blob. So searching for # matching fields is a bit trickier. See the docstring. elif field in model.Resource.get_extra_columns(): model_attr = getattr(model.Resource, 'extras') like = _or_( model_attr.ilike(u'''%%"%s": "%%%s%%",%%''' % (field, term)), model_attr.ilike(u'''%%"%s": "%%%s%%"}''' % (field, term)) ) q = q.filter(like) # Just a regular field else: q = q.filter(model_attr.ilike('%' + unicode(term) + '%')) if order_by is not None: if hasattr(model.Resource, order_by): q = q.order_by(getattr(model.Resource, order_by)) count = q.count() q = q.offset(offset) q = q.limit(limit) results = [] for result in q: if isinstance(result, tuple) and isinstance(result[0], model.DomainObject): # This is the case for order_by rank due to the add_column. results.append(result[0]) else: results.append(result) # If run in the context of a search query, then don't dictize the results. if not context.get('search_query', False): results = model_dictize.resource_list_dictize(results, context) return {'count': count, 'results': results} def _tag_search(context, data_dict): model = context['model'] terms = data_dict.get('query') or data_dict.get('q') or [] if isinstance(terms, basestring): terms = [terms] terms = [ t.strip() for t in terms if t.strip() ] if 'fields' in data_dict: log.warning('"fields" parameter is deprecated. ' 'Use the "query" parameter instead') fields = data_dict.get('fields', {}) offset = data_dict.get('offset') limit = data_dict.get('limit') # TODO: should we check for user authentication first? q = model.Session.query(model.Tag) if 'vocabulary_id' in data_dict: # Filter by vocabulary. vocab = model.Vocabulary.get(_get_or_bust(data_dict, 'vocabulary_id')) if not vocab: raise NotFound q = q.filter(model.Tag.vocabulary_id == vocab.id) else: # If no vocabulary_name in data dict then show free tags only. q = q.filter(model.Tag.vocabulary_id == None) # If we're searching free tags, limit results to tags that are # currently applied to a package. q = q.distinct().join(model.Tag.package_tags) for field, value in fields.items(): if field in ('tag', 'tags'): terms.append(value) if not len(terms): return [], 0 for term in terms: escaped_term = misc.escape_sql_like_special_characters(term, escape='\\') q = q.filter(model.Tag.name.ilike('%' + escaped_term + '%')) count = q.count() q = q.offset(offset) q = q.limit(limit) return q.all(), count def tag_search(context, data_dict): '''Return a list of tags whose names contain a given string. By default only free tags (tags that don't belong to any vocabulary) are searched. If the ``vocabulary_id`` argument is given then only tags belonging to that vocabulary will be searched instead. :param query: the string(s) to search for :type query: string or list of strings :param vocabulary_id: the id or name of the tag vocabulary to search in (optional) :type vocabulary_id: string :param fields: deprecated :type fields: dictionary :param limit: the maximum number of tags to return :type limit: int :param offset: when ``limit`` is given, the offset to start returning tags from :type offset: int :returns: A dictionary with the following keys: ``'count'`` The number of tags in the result. ``'results'`` The list of tags whose names contain the given string, a list of dictionaries. :rtype: dictionary ''' tags, count = _tag_search(context, data_dict) return {'count': count, 'results': [_table_dictize(tag, context) for tag in tags]} def tag_autocomplete(context, data_dict): '''Return a list of tag names that contain a given string. By default only free tags (tags that don't belong to any vocabulary) are searched. If the ``vocabulary_id`` argument is given then only tags belonging to that vocabulary will be searched instead. :param query: the string to search for :type query: string :param vocabulary_id: the id or name of the tag vocabulary to search in (optional) :type vocabulary_id: string :param fields: deprecated :type fields: dictionary :param limit: the maximum number of tags to return :type limit: int :param offset: when ``limit`` is given, the offset to start returning tags from :type offset: int :rtype: list of strings ''' _check_access('tag_autocomplete', context, data_dict) matching_tags, count = _tag_search(context, data_dict) if matching_tags: return [tag.name for tag in matching_tags] else: return [] def task_status_show(context, data_dict): '''Return a task status. Either the ``id`` parameter *or* the ``entity_id``, ``task_type`` *and* ``key`` parameters must be given. :param id: the id of the task status (optional) :type id: string :param entity_id: the entity_id of the task status (optional) :type entity_id: string :param task_type: the task_type of the task status (optional) :type tast_type: string :param key: the key of the task status (optional) :type key: string :rtype: dictionary ''' model = context['model'] id = data_dict.get('id') if id: task_status = model.TaskStatus.get(id) else: query = model.Session.query(model.TaskStatus)\ .filter(_and_( model.TaskStatus.entity_id == _get_or_bust(data_dict, 'entity_id'), model.TaskStatus.task_type == _get_or_bust(data_dict, 'task_type'), model.TaskStatus.key == _get_or_bust(data_dict, 'key') )) task_status = query.first() context['task_status'] = task_status _check_access('task_status_show', context, data_dict) if task_status is None: raise NotFound task_status_dict = model_dictize.task_status_dictize(task_status, context) return task_status_dict def term_translation_show(context, data_dict): '''Return the translations for the given term(s) and language(s). :param terms: the terms to search for translations of, e.g. ``'Russian'``, ``'romantic novel'`` :type terms: list of strings :param lang_codes: the language codes of the languages to search for translations into, e.g. ``'en'``, ``'de'`` (optional, default is to search for translations into any language) :type lang_codes: list of language code strings :rtype: a list of term translation dictionaries each with keys ``'term'`` (the term searched for, in the source language), ``'term_translation'`` (the translation of the term into the target language) and ``'lang_code'`` (the language code of the target language) ''' model = context['model'] trans_table = model.term_translation_table q = _select([trans_table]) if 'terms' not in data_dict: raise ValidationError({'terms': 'terms not in data'}) # This action accepts `terms` as either a list of strings, or a single # string. terms = _get_or_bust(data_dict, 'terms') if isinstance(terms, basestring): terms = [terms] if terms: q = q.where(trans_table.c.term.in_(terms)) # This action accepts `lang_codes` as either a list of strings, or a single # string. if 'lang_codes' in data_dict: lang_codes = _get_or_bust(data_dict, 'lang_codes') if isinstance(lang_codes, basestring): lang_codes = [lang_codes] q = q.where(trans_table.c.lang_code.in_(lang_codes)) conn = model.Session.connection() cursor = conn.execute(q) results = [] for row in cursor: results.append(_table_dictize(row, context)) return results # Only internal services are allowed to call get_site_user. def get_site_user(context, data_dict): _check_access('get_site_user', context, data_dict) model = context['model'] site_id = config.get('ckan.site_id', 'ckan_site_user') user = model.User.get(site_id) if not user: apikey = str(<KEY>()) user = model.User(name=site_id, password=<PASSWORD>, apikey=apikey) # make sysadmin user.sysadmin = True model.Session.add(user) model.Session.flush() if not context.get('defer_commit'): model.repo.commit_and_remove() return {'name': user.name, 'apikey': user.apikey} def roles_show(context, data_dict): '''Return the roles of all users and authorization groups for an object. :param domain_object: a package or group name or id to filter the results by :type domain_object: string :param user: a user name or id :type user: string :rtype: list of dictionaries ''' model = context['model'] session = context['session'] domain_object_ref = _get_or_bust(data_dict, 'domain_object') user_ref = data_dict.get('user') domain_object = ckan.logic.action.get_domain_object(model, domain_object_ref) if isinstance(domain_object, model.Package): query = session.query(model.PackageRole).join('package') elif isinstance(domain_object, model.Group): query = session.query(model.GroupRole).join('group') elif domain_object is model.System: query = session.query(model.SystemRole) else: raise NotFound(_('Cannot list entity of this type: %s') % type(domain_object).__name__) # Filter by the domain_obj (apart from if it is the system object) if not isinstance(domain_object, type): query = query.filter_by(id=domain_object.id) # Filter by the user if user_ref: user = model.User.get(user_ref) if not user: raise NotFound(_('unknown user:') + repr(user_ref)) query = query.join('user').filter_by(id=user.id) uors = query.all() uors_dictized = [_table_dictize(uor, context) for uor in uors] result = {'domain_object_type': type(domain_object).__name__, 'domain_object_id': domain_object.id if domain_object != model.System else None, 'roles': uors_dictized} if user_ref: result['user'] = user.id return result def status_show(context, data_dict): '''Return a dictionary with information about the site's configuration. :rtype: dictionary ''' return { 'site_title': config.get('ckan.site_title'), 'site_description': config.get('ckan.site_description'), 'site_url': config.get('ckan.site_url'), 'ckan_version': ckan.__version__, 'error_emails_to': config.get('email_to'), 'locale_default': config.get('ckan.locale_default'), 'extensions': config.get('ckan.plugins').split(), } def vocabulary_list(context, data_dict): '''Return a list of all the site's tag vocabularies. :rtype: list of dictionaries ''' model = context['model'] vocabulary_objects = model.Session.query(model.Vocabulary).all() return model_dictize.vocabulary_list_dictize(vocabulary_objects, context) def vocabulary_show(context, data_dict): '''Return a single tag vocabulary. :param id: the id or name of the vocabulary :type id: string :return: the vocabulary. :rtype: dictionary ''' model = context['model'] vocab_id = data_dict.get('id') if not vocab_id: raise ValidationError({'id': _('id not in data')}) vocabulary = model.vocabulary.Vocabulary.get(vocab_id) if vocabulary is None: raise NotFound(_('Could not find vocabulary "%s"') % vocab_id) vocabulary_dict = model_dictize.vocabulary_dictize(vocabulary, context) return vocabulary_dict @logic.validate(logic.schema.default_activity_list_schema) def user_activity_list(context, data_dict): '''Return a user's public activity stream. You must be authorized to view the user's profile. :param id: the id or name of the user :type id: string :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ckan.activity_list_limit setting) :type limit: int :rtype: list of dictionaries ''' # FIXME: Filter out activities whose subject or object the user is not # authorized to read. _check_access('user_show', context, data_dict) model = context['model'] user_ref = data_dict.get('id') # May be user name or id. user = model.User.get(user_ref) if user is None: raise logic.NotFound offset = data_dict.get('offset', 0) limit = int( data_dict.get('limit', config.get('ckan.activity_list_limit', 31))) activity_objects = model.activity.user_activity_list(user.id, limit=limit, offset=offset) return model_dictize.activity_list_dictize(activity_objects, context) @logic.validate(logic.schema.default_activity_list_schema) def package_activity_list(context, data_dict): '''Return a package's activity stream. You must be authorized to view the package. :param id: the id or name of the package :type id: string :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ckan.activity_list_limit setting) :type limit: int :rtype: list of dictionaries ''' # FIXME: Filter out activities whose subject or object the user is not # authorized to read. _check_access('package_show', context, data_dict) model = context['model'] package_ref = data_dict.get('id') # May be name or ID. package = model.Package.get(package_ref) if package is None: raise logic.NotFound offset = int(data_dict.get('offset', 0)) limit = int( data_dict.get('limit', config.get('ckan.activity_list_limit', 31))) activity_objects = model.activity.package_activity_list(package.id, limit=limit, offset=offset) return model_dictize.activity_list_dictize(activity_objects, context) @logic.validate(logic.schema.default_activity_list_schema) def group_activity_list(context, data_dict): '''Return a group's activity stream. You must be authorized to view the group. :param id: the id or name of the group :type id: string :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ckan.activity_list_limit setting) :type limit: int :rtype: list of dictionaries ''' # FIXME: Filter out activities whose subject or object the user is not # authorized to read. _check_access('group_show', context, data_dict) model = context['model'] group_id = data_dict.get('id') offset = data_dict.get('offset', 0) limit = int( data_dict.get('limit', config.get('ckan.activity_list_limit', 31))) # Convert group_id (could be id or name) into id. group_show = logic.get_action('group_show') group_id = group_show(context, {'id': group_id})['id'] activity_objects = model.activity.group_activity_list(group_id, limit=limit, offset=offset) return model_dictize.activity_list_dictize(activity_objects, context) @logic.validate(logic.schema.default_activity_list_schema) def organization_activity_list(context, data_dict): '''Return a organization's activity stream. :param id: the id or name of the organization :type id: string :rtype: list of dictionaries ''' # FIXME: Filter out activities whose subject or object the user is not # authorized to read. _check_access('organization_show', context, data_dict) model = context['model'] org_id = data_dict.get('id') offset = data_dict.get('offset', 0) limit = int( data_dict.get('limit', config.get('ckan.activity_list_limit', 31))) # Convert org_id (could be id or name) into id. org_show = logic.get_action('organization_show') org_id = org_show(context, {'id': org_id})['id'] activity_objects = model.activity.group_activity_list(org_id, limit=limit, offset=offset) return model_dictize.activity_list_dictize(activity_objects, context) @logic.validate(logic.schema.default_pagination_schema) def recently_changed_packages_activity_list(context, data_dict): '''Return the activity stream of all recently added or changed packages. :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ckan.activity_list_limit setting) :type limit: int :rtype: list of dictionaries ''' # FIXME: Filter out activities whose subject or object the user is not # authorized to read. model = context['model'] offset = data_dict.get('offset', 0) limit = int( data_dict.get('limit', config.get('ckan.activity_list_limit', 31))) activity_objects = model.activity.recently_changed_packages_activity_list( limit=limit, offset=offset) return model_dictize.activity_list_dictize(activity_objects, context) def activity_detail_list(context, data_dict): '''Return an activity's list of activity detail items. :param id: the id of the activity :type id: string :rtype: list of dictionaries. ''' # FIXME: Filter out activities whose subject or object the user is not # authorized to read. model = context['model'] activity_id = _get_or_bust(data_dict, 'id') activity_detail_objects = model.ActivityDetail.by_activity_id(activity_id) return model_dictize.activity_detail_list_dictize(activity_detail_objects, context) def user_activity_list_html(context, data_dict): '''Return a user's public activity stream as HTML. The activity stream is rendered as a snippet of HTML meant to be included in an HTML page, i.e. it doesn't have any HTML header or footer. :param id: The id or name of the user. :type id: string :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ckan.activity_list_limit setting) :type limit: int :rtype: string ''' activity_stream = user_activity_list(context, data_dict) offset = int(data_dict.get('offset', 0)) extra_vars = { 'controller': 'user', 'action': 'activity', 'id': data_dict['id'], 'offset': offset, } return activity_streams.activity_list_to_html(context, activity_stream, extra_vars) def package_activity_list_html(context, data_dict): '''Return a package's activity stream as HTML. The activity stream is rendered as a snippet of HTML meant to be included in an HTML page, i.e. it doesn't have any HTML header or footer. :param id: the id or name of the package :type id: string :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ckan.activity_list_limit setting) :type limit: int :rtype: string ''' activity_stream = package_activity_list(context, data_dict) offset = int(data_dict.get('offset', 0)) extra_vars = { 'controller': 'package', 'action': 'activity', 'id': data_dict['id'], 'offset': offset, } return activity_streams.activity_list_to_html(context, activity_stream, extra_vars) def group_activity_list_html(context, data_dict): '''Return a group's activity stream as HTML. The activity stream is rendered as a snippet of HTML meant to be included in an HTML page, i.e. it doesn't have any HTML header or footer. :param id: the id or name of the group :type id: string :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ckan.activity_list_limit setting) :type limit: int :rtype: string ''' activity_stream = group_activity_list(context, data_dict) offset = int(data_dict.get('offset', 0)) extra_vars = { 'controller': 'group', 'action': 'activity', 'id': data_dict['id'], 'offset': offset, } return activity_streams.activity_list_to_html(context, activity_stream, extra_vars) def organization_activity_list_html(context, data_dict): '''Return a organization's activity stream as HTML. The activity stream is rendered as a snippet of HTML meant to be included in an HTML page, i.e. it doesn't have any HTML header or footer. :param id: the id or name of the organization :type id: string :rtype: string ''' activity_stream = organization_activity_list(context, data_dict) offset = int(data_dict.get('offset', 0)) extra_vars = { 'controller': 'organization', 'action': 'activity', 'id': data_dict['id'], 'offset': offset, } return activity_streams.activity_list_to_html(context, activity_stream, extra_vars) def recently_changed_packages_activity_list_html(context, data_dict): '''Return the activity stream of all recently changed packages as HTML. The activity stream includes all recently added or changed packages. It is rendered as a snippet of HTML meant to be included in an HTML page, i.e. it doesn't have any HTML header or footer. :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ckan.activity_list_limit setting) :type limit: int :rtype: string ''' activity_stream = recently_changed_packages_activity_list(context, data_dict) offset = int(data_dict.get('offset', 0)) extra_vars = { 'controller': 'package', 'action': 'activity', 'offset': offset, } return activity_streams.activity_list_to_html(context, activity_stream, extra_vars) def _follower_count(context, data_dict, default_schema, ModelClass): schema = context.get('schema', default_schema) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) return ModelClass.follower_count(data_dict['id']) def user_follower_count(context, data_dict): '''Return the number of followers of a user. :param id: the id or name of the user :type id: string :rtype: int ''' return _follower_count(context, data_dict, ckan.logic.schema.default_follow_user_schema(), context['model'].UserFollowingUser) def dataset_follower_count(context, data_dict): '''Return the number of followers of a dataset. :param id: the id or name of the dataset :type id: string :rtype: int ''' return _follower_count(context, data_dict, ckan.logic.schema.default_follow_dataset_schema(), context['model'].UserFollowingDataset) def group_follower_count(context, data_dict): '''Return the number of followers of a group. :param id: the id or name of the group :type id: string :rtype: int ''' return _follower_count(context, data_dict, ckan.logic.schema.default_follow_group_schema(), context['model'].UserFollowingGroup) def _follower_list(context, data_dict, default_schema, FollowerClass): schema = context.get('schema', default_schema) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) # Get the list of Follower objects. model = context['model'] object_id = data_dict.get('id') followers = FollowerClass.follower_list(object_id) # Convert the list of Follower objects to a list of User objects. users = [model.User.get(follower.follower_id) for follower in followers] users = [user for user in users if user is not None] # Dictize the list of User objects. return model_dictize.user_list_dictize(users, context) def user_follower_list(context, data_dict): '''Return the list of users that are following the given user. :param id: the id or name of the user :type id: string :rtype: list of dictionaries ''' _check_access('user_follower_list', context, data_dict) return _follower_list(context, data_dict, ckan.logic.schema.default_follow_user_schema(), context['model'].UserFollowingUser) def dataset_follower_list(context, data_dict): '''Return the list of users that are following the given dataset. :param id: the id or name of the dataset :type id: string :rtype: list of dictionaries ''' _check_access('dataset_follower_list', context, data_dict) return _follower_list(context, data_dict, ckan.logic.schema.default_follow_dataset_schema(), context['model'].UserFollowingDataset) def group_follower_list(context, data_dict): '''Return the list of users that are following the given group. :param id: the id or name of the group :type id: string :rtype: list of dictionaries ''' _check_access('group_follower_list', context, data_dict) return _follower_list(context, data_dict, ckan.logic.schema.default_follow_group_schema(), context['model'].UserFollowingGroup) def _am_following(context, data_dict, default_schema, FollowerClass): schema = context.get('schema', default_schema) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) if 'user' not in context: raise logic.NotAuthorized model = context['model'] userobj = model.User.get(context['user']) if not userobj: raise logic.NotAuthorized object_id = data_dict.get('id') return FollowerClass.is_following(userobj.id, object_id) def am_following_user(context, data_dict): '''Return ``True`` if you're following the given user, ``False`` if not. :param id: the id or name of the user :type id: string :rtype: boolean ''' return _am_following(context, data_dict, ckan.logic.schema.default_follow_user_schema(), context['model'].UserFollowingUser) def am_following_dataset(context, data_dict): '''Return ``True`` if you're following the given dataset, ``False`` if not. :param id: the id or name of the dataset :type id: string :rtype: boolean ''' return _am_following(context, data_dict, ckan.logic.schema.default_follow_dataset_schema(), context['model'].UserFollowingDataset) def am_following_group(context, data_dict): '''Return ``True`` if you're following the given group, ``False`` if not. :param id: the id or name of the group :type id: string :rtype: boolean ''' return _am_following(context, data_dict, ckan.logic.schema.default_follow_group_schema(), context['model'].UserFollowingGroup) def _followee_count(context, data_dict, FollowerClass): if not context.get('skip_validation'): schema = context.get('schema', ckan.logic.schema.default_follow_user_schema()) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) return FollowerClass.followee_count(data_dict['id']) def followee_count(context, data_dict): '''Return the number of objects that are followed by the given user. Counts all objects, of any type, that the given user is following (e.g. followed users, followed datasets, followed groups). :param id: the id of the user :type id: string :rtype: int ''' model = context['model'] followee_users = _followee_count(context, data_dict, model.UserFollowingUser) # followee_users has validated data_dict so the following functions don't # need to validate it again. context['skip_validation'] = True followee_datasets = _followee_count(context, data_dict, model.UserFollowingDataset) followee_groups = _followee_count(context, data_dict, model.UserFollowingGroup) return sum((followee_users, followee_datasets, followee_groups)) def user_followee_count(context, data_dict): '''Return the number of users that are followed by the given user. :param id: the id of the user :type id: string :rtype: int ''' return _followee_count(context, data_dict, context['model'].UserFollowingUser) def dataset_followee_count(context, data_dict): '''Return the number of datasets that are followed by the given user. :param id: the id of the user :type id: string :rtype: int ''' return _followee_count(context, data_dict, context['model'].UserFollowingDataset) def group_followee_count(context, data_dict): '''Return the number of groups that are followed by the given user. :param id: the id of the user :type id: string :rtype: int ''' return _followee_count(context, data_dict, context['model'].UserFollowingGroup) @logic.validate(logic.schema.default_follow_user_schema) def followee_list(context, data_dict): '''Return the list of objects that are followed by the given user. Returns all objects, of any type, that the given user is following (e.g. followed users, followed datasets, followed groups.. ). :param id: the id of the user :type id: string :param q: a query string to limit results by, only objects whose display name begins with the given string (case-insensitive) wil be returned (optional) :type q: string :rtype: list of dictionaries, each with keys 'type' (e.g. 'user', 'dataset' or 'group'), 'display_name' (e.g. a user's display name, or a package's title) and 'dict' (e.g. a dict representing the followed user, package or group, the same as the dict that would be returned by user_show, package_show or group_show) ''' _check_access('followee_list', context, data_dict) def display_name(followee): '''Return a display name for the given user, group or dataset dict.''' display_name = followee.get('display_name') fullname = followee.get('fullname') title = followee.get('title') name = followee.get('name') return display_name or fullname or title or name # Get the followed objects. # TODO: Catch exceptions raised by these *_followee_list() functions? # FIXME should we be changing the context like this it seems dangerous followee_dicts = [] context['skip_validation'] = True context['ignore_auth'] = True for followee_list_function, followee_type in ( (user_followee_list, 'user'), (dataset_followee_list, 'dataset'), (group_followee_list, 'group')): dicts = followee_list_function(context, data_dict) for d in dicts: followee_dicts.append( {'type': followee_type, 'display_name': display_name(d), 'dict': d}) followee_dicts.sort(key=lambda d: d['display_name']) q = data_dict.get('q') if q: q = q.strip().lower() matching_followee_dicts = [] for followee_dict in followee_dicts: if followee_dict['display_name'].strip().lower().startswith(q): matching_followee_dicts.append(followee_dict) followee_dicts = matching_followee_dicts return followee_dicts def user_followee_list(context, data_dict): '''Return the list of users that are followed by the given user. :param id: the id of the user :type id: string :rtype: list of dictionaries ''' _check_access('user_followee_list', context, data_dict) if not context.get('skip_validation'): schema = context.get('schema') or ( ckan.logic.schema.default_follow_user_schema()) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) # Get the list of Follower objects. model = context['model'] user_id = _get_or_bust(data_dict, 'id') followees = model.UserFollowingUser.followee_list(user_id) # Convert the list of Follower objects to a list of User objects. users = [model.User.get(followee.object_id) for followee in followees] users = [user for user in users if user is not None] # Dictize the list of User objects. return model_dictize.user_list_dictize(users, context) def dataset_followee_list(context, data_dict): '''Return the list of datasets that are followed by the given user. :param id: the id or name of the user :type id: string :rtype: list of dictionaries ''' _check_access('dataset_followee_list', context, data_dict) if not context.get('skip_validation'): schema = context.get('schema') or ( ckan.logic.schema.default_follow_user_schema()) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) # Get the list of Follower objects. model = context['model'] user_id = _get_or_bust(data_dict, 'id') followees = model.UserFollowingDataset.followee_list(user_id) # Convert the list of Follower objects to a list of Package objects. datasets = [model.Package.get(followee.object_id) for followee in followees] datasets = [dataset for dataset in datasets if dataset is not None] # Dictize the list of Package objects. return [model_dictize.package_dictize(dataset, context) for dataset in datasets] def group_followee_list(context, data_dict): '''Return the list of groups that are followed by the given user. :param id: the id or name of the user :type id: string :rtype: list of dictionaries ''' _check_access('group_followee_list', context, data_dict) if not context.get('skip_validation'): schema = context.get('schema', ckan.logic.schema.default_follow_user_schema()) data_dict, errors = _validate(data_dict, schema, context) if errors: raise ValidationError(errors) # Get the list of UserFollowingGroup objects. model = context['model'] user_id = _get_or_bust(data_dict, 'id') followees = model.UserFollowingGroup.followee_list(user_id) # Convert the UserFollowingGroup objects to a list of Group objects. groups = [model.Group.get(followee.object_id) for followee in followees] groups = [group for group in groups if group is not None] # Dictize the list of Group objects. return [model_dictize.group_dictize(group, context) for group in groups] @logic.validate(logic.schema.default_pagination_schema) def dashboard_activity_list(context, data_dict): '''Return the authorized user's dashboard activity stream. Unlike the activity dictionaries returned by other ``*_activity_list`` actions, these activity dictionaries have an extra boolean value with key ``is_new`` that tells you whether the activity happened since the user last viewed her dashboard (``'is_new': True``) or not (``'is_new': False``). The user's own activities are always marked ``'is_new': False``. :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ``ckan.activity_list_limit`` setting) :rtype: list of activity dictionaries ''' _check_access('dashboard_activity_list', context, data_dict) model = context['model'] user_id = model.User.get(context['user']).id offset = data_dict.get('offset', 0) limit = int( data_dict.get('limit', config.get('ckan.activity_list_limit', 31))) # FIXME: Filter out activities whose subject or object the user is not # authorized to read. activity_objects = model.activity.dashboard_activity_list(user_id, limit=limit, offset=offset) activity_dicts = model_dictize.activity_list_dictize( activity_objects, context) # Mark the new (not yet seen by user) activities. strptime = datetime.datetime.strptime fmt = '%Y-%m-%dT%H:%M:%S.%f' last_viewed = model.Dashboard.get(user_id).activity_stream_last_viewed for activity in activity_dicts: if activity['user_id'] == user_id: # Never mark the user's own activities as new. activity['is_new'] = False else: activity['is_new'] = (strptime(activity['timestamp'], fmt) > last_viewed) return activity_dicts @logic.validate(ckan.logic.schema.default_pagination_schema) def dashboard_activity_list_html(context, data_dict): '''Return the authorized user's dashboard activity stream as HTML. The activity stream is rendered as a snippet of HTML meant to be included in an HTML page, i.e. it doesn't have any HTML header or footer. :param id: the id or name of the user :type id: string :param offset: where to start getting activity items from (optional, default: 0) :type offset: int :param limit: the maximum number of activities to return (optional, default: 31, the default value is configurable via the ckan.activity_list_limit setting) :type limit: int :rtype: string ''' activity_stream = dashboard_activity_list(context, data_dict) model = context['model'] offset = data_dict.get('offset', 0) extra_vars = { 'controller': 'user', 'action': 'dashboard', 'offset': offset, } return activity_streams.activity_list_to_html(context, activity_stream, extra_vars) def dashboard_new_activities_count(context, data_dict): '''Return the number of new activities in the user's dashboard. Return the number of new activities in the authorized user's dashboard activity stream. Activities from the user herself are not counted by this function even though they appear in the dashboard (users don't want to be notified about things they did themselves). :rtype: int ''' _check_access('dashboard_new_activities_count', context, data_dict) activities = logic.get_action('dashboard_activity_list')( context, data_dict) return len([activity for activity in activities if activity['is_new']]) def _unpick_search(sort, allowed_fields=None, total=None): ''' This is a helper function that takes a sort string eg 'name asc, last_modified desc' and returns a list of split field order eg [('name', 'asc'), ('last_modified', 'desc')] allowed_fields can limit which field names are ok. total controls how many sorts can be specifed ''' sorts = [] split_sort = sort.split(',') for part in split_sort: split_part = part.strip().split() field = split_part[0] if len(split_part) > 1: order = split_part[1].lower() else: order = 'asc' if allowed_fields: if field not in allowed_fields: raise ValidationError('Cannot sort by field `%s`' % field) if order not in ['asc', 'desc']: raise ValidationError('Invalid sort direction `%s`' % order) sorts.append((field, order)) if total and len(sorts) > total: raise ValidationError( 'Too many sort criteria provided only %s allowed' % total) return sorts def member_roles_list(context, data_dict): '''Return the possible roles for members of groups and organizations. :param group_type: the group type, either "group" or "organization" (optional, default "organization") :type id: string :returns: a list of dictionaries each with two keys: "text" (the display name of the role, e.g. "Admin") and "value" (the internal name of the role, e.g. "admin") :rtype: list of dictionaries ''' group_type = data_dict.get('group_type', 'organization') roles_list = new_authz.roles_list() if group_type == 'group': roles_list = [role for role in roles_list if role['value'] != 'editor'] _check_access('member_roles_list', context, data_dict) return roles_list <file_sep>import logging import routes.mapper import ckan.lib.base as base import ckan.lib.helpers as h import ckan.plugins as p from ckan.lib.plugins import DefaultTranslation import ckan.plugins.toolkit as tk import urllib2 import urllib from ckan.common import _, json import collections from pylons import config import pylons from ckan.common import request, c import ckan.lib.navl as navl import sets import ckan import ckan.lib.jsonp as jsonp import ast log = logging.getLogger(__name__) def convert_dict_to_string(dictionary): return json.dumps(dictionary) def convert_string_to_dict(string): # return ast.literal_eval(string) return json.loads(string) if string else {} # def infograph_data(res,infograph_config): # res_id = res['id'] # axis1 = infograph_config['axis1'] # axis2 = infograph_config['axis2'] # aggregation = infograph_config.get('aggregation','sum') # # sort = infograph_config.get('sort','_id') # # order = infograph_config.get('order','ASC') # query = 'SELECT "'+axis1+'",'+aggregation+'("'+axis2+'") AS "'+axis2+'" FROM "'+res_id+'" WHERE "'+axis2+'" IS NOT NULL' # if infograph_config.get('filter',[]): # for f in infograph_config.get('filter',[]): # query += ' AND (1=0' # for v in f.get('values',[]): # query += ' OR "'+f['column']+'" '+f.get('operator','=')+' \''+v+'\'' # query += ')' # query += ' GROUP BY "'+axis1+'" ORDER BY "'+axis1+'"' # # +' LIMIT 10' # log.debug(query) # url = config.get('ckan.base_url')+'/catalog/api/action/datastore_search_sql?sql='+query.replace(' ','%20') # try: # response = urllib2.urlopen(url) # response_body = response.read() # except urllib2.HTTPError as e: # error_message = json.loads(e.read()) # return error_message # except Exception, inst: # msg = "Couldn't read response from datastore service %r: %s" % (response_body, inst) # raise Exception, inst # try: # datastore = json.loads(response_body) # except Exception, inst: # msg = "Couldn't read response from datastore service %r: %s" % (response_body, inst) # raise Exception, inst # data = [] # for r in datastore["result"]["records"]: # data.append({'axis1':r[axis1],'axis2':float(r[axis2])}) # return data # def comuni(): # response_body = '' # try: # comuni = json.loads(response_body) # except Exception, inst: # msg = "Couldn't read response from comuni service %r: %s" % (response_body, inst) # raise Exception, inst # return comuni # def facets(): # d = collections.OrderedDict() # d['organization'] = _('Organizations') # d['tags'] = _('Tags') # d['res_format'] = _('Formats') # d['license_id'] = _('Licenses') # return d # def translate_resource_data_dict(data_dict): # '''Return the given dict with as many of its fields # as possible translated into the desired or the fallback language. # ''' # try: # desired_lang_code = pylons.request.environ['CKAN_LANG'] # except Exception, e: # desired_lang_code = 'it' # fallback_lang_code = pylons.config.get('ckan.locale_default', 'en') # # Get a flattened copy of data_dict to do the translation on. # flattened = navl.dictization_functions.flatten_dict(data_dict) # # Get a simple flat list of all the terms to be translated, from the # # flattened data dict. # terms = sets.Set() # for (key, value) in flattened.items(): # if value in (None, True, False): # continue # elif isinstance(value, basestring): # terms.add(value) # elif isinstance(value, (int, long)): # continue # else: # for item in value: # terms.add(item) # # Get the translations of all the terms (as a list of dictionaries). # translations = ckan.logic.action.get.term_translation_show( # {'model': ckan.model}, # {'terms': terms, # 'lang_codes': (desired_lang_code, fallback_lang_code)}) # # Transform the translations into a more convenient structure. # desired_translations = {} # fallback_translations = {} # for translation in translations: # if translation['lang_code'] == desired_lang_code: # desired_translations[translation['term']] = ( # translation['term_translation']) # else: # assert translation['lang_code'] == fallback_lang_code # fallback_translations[translation['term']] = ( # translation['term_translation']) # # Make a copy of the flattened data dict with all the terms replaced by # # their translations, where available. # translated_flattened = {} # for (key, value) in flattened.items(): # # Don't translate names that are used for form URLs. # if key == ('name',): # if value in desired_translations: # translated_flattened[key] = desired_translations[value] # elif value in fallback_translations: # translated_flattened[key] = fallback_translations.get(value, value) # else: # translated_flattened[key] = value # elif value in (None, True, False): # # Don't try to translate values that aren't strings. # translated_flattened[key] = value # elif isinstance(value, basestring): # if value in desired_translations: # translated_flattened[key] = desired_translations[value] # else: # translated_flattened[key] = fallback_translations.get( # value, value) # elif isinstance(value, (int, long, dict)): # translated_flattened[key] = value # else: # translated_value = [] # for item in value: # if item in desired_translations: # translated_value.append(desired_translations[item]) # else: # translated_value.append( # fallback_translations.get(item, item) # ) # translated_flattened[key] = translated_value # # Finally unflatten and return the translated data dict. # translated_data_dict = (navl.dictization_functions # .unflatten(translated_flattened)) # return translated_data_dict # def translate_resource_data_dict_list(data_dict_list): # translated = [] # for dict in data_dict_list: # translated.append(translate_resource_data_dict(dict)) # return translated # def translate_related_list(related_list): # translated = [] # for related in related_list: # dict = {'title':related.title, 'description':related.description} # dict_trans = translate_resource_data_dict(dict) # dict_trans['id'] = related.id # dict_trans['type'] = related.type # dict_trans['url'] = related.url # translated.append(dict_trans) # return translated class LaitPlugin(p.SingletonPlugin, DefaultTranslation): p.implements(p.IConfigurer) p.implements(p.IRoutes) p.implements(p.ITemplateHelpers) p.implements(p.IResourceController, inherit=True) p.implements(p.IFacets) p.implements(p.ITranslation) p.implements(p.IPackageController, inherit=True) ## implement IPackageController.before_view def before_view(self, pkg_dict): groups = pkg_dict['groups'] if len(groups)>0: context = {'model': ckan.model, 'session': ckan.model.Session, 'user': c.user, 'for_view': True, 'auth_user_obj': c.userobj, 'use_cache': False} for idx, group in enumerate(groups): data_dict = {'id': group['id']} try: loadedGroup = ckan.logic.get_action('group_show')(context, data_dict) if 'users' in loadedGroup.keys(): del loadedGroup['users'] pkg_dict['groups'][idx] = loadedGroup except: log.info('[before_view] Error loading group: ' + groups[idx]['name']) else: log.info('[before_view] No group for dataset: ' + pkg_dict['name']) return pkg_dict def dataset_facets(self, facets_dict, package_type): for facet_key in facets_dict.keys(): if 'organization_region_' in facet_key: del facets_dict[facet_key] if 'source_catalog_title' in facets_dict.keys(): del facets_dict['source_catalog_title'] return facets_dict def group_facets(self, facets_dict, group_type, package_type): for facet_key in facets_dict.keys(): if 'organization_region_' in facet_key: del facets_dict[facet_key] if 'source_catalog_title' in facets_dict.keys(): del facets_dict['source_catalog_title'] return facets_dict def organization_facets(self, facets_dict, organization_type, package_type): for facet_key in facets_dict.keys(): if 'organization_region_' in facet_key: del facets_dict[facet_key] if 'source_catalog_title' in facets_dict.keys(): del facets_dict['source_catalog_title'] return facets_dict # def before_show(self, data_dict): # translated_data_dict = translate_resource_data_dict(data_dict) # return translated_data_dict def get_helpers(self): return { # 'translate_related_list': translate_related_list, # 'translate_resource_data_dict_list': translate_resource_data_dict_list, # 'comuni': comuni, # 'facets':facets, # 'infograph_data': infograph_data, 'convert_string_to_dict': convert_string_to_dict, 'convert_dict_to_string': convert_dict_to_string} def update_config(self, config): # Add this plugin's templates dir to CKAN's extra_template_paths, so # that CKAN will use this plugin's custom templates. # 'templates' is the path to the templates dir, relative to this # plugin.py file. tk.add_template_directory(config, 'templates') tk.add_public_directory(config, 'public') tk.add_resource('public', 'ckanext-lait') def before_map(self, route_map): with routes.mapper.SubMapper(route_map, controller='ckanext.lait.plugin:LaitController') as m: m.connect('translator_index', '/translator', action='translator') m.connect('geocoding_gazetteer', '/geocoding_gazetteer', action='geocoding_gazetteer') return route_map def after_map(self, route_map): return route_map class LaitController(base.BaseController): def translator(self): context = {'model': ckan.model, 'session': ckan.model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'save': 'save' in request.params} try: ckan.logic.check_access('package_create', context) except ckan.logic.NotAuthorized: base.abort(401, _('Unauthorized to access translator')) return base.render('translator/index.html') @jsonp.jsonpify def geocoding_gazetteer(self): q = request.params.get('q', '') limit = request.params.get('limit', 20) url = config.get('ckan.base_url', '')+'/CKANAPIExtension/geocoding_gazetteer?text='+q.replace(' ', '%20') try: response = urllib2.urlopen(url) response_body = response.read() except Exception, inst: msg = "Couldn't connect to geocoding_gazetteer service %r: %s" % (url, inst) raise Exception, msg try: result= json.loads(response_body) except Exception, inst: msg = "Couldn't read response from geocoding_gazetteerservice %r: %s" % (response_body, inst) raise Exception, inst return result <file_sep># ckanext-lait versione modificata del plugin https://github.com/sciamlab/ckanext-lait <file_sep>from setuptools import setup, find_packages import sys, os version = '0.1.4' setup( name='ckanext-lait', version=version, description="Lait Extension", long_description=''' ''', classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Sciamlab', author_email='<EMAIL>', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages=['ckanext', 'ckanext.lait'], include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- ], entry_points=''' [ckan.plugins] # Add plugins here, e.g. # myplugin=ckanext.lait.plugin:PluginClass lait = ckanext.lait.plugin:LaitPlugin [babel.extractors] ckan = ckan.lib.extract:extract_ckan ''', # TODO: AGGIUNTO message_extractors={ 'ckanext': [ ('**.py', 'python', None), ('**.js', 'javascript', None), ('**/templates/**.html', 'ckan', None), ], } ) <file_sep>import logging from urllib import urlencode import datetime import os import mimetypes import cgi from pylons import config from genshi.template import MarkupTemplate from genshi.template.text import NewTextTemplate from paste.deploy.converters import asbool import paste.fileapp import ckan.logic as logic import ckan.lib.base as base import ckan.lib.maintain as maintain import ckan.lib.package_saver as package_saver import ckan.lib.i18n as i18n import ckan.lib.navl.dictization_functions as dict_fns import ckan.lib.accept as accept import ckan.lib.helpers as h import ckan.model as model import ckan.lib.datapreview as datapreview import ckan.lib.plugins import ckan.lib.uploader as uploader import ckan.plugins as p import ckan.lib.render from ckan.common import OrderedDict, _, json, request, c, g, response from home import CACHE_PARAMETERS log = logging.getLogger(__name__) render = base.render abort = base.abort redirect = base.redirect NotFound = logic.NotFound NotAuthorized = logic.NotAuthorized ValidationError = logic.ValidationError check_access = logic.check_access get_action = logic.get_action tuplize_dict = logic.tuplize_dict clean_dict = logic.clean_dict parse_params = logic.parse_params flatten_to_string_key = logic.flatten_to_string_key lookup_package_plugin = ckan.lib.plugins.lookup_package_plugin def _encode_params(params): return [(k, v.encode('utf-8') if isinstance(v, basestring) else str(v)) for k, v in params] def url_with_params(url, params): params = _encode_params(params) return url + u'?' + urlencode(params) def search_url(params, package_type=None): if not package_type or package_type == 'dataset': url = h.url_for(controller='package', action='search') else: url = h.url_for('{0}_search'.format(package_type)) return url_with_params(url, params) class PackageController(base.BaseController): def _package_form(self, package_type=None): return lookup_package_plugin(package_type).package_form() def _setup_template_variables(self, context, data_dict, package_type=None): return lookup_package_plugin(package_type).\ setup_template_variables(context, data_dict) def _new_template(self, package_type): return lookup_package_plugin(package_type).new_template() def _edit_template(self, package_type): return lookup_package_plugin(package_type).edit_template() def _search_template(self, package_type): return lookup_package_plugin(package_type).search_template() def _read_template(self, package_type): return lookup_package_plugin(package_type).read_template() def _history_template(self, package_type): return lookup_package_plugin(package_type).history_template() def _guess_package_type(self, expecting_name=False): """ Guess the type of package from the URL handling the case where there is a prefix on the URL (such as /data/package) """ # Special case: if the rot URL '/' has been redirected to the package # controller (e.g. by an IRoutes extension) then there's nothing to do # here. if request.path == '/': return 'dataset' parts = [x for x in request.path.split('/') if x] idx = -1 if expecting_name: idx = -2 pt = parts[idx] if pt == 'package': pt = 'dataset' return pt def search(self): from ckan.lib.search import SearchError package_type = self._guess_package_type() try: context = {'model': model, 'user': c.user or c.author, 'auth_user_obj': c.userobj} check_access('site_read', context) except NotAuthorized: abort(401, _('Not authorized to see this page')) # unicode format (decoded from utf8) q = c.q = request.params.get('q', u'') c.query_error = False try: page = int(request.params.get('page', 1)) except ValueError, e: abort(400, ('"page" parameter must be an integer')) limit = g.datasets_per_page # most search operations should reset the page counter: params_nopage = [(k, v) for k, v in request.params.items() if k != 'page'] def drill_down_url(alternative_url=None, **by): return h.add_url_param(alternative_url=alternative_url, controller='package', action='search', new_params=by) c.drill_down_url = drill_down_url def remove_field(key, value=None, replace=None): return h.remove_url_param(key, value=value, replace=replace, controller='package', action='search') c.remove_field = remove_field sort_by = request.params.get('sort', None) params_nosort = [(k, v) for k, v in params_nopage if k != 'sort'] def _sort_by(fields): """ Sort by the given list of fields. Each entry in the list is a 2-tuple: (fieldname, sort_order) eg - [('metadata_modified', 'desc'), ('name', 'asc')] If fields is empty, then the default ordering is used. """ params = params_nosort[:] if fields: sort_string = ', '.join('%s %s' % f for f in fields) params.append(('sort', sort_string)) return search_url(params, package_type) c.sort_by = _sort_by if sort_by is None: c.sort_by_fields = [] else: c.sort_by_fields = [field.split()[0] for field in sort_by.split(',')] def pager_url(q=None, page=None): params = list(params_nopage) params.append(('page', page)) return search_url(params, package_type) c.search_url_params = urlencode(_encode_params(params_nopage)) try: c.fields = [] # c.fields_grouped will contain a dict of params containing # a list of values eg {'tags':['tag1', 'tag2']} c.fields_grouped = {} search_extras = {} fq = '' for (param, value) in request.params.items(): if param not in ['q', 'page', 'sort'] \ and len(value) and not param.startswith('_'): if not param.startswith('ext_'): c.fields.append((param, value)) fq += ' %s:"%s"' % (param, value) if param not in c.fields_grouped: c.fields_grouped[param] = [value] else: c.fields_grouped[param].append(value) else: search_extras[param] = value context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj} if package_type and package_type != 'dataset': # Only show datasets of this particular type fq += ' +dataset_type:{type}'.format(type=package_type) else: # Unless changed via config options, don't show non standard # dataset types on the default search page if not asbool(config.get('ckan.search.show_all_types', 'False')): fq += ' +dataset_type:dataset' facets = OrderedDict() # LAit customization default_facet_titles = { 'organization': _('Organizations'), 'category': _('Categories'), 'rating_average_int': _('Community Rating'), 'tags': _('Tags'), 'res_format': _('Formats'), 'license_id': _('Licenses'), } lait_custom_facets = ['organization','category','rating_average_int','tags','res_format','license_id'] for facet in lait_custom_facets: if facet in default_facet_titles: facets[facet] = default_facet_titles[facet] else: facets[facet] = facet # Facet titles for plugin in p.PluginImplementations(p.IFacets): facets = plugin.dataset_facets(facets, package_type) c.facet_titles = facets data_dict = { 'q': q, 'fq': fq.strip(), 'facet.field': facets.keys(), 'rows': limit, 'start': (page - 1) * limit, 'sort': sort_by, 'extras': search_extras } query = get_action('package_search')(context, data_dict) c.sort_by_selected = query['sort'] c.page = h.Page( collection=query['results'], page=page, url=pager_url, item_count=query['count'], items_per_page=limit ) c.facets = query['facets'] c.search_facets = query['search_facets'] c.page.items = query['results'] except SearchError, se: log.error('Dataset search error: %r', se.args) c.query_error = True c.facets = {} c.search_facets = {} c.page = h.Page(collection=[]) c.search_facets_limits = {} for facet in c.search_facets.keys(): try: limit = int(request.params.get('_%s_limit' % facet, g.facets_default_number)) except ValueError: abort(400, _('Parameter "{parameter_name}" is not ' 'an integer').format( parameter_name='_%s_limit' % facet )) c.search_facets_limits[facet] = limit maintain.deprecate_context_item( 'facets', 'Use `c.search_facets` instead.') self._setup_template_variables(context, {}, package_type=package_type) return render(self._search_template(package_type)) def _content_type_from_extension(self, ext): ct, mu, ext = accept.parse_extension(ext) if not ct: return None, None, None, return ct, ext, (NewTextTemplate, MarkupTemplate)[mu] def _content_type_from_accept(self): """ Given a requested format this method determines the content-type to set and the genshi template loader to use in order to render it accurately. TextTemplate must be used for non-xml templates whilst all that are some sort of XML should use MarkupTemplate. """ ct, mu, ext = accept.parse_header(request.headers.get('Accept', '')) return ct, ext, (NewTextTemplate, MarkupTemplate)[mu] def resources(self, id): package_type = self._get_package_type(id.split('@')[0]) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: check_access('package_update', context, data_dict) except NotAuthorized, e: abort(401, _('User %r not authorized to edit %s') % (c.user, id)) # check if package exists try: c.pkg_dict = get_action('package_show')(context, data_dict) c.pkg = context['package'] except NotFound: abort(404, _('Dataset not found')) except NotAuthorized: abort(401, _('Unauthorized to read package %s') % id) self._setup_template_variables(context, {'id': id}, package_type=package_type) return render('package/resources.html') def read(self, id, format='html'): if not format == 'html': ctype, extension, loader = \ self._content_type_from_extension(format) if not ctype: # An unknown format, we'll carry on in case it is a # revision specifier and re-constitute the original id id = "%s.%s" % (id, format) ctype, format, loader = "text/html; charset=utf-8", "html", \ MarkupTemplate else: ctype, format, loader = self._content_type_from_accept() response.headers['Content-Type'] = ctype package_type = self._get_package_type(id.split('@')[0]) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj} data_dict = {'id': id} # interpret @<revision_id> or @<date> suffix split = id.split('@') if len(split) == 2: data_dict['id'], revision_ref = split if model.is_id(revision_ref): context['revision_id'] = revision_ref else: try: date = h.date_str_to_datetime(revision_ref) context['revision_date'] = date except TypeError, e: abort(400, _('Invalid revision format: %r') % e.args) except ValueError, e: abort(400, _('Invalid revision format: %r') % e.args) elif len(split) > 2: abort(400, _('Invalid revision format: %r') % 'Too many "@" symbols') # check if package exists try: c.pkg_dict = get_action('package_show')(context, data_dict) c.pkg = context['package'] except NotFound: abort(404, _('Dataset not found')) except NotAuthorized: abort(401, _('Unauthorized to read package %s') % id) # used by disqus plugin c.current_package_id = c.pkg.id c.related_count = c.pkg.related_count # can the resources be previewed? for resource in c.pkg_dict['resources']: resource['can_be_previewed'] = self._resource_preview( {'resource': resource, 'package': c.pkg_dict}) self._setup_template_variables(context, {'id': id}, package_type=package_type) package_saver.PackageSaver().render_package(c.pkg_dict, context) template = self._read_template(package_type) template = template[:template.index('.') + 1] + format try: return render(template, loader_class=loader) except ckan.lib.render.TemplateNotFound: msg = _("Viewing {package_type} datasets in {format} format is " "not supported (template file {file} not found).".format( package_type=package_type, format=format, file=template)) abort(404, msg) assert False, "We should never get here" def history(self, id): package_type = self._get_package_type(id.split('@')[0]) if 'diff' in request.params or 'selected1' in request.params: try: params = {'id': request.params.getone('pkg_name'), 'diff': request.params.getone('selected1'), 'oldid': request.params.getone('selected2'), } except KeyError, e: if 'pkg_name' in dict(request.params): id = request.params.getone('pkg_name') c.error = \ _('Select two revisions before doing the comparison.') else: params['diff_entity'] = 'package' h.redirect_to(controller='revision', action='diff', **params) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: c.pkg_dict = get_action('package_show')(context, data_dict) c.pkg_revisions = get_action('package_revision_list')(context, data_dict) # TODO: remove # Still necessary for the authz check in group/layout.html c.pkg = context['package'] except NotAuthorized: abort(401, _('Unauthorized to read package %s') % '') except NotFound: abort(404, _('Dataset not found')) format = request.params.get('format', '') if format == 'atom': # Generate and return Atom 1.0 document. from webhelpers.feedgenerator import Atom1Feed feed = Atom1Feed( title=_(u'CKAN Dataset Revision History'), link=h.url_for(controller='revision', action='read', id=c.pkg_dict['name']), description=_(u'Recent changes to CKAN Dataset: ') + (c.pkg_dict['title'] or ''), language=unicode(i18n.get_lang()), ) for revision_dict in c.pkg_revisions: revision_date = h.date_str_to_datetime( revision_dict['timestamp']) try: dayHorizon = int(request.params.get('days')) except: dayHorizon = 30 dayAge = (datetime.datetime.now() - revision_date).days if dayAge >= dayHorizon: break if revision_dict['message']: item_title = u'%s' % revision_dict['message'].\ split('\n')[0] else: item_title = u'%s' % revision_dict['id'] item_link = h.url_for(controller='revision', action='read', id=revision_dict['id']) item_description = _('Log message: ') item_description += '%s' % (revision_dict['message'] or '') item_author_name = revision_dict['author'] item_pubdate = revision_date feed.add_item( title=item_title, link=item_link, description=item_description, author_name=item_author_name, pubdate=item_pubdate, ) feed.content_type = 'application/atom+xml' return feed.writeString('utf-8') c.related_count = c.pkg.related_count return render(self._history_template(c.pkg_dict.get('type', package_type))) def new(self, data=None, errors=None, error_summary=None): package_type = self._guess_package_type(True) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'save': 'save' in request.params} # Package needs to have a organization group in the call to # check_access and also to save it try: check_access('package_create', context) except NotAuthorized: abort(401, _('Unauthorized to create a package')) if context['save'] and not data: return self._save_new(context, package_type=package_type) data = data or clean_dict(dict_fns.unflatten(tuplize_dict(parse_params( request.params, ignore_keys=CACHE_PARAMETERS)))) c.resources_json = h.json.dumps(data.get('resources', [])) # convert tags if not supplied in data if data and not data.get('tag_string'): data['tag_string'] = ', '.join( h.dict_list_reduce(data.get('tags', {}), 'name')) errors = errors or {} error_summary = error_summary or {} # in the phased add dataset we need to know that # we have already completed stage 1 stage = ['active'] if data.get('state') == 'draft': stage = ['active', 'complete'] elif data.get('state') == 'draft-complete': stage = ['active', 'complete', 'complete'] # if we are creating from a group then this allows the group to be # set automatically data['group_id'] = request.params.get('group') or \ request.params.get('groups__0__id') vars = {'data': data, 'errors': errors, 'error_summary': error_summary, 'action': 'new', 'stage': stage} c.errors_json = h.json.dumps(errors) self._setup_template_variables(context, {}, package_type=package_type) # TODO: This check is to maintain backwards compatibility with the # old way of creating custom forms. This behaviour is now deprecated. if hasattr(self, 'package_form'): c.form = render(self.package_form, extra_vars=vars) else: c.form = render(self._package_form(package_type=package_type), extra_vars=vars) return render(self._new_template(package_type), extra_vars={'stage': stage}) def resource_edit(self, id, resource_id, data=None, errors=None, error_summary=None): if request.method == 'POST' and not data: data = data or clean_dict(dict_fns.unflatten(tuplize_dict(parse_params( request.POST)))) # we don't want to include save as it is part of the form del data['save'] context = {'model': model, 'session': model.Session, 'api_version': 3, 'for_edit': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data['package_id'] = id try: if resource_id: data['id'] = resource_id get_action('resource_update')(context, data) else: get_action('resource_create')(context, data) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.resource_edit(id, resource_id, data, errors, error_summary) except NotAuthorized: abort(401, _('Unauthorized to edit this resource')) redirect(h.url_for(controller='package', action='resource_read', id=id, resource_id=resource_id)) context = {'model': model, 'session': model.Session, 'api_version': 3, 'for_edit': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} pkg_dict = get_action('package_show')(context, {'id': id}) if pkg_dict['state'].startswith('draft'): # dataset has not yet been fully created resource_dict = get_action('resource_show')(context, {'id': resource_id}) fields = ['url', 'resource_type', 'format', 'name', 'description', 'id'] data = {} for field in fields: data[field] = resource_dict[field] return self.new_resource(id, data=data) # resource is fully created try: resource_dict = get_action('resource_show')(context, {'id': resource_id}) except NotFound: abort(404, _('Resource not found')) c.pkg_dict = pkg_dict c.resource = resource_dict # set the form action c.form_action = h.url_for(controller='package', action='resource_edit', resource_id=resource_id, id=id) if not data: data = resource_dict errors = errors or {} error_summary = error_summary or {} vars = {'data': data, 'errors': errors, 'error_summary': error_summary, 'action': 'new'} return render('package/resource_edit.html', extra_vars=vars) def new_resource(self, id, data=None, errors=None, error_summary=None): ''' FIXME: This is a temporary action to allow styling of the forms. ''' if request.method == 'POST' and not data: save_action = request.params.get('save') data = data or clean_dict(dict_fns.unflatten(tuplize_dict(parse_params( request.POST)))) # we don't want to include save as it is part of the form del data['save'] resource_id = data['id'] del data['id'] context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} # see if we have any data that we are trying to save data_provided = False for key, value in data.iteritems(): if ((value or isinstance(value, cgi.FieldStorage)) and key != 'resource_type'): data_provided = True break if not data_provided and save_action != "go-dataset-complete": if save_action == 'go-dataset': # go to final stage of adddataset redirect(h.url_for(controller='package', action='edit', id=id)) # see if we have added any resources try: data_dict = get_action('package_show')(context, {'id': id}) except NotAuthorized: abort(401, _('Unauthorized to update dataset')) except NotFound: abort(404, _('The dataset {id} could not be found.').format(id=id)) if not len(data_dict['resources']): # no data so keep on page msg = _('You must add at least one data resource') # On new templates do not use flash message if g.legacy_templates: h.flash_error(msg) redirect(h.url_for(controller='package', action='new_resource', id=id)) else: errors = {} error_summary = {_('Error'): msg} return self.new_resource(id, data, errors, error_summary) # we have a resource so let them add metadata redirect(h.url_for(controller='package', action='new_metadata', id=id)) data['package_id'] = id try: if resource_id: data['id'] = resource_id get_action('resource_update')(context, data) else: get_action('resource_create')(context, data) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.new_resource(id, data, errors, error_summary) except NotAuthorized: abort(401, _('Unauthorized to create a resource')) except NotFound: abort(404, _('The dataset {id} could not be found.').format(id=id)) if save_action == 'go-metadata': # go to final stage of add dataset redirect(h.url_for(controller='package', action='new_metadata', id=id)) elif save_action == 'go-dataset': # go to first stage of add dataset redirect(h.url_for(controller='package', action='edit', id=id)) elif save_action == 'go-dataset-complete': # go to first stage of add dataset redirect(h.url_for(controller='package', action='read', id=id)) else: # add more resources redirect(h.url_for(controller='package', action='new_resource', id=id)) errors = errors or {} error_summary = error_summary or {} vars = {'data': data, 'errors': errors, 'error_summary': error_summary, 'action': 'new'} vars['pkg_name'] = id # get resources for sidebar context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} try: pkg_dict = get_action('package_show')(context, {'id': id}) except NotFound: abort(404, _('The dataset {id} could not be found.').format(id=id)) # required for nav menu vars['pkg_dict'] = pkg_dict template = 'package/new_resource_not_draft.html' if pkg_dict['state'] == 'draft': vars['stage'] = ['complete', 'active'] template = 'package/new_resource.html' elif pkg_dict['state'] == 'draft-complete': vars['stage'] = ['complete', 'active', 'complete'] template = 'package/new_resource.html' return render(template, extra_vars=vars) def new_metadata(self, id, data=None, errors=None, error_summary=None): ''' FIXME: This is a temporary action to allow styling of the forms. ''' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} if request.method == 'POST' and not data: save_action = request.params.get('save') data = data or clean_dict(dict_fns.unflatten(tuplize_dict(parse_params( request.POST)))) # we don't want to include save as it is part of the form del data['save'] data_dict = get_action('package_show')(context, {'id': id}) data_dict['id'] = id # update the state if save_action == 'finish': # we want this to go live when saved data_dict['state'] = 'active' elif save_action in ['go-resources', 'go-dataset']: data_dict['state'] = 'draft-complete' # allow the state to be changed context['allow_state_change'] = True data_dict.update(data) try: get_action('package_update')(context, data_dict) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.new_metadata(id, data, errors, error_summary) except NotAuthorized: abort(401, _('Unauthorized to update dataset')) if save_action == 'go-resources': # we want to go back to the add resources form stage redirect(h.url_for(controller='package', action='new_resource', id=id)) elif save_action == 'go-dataset': # we want to go back to the add dataset stage redirect(h.url_for(controller='package', action='edit', id=id)) redirect(h.url_for(controller='package', action='read', id=id)) if not data: data = get_action('package_show')(context, {'id': id}) errors = errors or {} error_summary = error_summary or {} vars = {'data': data, 'errors': errors, 'error_summary': error_summary} vars['pkg_name'] = id package_type = self._get_package_type(id) self._setup_template_variables(context, {}, package_type=package_type) return render('package/new_package_metadata.html', extra_vars=vars) def edit(self, id, data=None, errors=None, error_summary=None): package_type = self._get_package_type(id) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'save': 'save' in request.params, 'moderated': config.get('moderated'), 'pending': True} if context['save'] and not data: return self._save_edit(id, context, package_type=package_type) try: c.pkg_dict = get_action('package_show')(context, {'id': id}) context['for_edit'] = True old_data = get_action('package_show')(context, {'id': id}) # old data is from the database and data is passed from the # user if there is a validation error. Use users data if there. if data: old_data.update(data) data = old_data except NotAuthorized: abort(401, _('Unauthorized to read package %s') % '') except NotFound: abort(404, _('Dataset not found')) # are we doing a multiphase add? if data.get('state', '').startswith('draft'): c.form_action = h.url_for(controller='package', action='new') c.form_style = 'new' return self.new(data=data, errors=errors, error_summary=error_summary) c.pkg = context.get("package") c.resources_json = h.json.dumps(data.get('resources', [])) try: check_access('package_update', context) except NotAuthorized, e: abort(401, _('User %r not authorized to edit %s') % (c.user, id)) # convert tags if not supplied in data if data and not data.get('tag_string'): data['tag_string'] = ', '.join(h.dict_list_reduce( c.pkg_dict.get('tags', {}), 'name')) errors = errors or {} vars = {'data': data, 'errors': errors, 'error_summary': error_summary, 'action': 'edit'} c.errors_json = h.json.dumps(errors) self._setup_template_variables(context, {'id': id}, package_type=package_type) c.related_count = c.pkg.related_count # we have already completed stage 1 vars['stage'] = ['active'] if data.get('state') == 'draft': vars['stage'] = ['active', 'complete'] elif data.get('state') == 'draft-complete': vars['stage'] = ['active', 'complete', 'complete'] # TODO: This check is to maintain backwards compatibility with the # old way of creating custom forms. This behaviour is now deprecated. if hasattr(self, 'package_form'): c.form = render(self.package_form, extra_vars=vars) else: c.form = render(self._package_form(package_type=package_type), extra_vars=vars) return render(self._edit_template(package_type), extra_vars={'stage': vars['stage']}) def read_ajax(self, id, revision=None): package_type = self._get_package_type(id) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'revision_id': revision} try: data = get_action('package_show')(context, {'id': id}) except NotAuthorized: abort(401, _('Unauthorized to read package %s') % '') except NotFound: abort(404, _('Dataset not found')) data.pop('tags') data = flatten_to_string_key(data) response.headers['Content-Type'] = 'application/json;charset=utf-8' return h.json.dumps(data) def history_ajax(self, id): context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: pkg_revisions = get_action('package_revision_list')( context, data_dict) except NotAuthorized: abort(401, _('Unauthorized to read package %s') % '') except NotFound: abort(404, _('Dataset not found')) data = [] approved = False for num, revision in enumerate(pkg_revisions): if not approved and revision['approved_timestamp']: current_approved, approved = True, True else: current_approved = False data.append({'revision_id': revision['id'], 'message': revision['message'], 'timestamp': revision['timestamp'], 'author': revision['author'], 'approved': bool(revision['approved_timestamp']), 'current_approved': current_approved}) response.headers['Content-Type'] = 'application/json;charset=utf-8' return h.json.dumps(data) def _get_package_type(self, id): """ Given the id of a package it determines the plugin to load based on the package's type name (type). The plugin found will be returned, or None if there is no plugin associated with the type. """ pkg = model.Package.get(id) if pkg: return pkg.type or 'dataset' return None def _tag_string_to_list(self, tag_string): ''' This is used to change tags from a sting to a list of dicts ''' out = [] for tag in tag_string.split(','): tag = tag.strip() if tag: out.append({'name': tag, 'state': 'active'}) return out def _save_new(self, context, package_type=None): # The staged add dataset used the new functionality when the dataset is # partially created so we need to know if we actually are updating or # this is a real new. is_an_update = False ckan_phase = request.params.get('_ckan_phase') from ckan.lib.search import SearchIndexError try: data_dict = clean_dict(dict_fns.unflatten( tuplize_dict(parse_params(request.POST)))) if ckan_phase: # prevent clearing of groups etc context['allow_partial_update'] = True # sort the tags data_dict['tags'] = self._tag_string_to_list( data_dict['tag_string']) if data_dict.get('pkg_name'): is_an_update = True # This is actually an update not a save data_dict['id'] = data_dict['pkg_name'] del data_dict['pkg_name'] # this is actually an edit not a save pkg_dict = get_action('package_update')(context, data_dict) if request.params['save'] == 'go-metadata': # redirect to add metadata url = h.url_for(controller='package', action='new_metadata', id=pkg_dict['name']) else: # redirect to add dataset resources url = h.url_for(controller='package', action='new_resource', id=pkg_dict['name']) redirect(url) # Make sure we don't index this dataset if request.params['save'] not in ['go-resource', 'go-metadata']: data_dict['state'] = 'draft' # allow the state to be changed context['allow_state_change'] = True data_dict['type'] = package_type context['message'] = data_dict.get('log_message', '') pkg_dict = get_action('package_create')(context, data_dict) if ckan_phase: # redirect to add dataset resources url = h.url_for(controller='package', action='new_resource', id=pkg_dict['name']) redirect(url) self._form_save_redirect(pkg_dict['name'], 'new', package_type=package_type) except NotAuthorized: abort(401, _('Unauthorized to read package %s') % '') except NotFound, e: abort(404, _('Dataset not found')) except dict_fns.DataError: abort(400, _(u'Integrity Error')) except SearchIndexError, e: try: exc_str = unicode(repr(e.args)) except Exception: # We don't like bare excepts exc_str = unicode(str(e)) abort(500, _(u'Unable to add package to search index.') + exc_str) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary if is_an_update: # we need to get the state of the dataset to show the stage we # are on. pkg_dict = get_action('package_show')(context, data_dict) data_dict['state'] = pkg_dict['state'] return self.edit(data_dict['id'], data_dict, errors, error_summary) data_dict['state'] = 'none' return self.new(data_dict, errors, error_summary) def _save_edit(self, name_or_id, context, package_type=None): from ckan.lib.search import SearchIndexError log.debug('Package save request name: %s POST: %r', name_or_id, request.POST) try: data_dict = clean_dict(dict_fns.unflatten( tuplize_dict(parse_params(request.POST)))) if '_ckan_phase' in data_dict: # we allow partial updates to not destroy existing resources context['allow_partial_update'] = True data_dict['tags'] = self._tag_string_to_list( data_dict['tag_string']) del data_dict['_ckan_phase'] del data_dict['save'] context['message'] = data_dict.get('log_message', '') if not context['moderated']: context['pending'] = False data_dict['id'] = name_or_id pkg = get_action('package_update')(context, data_dict) if request.params.get('save', '') == 'Approve': get_action('make_latest_pending_package_active')( context, data_dict) c.pkg = context['package'] c.pkg_dict = pkg self._form_save_redirect(pkg['name'], 'edit', package_type=package_type) except NotAuthorized: abort(401, _('Unauthorized to read package %s') % id) except NotFound, e: abort(404, _('Dataset not found')) except dict_fns.DataError: abort(400, _(u'Integrity Error')) except SearchIndexError, e: try: exc_str = unicode(repr(e.args)) except Exception: # We don't like bare excepts exc_str = unicode(str(e)) abort(500, _(u'Unable to update search index.') + exc_str) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.edit(name_or_id, data_dict, errors, error_summary) def _form_save_redirect(self, pkgname, action, package_type=None): '''This redirects the user to the CKAN package/read page, unless there is request parameter giving an alternate location, perhaps an external website. @param pkgname - Name of the package just edited @param action - What the action of the edit was ''' assert action in ('new', 'edit') url = request.params.get('return_to') or \ config.get('package_%s_return_url' % action) if url: url = url.replace('<NAME>', pkgname) else: if package_type is None or package_type == 'dataset': url = h.url_for(controller='package', action='read', id=pkgname) else: url = h.url_for('{0}_read'.format(package_type), id=pkgname) redirect(url) def _adjust_license_id_options(self, pkg, fs): options = fs.license_id.render_opts['options'] is_included = False for option in options: license_id = option[1] if license_id == pkg.license_id: is_included = True if not is_included: options.insert(1, (pkg.license_id, pkg.license_id)) def delete(self, id): if 'cancel' in request.params: h.redirect_to(controller='package', action='edit', id=id) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} try: check_access('package_delete', context, {'id': id}) except NotAuthorized: abort(401, _('Unauthorized to delete package %s') % '') try: if request.method == 'POST': get_action('package_delete')(context, {'id': id}) h.flash_notice(_('Dataset has been deleted.')) h.redirect_to(controller='package', action='search') c.pkg_dict = get_action('package_show')(context, {'id': id}) except NotAuthorized: abort(401, _('Unauthorized to delete package %s') % '') except NotFound: abort(404, _('Dataset not found')) return render('package/confirm_delete.html') def resource_delete(self, id, resource_id): if 'cancel' in request.params: h.redirect_to(controller='package', action='resource_edit', resource_id=resource_id, id=id) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} try: check_access('package_delete', context, {'id': id}) except NotAuthorized: abort(401, _('Unauthorized to delete package %s') % '') try: if request.method == 'POST': get_action('resource_delete')(context, {'id': resource_id}) h.flash_notice(_('Resource has been deleted.')) h.redirect_to(controller='package', action='read', id=id) c.resource_dict = get_action('resource_show')(context, {'id': resource_id}) c.pkg_id = id except NotAuthorized: abort(401, _('Unauthorized to delete resource %s') % '') except NotFound: abort(404, _('Resource not found')) return render('package/confirm_delete_resource.html') def autocomplete(self): # DEPRECATED in favour of /api/2/util/dataset/autocomplete q = unicode(request.params.get('q', '')) if not len(q): return '' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'q': q} packages = get_action('package_autocomplete')(context, data_dict) pkg_list = [] for pkg in packages: pkg_list.append('%s|%s' % (pkg['match_displayed']. replace('|', ' '), pkg['name'])) return '\n'.join(pkg_list) def _render_edit_form(self, fs, params={}, clear_session=False): # errors arrive in c.error and fs.errors c.log_message = params.get('log_message', '') # rgrp: expunge everything from session before dealing with # validation errors) so we don't have any problematic saves # when the fs.render causes a flush. # seb: If the session is *expunged*, then the form can't be # rendered; I've settled with a rollback for now, which isn't # necessarily what's wanted here. # dread: I think this only happened with tags because until # this changeset, Tag objects were created in the Renderer # every time you hit preview. So I don't believe we need to # clear the session any more. Just in case I'm leaving it in # with the log comments to find out. if clear_session: # log to see if clearing the session is ever required if model.Session.new or model.Session.dirty or \ model.Session.deleted: log.warn('Expunging session changes which were not expected: ' '%r %r %r', (model.Session.new, model.Session.dirty, model.Session.deleted)) try: model.Session.rollback() except AttributeError: # older SQLAlchemy versions model.Session.clear() edit_form_html = fs.render() c.form = h.literal(edit_form_html) return h.literal(render('package/edit_form.html')) def _update_authz(self, fs): validation = fs.validate() if not validation: c.form = self._render_edit_form(fs, request.params) raise package_saver.ValidationException(fs) try: fs.sync() except Exception, inst: model.Session.rollback() raise else: model.Session.commit() def resource_read(self, id, resource_id): context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, "for_view":True} try: c.resource = get_action('resource_show')(context, {'id': resource_id}) c.package = get_action('package_show')(context, {'id': id}) # required for nav menu c.pkg = context['package'] c.pkg_dict = c.package except NotFound: abort(404, _('Resource not found')) except NotAuthorized: abort(401, _('Unauthorized to read resource %s') % id) # get package license info license_id = c.package.get('license_id') try: c.package['isopen'] = model.Package.\ get_license_register()[license_id].isopen() except KeyError: c.package['isopen'] = False # TODO: find a nicer way of doing this c.datastore_api = '%s/api/action' % config.get('ckan.site_url', '').rstrip('/') c.related_count = c.pkg.related_count c.resource['can_be_previewed'] = self._resource_preview( {'resource': c.resource, 'package': c.package}) return render('package/resource_read.html') def _resource_preview(self, data_dict): return bool(datapreview.res_format(data_dict['resource']) in datapreview.direct() + datapreview.loadable() or datapreview.get_preview_plugin( data_dict, return_first=True)) def resource_download(self, id, resource_id, filename=None): """ Provides a direct download by either redirecting the user to the url stored or downloading an uploaded file directly. """ context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} try: rsc = get_action('resource_show')(context, {'id': resource_id}) pkg = get_action('package_show')(context, {'id': id}) except NotFound: abort(404, _('Resource not found')) except NotAuthorized: abort(401, _('Unauthorized to read resource %s') % id) if rsc.get('url_type') == 'upload': upload = uploader.ResourceUpload(rsc) filepath = upload.get_path(rsc['id']) fileapp = paste.fileapp.FileApp(filepath) try: status, headers, app_iter = request.call_application(fileapp) except OSError: abort(404, _('Resource data not found')) response.headers.update(dict(headers)) content_type, content_enc = mimetypes.guess_type(rsc.get('url','')) response.headers['Content-Type'] = content_type response.status = status return app_iter elif not 'url' in rsc: abort(404, _('No download is available')) redirect(rsc['url']) def follow(self, id): '''Start following this dataset.''' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: get_action('follow_dataset')(context, data_dict) package_dict = get_action('package_show')(context, data_dict) h.flash_success(_("You are now following {0}").format( package_dict['title'])) except ValidationError as e: error_message = (e.extra_msg or e.message or e.error_summary or e.error_dict) h.flash_error(error_message) except NotAuthorized as e: h.flash_error(e.extra_msg) h.redirect_to(controller='package', action='read', id=id) def unfollow(self, id): '''Stop following this dataset.''' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: get_action('unfollow_dataset')(context, data_dict) package_dict = get_action('package_show')(context, data_dict) h.flash_success(_("You are no longer following {0}").format( package_dict['title'])) except ValidationError as e: error_message = (e.extra_msg or e.message or e.error_summary or e.error_dict) h.flash_error(error_message) except (NotFound, NotAuthorized) as e: error_message = e.extra_msg or e.message h.flash_error(error_message) h.redirect_to(controller='package', action='read', id=id) def followers(self, id=None): context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: c.pkg_dict = get_action('package_show')(context, data_dict) c.pkg = context['package'] c.followers = get_action('dataset_follower_list')(context, {'id': c.pkg_dict['id']}) c.related_count = c.pkg.related_count except NotFound: abort(404, _('Dataset not found')) except NotAuthorized: abort(401, _('Unauthorized to read package %s') % id) return render('package/followers.html') def groups(self, id): context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj, 'use_cache': False} data_dict = {'id': id} try: c.pkg_dict = get_action('package_show')(context, data_dict) except NotFound: abort(404, _('Dataset not found')) except NotAuthorized: abort(401, _('Unauthorized to read dataset %s') % id) if request.method == 'POST': new_group = request.POST.get('group_added') if new_group: data_dict = {"id": new_group, "object": id, "object_type": 'package', "capacity": 'public'} try: get_action('member_create')(context, data_dict) except NotFound: abort(404, _('Group not found')) removed_group = None for param in request.POST: if param.startswith('group_remove'): removed_group = param.split('.')[-1] break if removed_group: data_dict = {"id": removed_group, "object": id, "object_type": 'package'} try: get_action('member_delete')(context, data_dict) except NotFound: abort(404, _('Group not found')) redirect(h.url_for(controller='package', action='groups', id=id)) context['is_member'] = True users_groups = get_action('group_list_authz')(context, data_dict) pkg_group_ids = set(group['id'] for group in c.pkg_dict.get('groups', [])) user_group_ids = set(group['id'] for group in users_groups) c.group_dropdown = [[group['id'], group['display_name']] for group in users_groups if group['id'] not in pkg_group_ids] for group in c.pkg_dict.get('groups', []): group['user_member'] = (group['id'] in user_group_ids) return render('package/group_list.html') def activity(self, id): '''Render this package's public activity stream page.''' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: c.pkg_dict = get_action('package_show')(context, data_dict) c.pkg = context['package'] c.package_activity_stream = get_action( 'package_activity_list_html')(context, {'id': c.pkg_dict['id']}) c.related_count = c.pkg.related_count except NotFound: abort(404, _('Dataset not found')) except NotAuthorized: abort(401, _('Unauthorized to read dataset %s') % id) return render('package/activity.html') def resource_embedded_dataviewer(self, id, resource_id, width=500, height=500): """ Embeded page for a read-only resource dataview. Allows for width and height to be specified as part of the querystring (as well as accepting them via routes). """ context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} try: c.resource = get_action('resource_show')(context, {'id': resource_id}) c.package = get_action('package_show')(context, {'id': id}) c.resource_json = h.json.dumps(c.resource) # double check that the resource belongs to the specified package if not c.resource['id'] in [r['id'] for r in c.package['resources']]: raise NotFound except NotFound: abort(404, _('Resource not found')) except NotAuthorized: abort(401, _('Unauthorized to read resource %s') % id) # Construct the recline state state_version = int(request.params.get('state_version', '1')) recline_state = self._parse_recline_state(request.params) if recline_state is None: abort(400, ('"state" parameter must be a valid recline ' 'state (version %d)' % state_version)) c.recline_state = h.json.dumps(recline_state) c.width = max(int(request.params.get('width', width)), 100) c.height = max(int(request.params.get('height', height)), 100) c.embedded = True return render('package/resource_embedded_dataviewer.html') def _parse_recline_state(self, params): state_version = int(request.params.get('state_version', '1')) if state_version != 1: return None recline_state = {} for k, v in request.params.items(): try: v = h.json.loads(v) except ValueError: pass recline_state[k] = v recline_state.pop('width', None) recline_state.pop('height', None) recline_state['readOnly'] = True # previous versions of recline setup used elasticsearch_url attribute # for data api url - see http://trac.ckan.org/ticket/2639 # fix by relocating this to url attribute which is the default location if 'dataset' in recline_state and 'elasticsearch_url' in recline_state['dataset']: recline_state['dataset']['url'] = recline_state['dataset']['elasticsearch_url'] # Ensure only the currentView is available # default to grid view if none specified if not recline_state.get('currentView', None): recline_state['currentView'] = 'grid' for k in recline_state.keys(): if k.startswith('view-') and \ not k.endswith(recline_state['currentView']): recline_state.pop(k) return recline_state def resource_datapreview(self, id, resource_id): ''' Embeded page for a resource data-preview. Depending on the type, different previews are loaded. This could be an img tag where the image is loaded directly or an iframe that embeds a webpage, recline or a pdf preview. ''' context = { 'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj } try: c.resource = get_action('resource_show')(context, {'id': resource_id}) c.package = get_action('package_show')(context, {'id': id}) data_dict = {'resource': c.resource, 'package': c.package} preview_plugin = datapreview.get_preview_plugin(data_dict) if preview_plugin is None: abort(409, _('No preview has been defined.')) preview_plugin.setup_template_variables(context, data_dict) c.resource_json = json.dumps(c.resource) except NotFound: abort(404, _('Resource not found')) except NotAuthorized: abort(401, _('Unauthorized to read resource %s') % id) else: return render(preview_plugin.preview_template(context, data_dict))<file_sep>var host = ''; var ckan4j_webapi_endpoint = host + '/CKANAPIExtension/translate/term/'; var page_size = 25; var page_current; var page_last; var terms_count; var lang_code_current = 'en'; var lang_code_main = 'it'; var langs = { "it":{ "display_it":"Italiano" },"en":{ "display_it":"Inglese" } }; function onLoad(){ document.getElementById("mainLang").innerHTML = langs[lang_code_main]["display_"+lang_code_main]; document.getElementById("translatedLang").innerHTML = langs[lang_code_current]["display_"+lang_code_main]; search(); } function enter(e){ if(e.charCode == 13 && !$('#translateModal').hasClass('in')) search(); } function search(){ var term = document.getElementById("term"); term.innerHTML = ""; term.style.color = "grey"; document.getElementById("term-translation").value = ""; page_current = 1; populateTable(); } function changePage(page_num){ page_current = page_num; populateTable(); } function updatePagination(){ var ul = document.createElement('ul'); ul.setAttribute("class", "pagination"); var div = document.getElementById("pagination"); var old_ul = div.getElementsByTagName('ul')[0]; div.replaceChild(ul, old_ul); //first ul.appendChild(createPaginationElement(1, '&laquo;')); //prev var page_prev = page_current; if(page_current>1) page_prev--; ul.appendChild(createPaginationElement(page_prev, '&#60;')); //numbers for(var i = 1; i <= page_last; i++) { var li = createPaginationElement(i, i+''); if(i==page_current) li.setAttribute("class","active"); ul.appendChild(li); } //next var page_next = page_current; if(page_current<page_last) page_next++; ul.appendChild(createPaginationElement(page_next, '&#62;')); //last ul.appendChild(createPaginationElement(page_last, '&raquo;')); } function createPaginationElement(page, label){ var li = document.createElement('li'); var a = document.createElement('a'); a.setAttribute("onclick","changePage("+page+");"); a.innerHTML = label; li.appendChild(a); return li; } function populateTable() { var include_not_translated = document.getElementById("search-not-translated").checked; var include_translated = document.getElementById("search-translated").checked; var query_filter = document.getElementById("search-filter").value; //update terms and pages count var service = 'count'; //getting current count (filtered) doAjax('GET', ckan4j_webapi_endpoint, service, 'e=category&l='+lang_code_current+'&tr='+include_translated+'&ntr='+include_not_translated+'&q='+query_filter, null, true, function(result){ // alert(result); var json = eval('(' + result + ')'); terms_count = json.count; document.getElementById("terms-count").innerHTML = terms_count; document.getElementById("terms-count-box").style.display = 'block'; var additional_page = 0; if(terms_count%page_size>1) additional_page = 1; page_last = (Math.floor(terms_count/page_size))+additional_page; updatePagination(); } ); //getting total count var total_terms_count; doAjax('GET', ckan4j_webapi_endpoint, service, 'e=category&l='+lang_code_current+'&tr=true&ntr=true&q=', null, false, function(result){ // alert(result); var json = eval('(' + result + ')'); total_terms_count = json.count; } ); //getting translated count var translated_terms_count; doAjax('GET', ckan4j_webapi_endpoint, service, 'e=category&l='+lang_code_current+'&tr=true&ntr=false&q=', null, false, function(result){ // alert(result); var json = eval('(' + result + ')'); translated_terms_count = json.count; } ); var translation_percentage = translated_terms_count/total_terms_count*100; document.getElementById("terms-stats-translated").innerHTML = translated_terms_count; document.getElementById("terms-stats-total").innerHTML = total_terms_count; document.getElementById("terms-stats-percentage").innerHTML = translation_percentage.toFixed(2); document.getElementById("terms-stats-box").style.display = 'block'; //update table content service = 'list'; doAjax('GET', ckan4j_webapi_endpoint, service, 'e=category&pn='+page_current+'&ps='+page_size+'&l='+lang_code_current+'&tr='+include_translated+'&ntr='+include_not_translated+'&q='+query_filter, null, true, function(result){ // alert(result); var json = eval('(' + result + ')'); var tbody = document.createElement('tbody'); var table = document.getElementById("main-table"); var old_tbody = table.getElementsByTagName('tbody')[0]; table.replaceChild(tbody, old_tbody); window.scrollTo(0, 0); for (var i = 0; i < json.length; i++) { var row = tbody.insertRow(i); row.setAttribute('data-toggle','modal'); row.setAttribute('data-id',i); row.setAttribute('data-target','#translateModal'); var cell0 = row.insertCell(0); var cell1 = row.insertCell(1); var cell2 = row.insertCell(2); cell0.innerHTML = i+1+((page_current-1)*page_size); cell0.setAttribute("style","text-align:center;"); cell1.innerHTML = json[i].term; if(json[i].term_translation) cell2.innerHTML = json[i].term_translation; else cell2.innerHTML = ''; row.onclick = (function() { return function() { document.getElementById("row-num").innerHTML = this.cells[0].innerHTML-1-((page_current-1)*page_size); document.getElementById("term").innerHTML = this.cells[1].innerHTML; document.getElementById("term").style.color = 'black'; document.getElementById("term-translation").value = this.cells[2].innerHTML; }; })(i); }; } ); } function insertTranslation(){ var row_num = document.getElementById("row-num").innerHTML; var term = document.getElementById("term").innerHTML; var term_translation = document.getElementById("term-translation").value; var data = {}; data['term'] = term; data['term_translation'] = term_translation; data['lang_code'] = lang_code_current; var service = 'insert'; doAjax('POST', ckan4j_webapi_endpoint, service, '', JSON.stringify(data), true, function(result){ // alert(result); var json = eval('(' + result + ')'); var message_box = document.getElementById("message-box"); var message; if(json.success){ var tbody = document.getElementById("main-table").getElementsByTagName('tbody')[0]; var row = tbody.rows[row_num]; row.cells[2].innerHTML = json.term_translation; message = "<div id='message' class='alert alert-success alert-dismissible' role='alert'>" + "<button type='button' class='close' data-dismiss='alert'>&times;</button>" + "<b>"+document.getElementById("msg-ok").innerHTML+"</b>" + "</div>"; window.setTimeout(function() { $('#translateModal').modal('hide'); message_box.innerHTML = ""; }, 2000); }else{ var msg = document.getElementById("msg-ko").innerHTML; if(json.msg) msg += ": "+json.msg; message = "<div id='message' class='alert alert-danger alert-dismissible' role='alert'>" + "<button type='button' class='close' data-dismiss='alert'>&times;</button>" + "<b>" + msg + "</b></div>"; } message_box.innerHTML = message; } ); } function doAjax(method, host, service, query, data, asynch, callback){ var requestObj = false; if (window.XMLHttpRequest) { requestObj = new XMLHttpRequest(); } else if (window.ActiveXObject) { requestObj = new ActiveXObject("Microsoft.XMLHTTP"); } if (requestObj) { requestObj.onreadystatechange = function (){ try { if (requestObj.readyState == 4 && requestObj.status == 200){ var result = requestObj.responseText; if(callback) callback(result); } }catch(err){ //alert(err); }finally{ } }; requestObj.open(method, host+service+'?'+query, asynch); requestObj.setRequestHeader("Content-type","application/json"); requestObj.setRequestHeader("Authorization",document.getElementById("api-key").innerHTML); requestObj.send(data); } } <file_sep>/* Module for handling the spatial querying */ var current_lang = parent.document.getElementById("current-lang").innerHTML; this.ckan.module('spatial-query', function ($, _) { return { options: { i18n: { draw_rectangle_label: 'Draw rectangle', draw_rectangle_label_it: 'Disegna rettangolo' }, style: { color: '#F06F64', weight: 2, opacity: 1, fillColor: '#F06F64', fillOpacity: 0.1 }, default_extent: [[90, 180], [-90, -180]] }, template: { buttons: [ '<div id="dataset-map-edit-buttons">', '<a href="javascript:;" class="btn cancel">Cancel</a> ', '<a id="reset-button" href="" class="btn cancel">Reset</a>', '<a href="javascript:;" class="btn apply disabled">Apply</a>', '</div>' ].join('') }, template_it: { buttons: [ '<div id="dataset-map-edit-buttons">', '<a href="javascript:;" class="btn cancel">Cancella</a> ', '<a id="reset-button" href="" class="btn cancel">Resetta</a>', '<a href="javascript:;" class="btn apply disabled">Applica</a>', '</div>' ].join('') }, initialize: function () { if(current_lang=='it'){ this.template = this.template_it; this.options.i18n.draw_rectangle_label = this.options.i18n.draw_rectangle_label_it; } var module = this; $.proxyAll(this, /_on/); L.Icon.Default.imagePath = this.options.site_url + 'js/vendor/leaflet/images'; var user_default_extent = this.el.data('default_extent'); if (user_default_extent ){ if (user_default_extent instanceof Array) { // Assume it's a pair of coords like [[90, 180], [-90, -180]] this.options.default_extent = user_default_extent; } else if (user_default_extent instanceof Object) { // Assume it's a GeoJSON bbox this.options.default_extent = new L.GeoJSON(user_default_extent).getBounds(); } } this.el.ready(this._onReady); }, _getParameterByName: function (name) { var match = RegExp('[?&]' + name + '=([^&]*)') .exec(window.location.search); return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null; }, _drawExtentFromCoords: function(xmin, ymin, xmax, ymax) { if ($.isArray(xmin)) { var coords = xmin; xmin = coords[0]; ymin = coords[1]; xmax = coords[2]; ymax = coords[3]; } return new L.Rectangle([[ymin, xmin], [ymax, xmax]], this.options.style); }, _drawExtentFromGeoJSON: function(geom) { return new L.GeoJSON(geom, {style: this.options.style}); }, _onReady: function() { var module = this; var map; var extentLayer; var previous_box; var previous_extent; var is_exanded = false; var should_zoom = true; var form = $("#dataset-search"); var ricerca = $("#field-geometric-search"); var markersLayer = new L.FeatureGroup(); // CKAN 2.1 if (!form.length) { form = $(".search-form"); } var buttons; // Add necessary fields to the search form if not already created $(['ext_bbox', 'ext_prev_extent']).each(function(index, item){ if ($("#" + item).length === 0) { $('<input type="hidden" />').attr({'id': item, 'name': item}).appendTo(form); } }); // OK map time map = ckan.commonLeafletMap('dataset-map-container', this.options.map_config, {attributionControl: false}); // Initialize the draw control map.addControl(new L.Control.Draw({ position: 'topright', polyline: false, polygon: false, circle: false, marker: false, rectangle: { shapeOptions: module.options.style, title: this.options.i18n.draw_rectangle_label } })); map.addLayer(markersLayer); //Imposta gli eventi sul geocoder ricerca.on("select2-selecting", function(e){ var coordinates = e.val.split(" "); markersLayer.clearLayers(); L.marker([coordinates[0], coordinates[1]]).addTo(markersLayer).bindPopup(e.object.text).openPopup(); map.fitBounds([[coordinates[0], coordinates[1]],[coordinates[0], coordinates[1]]]); map.zoomOut(4); e.object.id=""; }); // OK add the expander $('.leaflet-control-draw a', module.el).on('click', function(e) { if (!is_exanded) { $('body').addClass('dataset-map-expanded'); if (should_zoom && !extentLayer) { map.zoomIn(); } resetMap(); is_exanded = true; $(".geometric-search").show(); //$("#clear-geometric-search").show(); } }); // Setup the expanded buttons buttons = $(module.template.buttons).insertBefore('#dataset-map-attribution'); document.getElementById('reset-button').href=document.getElementById('reset-href').innerHTML; // Handle the cancel expanded action $('.cancel', buttons).on('click', function() { $(".geometric-search").hide(); //$("#clear-geometric-search").hide(); $('body').removeClass('dataset-map-expanded'); if (extentLayer) { map.removeLayer(extentLayer); } setPreviousExtent(); setPreviousBBBox(); resetMap(); is_exanded = false; }); // Handle the apply expanded action $('.apply', buttons).on('click', function() { if (extentLayer) { $(".geometric-search").hide(); //$("#clear-geometric-search").hide(); $('body').removeClass('dataset-map-expanded'); is_exanded = false; resetMap(); // Eugh, hacky hack. setTimeout(function() { map.fitBounds(extentLayer.getBounds()); submitForm(); }, 200); } }); // When user finishes drawing the box, record it and add it to the map map.on('draw:rectangle-created', function (e) { if (extentLayer) { map.removeLayer(extentLayer); } extentLayer = e.rect; $('#ext_bbox').val(extentLayer.getBounds().toBBoxString()); map.addLayer(extentLayer); $('.apply', buttons).removeClass('disabled').addClass('btn-primary'); }); // Record the current map view so we can replicate it after submitting map.on('moveend', function(e) { $('#ext_prev_extent').val(map.getBounds().toBBoxString()); }); // Ok setup the default state for the map var previous_bbox; setPreviousBBBox(); setPreviousExtent(); // OK, when we expand we shouldn't zoom then map.on('zoomstart', function(e) { should_zoom = false; }); // Is there an existing box from a previous search? function setPreviousBBBox() { previous_bbox = module._getParameterByName('ext_bbox'); if (previous_bbox) { $('#ext_bbox').val(previous_bbox); extentLayer = module._drawExtentFromCoords(previous_bbox.split(',')) map.addLayer(extentLayer); map.fitBounds(extentLayer.getBounds()); } } // Is there an existing extent from a previous search? function setPreviousExtent() { previous_extent = module._getParameterByName('ext_prev_extent'); if (previous_extent) { coords = previous_extent.split(','); map.fitBounds([[coords[1], coords[0]], [coords[3], coords[2]]]); } else { if (!previous_bbox){ map.fitBounds(module.options.default_extent); } } } // Reset map view function resetMap() { L.Util.requestAnimFrame(map.invalidateSize, map, !1, map._container); } // Add the loading class and submit the form function submitForm() { setTimeout(function() { form.submit(); }, 800); } var QueryString = function () { // This function is anonymous, is executed immediately and // the return value is assigned to QueryString! var query_string = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); // If first entry with this name if (typeof query_string[pair[0]] === "undefined") { query_string[pair[0]] = pair[1]; // If second entry with this name } else if (typeof query_string[pair[0]] === "string") { var arr = [ query_string[pair[0]], pair[1] ]; query_string[pair[0]] = arr; // If third or later entry with this name } else { query_string[pair[0]].push(pair[1]); } } return query_string; } (); // Simulating click on expand button if(QueryString._exp=='true') $('.leaflet-control-draw a', module.el).click(); } } });<file_sep>{% extends "page.html" %} {% block subtitle %}{% endblock %} {% block breadcrumb_content %}{% endblock %} {% block primary_content %} <script type="text/javascript"> window.location.href = "/"; </script> {% endblock %} {% block secondary_content %} {% endblock %} <file_sep>import mimetypes from logging import getLogger from ckan import plugins as p log = getLogger(__name__) class WMSPreview(p.SingletonPlugin): p.implements(p.IConfigurer, inherit=True) p.implements(p.IResourcePreview, inherit=True) WMS = ['wms'] def update_config(self, config): p.toolkit.add_public_directory(config, 'public') p.toolkit.add_template_directory(config, 'templates') p.toolkit.add_resource('public', 'ckanext-spatial') self.proxy_enabled = p.toolkit.asbool(config.get('ckan.resource_proxy_enabled', 'False')) def setup_template_variables(self, context, data_dict): import ckanext.resourceproxy.plugin as proxy if self.proxy_enabled and not data_dict['resource']['on_same_domain']: p.toolkit.c.resource['proxy_url'] = proxy.get_proxified_resource_url(data_dict) else: p.toolkit.c.resource['proxy_url'] = data_dict['resource']['url'] def can_preview(self, data_dict): format_lower = data_dict['resource']['format'].lower() correct_format = format_lower in self.WMS can_preview_from_domain = self.proxy_enabled or data_dict['resource']['on_same_domain'] quality = 2 if p.toolkit.check_ckan_version('2.1'): if correct_format: if can_preview_from_domain: return {'can_preview': True, 'quality': quality} else: return {'can_preview': False, 'fixable': 'Enable resource_proxy', 'quality': quality} else: return {'can_preview': False, 'quality': quality} return correct_format and can_preview_from_domain def preview_template(self, context, data_dict): return 'dataviewer/wms_lait.html' class GeoJSONPreview(p.SingletonPlugin): p.implements(p.IConfigurer, inherit=True) p.implements(p.IResourcePreview, inherit=True) p.implements(p.ITemplateHelpers, inherit=True) GeoJSON = ['gjson', 'geojson'] def update_config(self, config): ''' Set up the resource library, public directory and template directory for the preview ''' p.toolkit.add_public_directory(config, 'public') p.toolkit.add_template_directory(config, 'templates') p.toolkit.add_resource('public', 'ckanext-spatial') self.proxy_enabled = config.get( 'ckan.resource_proxy_enabled', False) mimetypes.add_type('application/json', '.geojson') def can_preview(self, data_dict): format_lower = data_dict['resource']['format'].lower() correct_format = format_lower in self.GeoJSON can_preview_from_domain = self.proxy_enabled or data_dict['resource']['on_same_domain'] quality = 2 if p.toolkit.check_ckan_version('2.1'): if correct_format: if can_preview_from_domain: return {'can_preview': True, 'quality': quality} else: return {'can_preview': False, 'fixable': 'Enable resource_proxy', 'quality': quality} else: return {'can_preview': False, 'quality': quality} return correct_format and can_preview_from_domain def setup_template_variables(self, context, data_dict): import ckanext.resourceproxy.plugin as proxy if (self.proxy_enabled and not data_dict['resource']['on_same_domain']): p.toolkit.c.resource['original_url'] = p.toolkit.c.resource['url'] p.toolkit.c.resource['url'] = proxy.get_proxified_resource_url( data_dict) def preview_template(self, context, data_dict): return 'dataviewer/geojson_lait.html' ## ITemplateHelpers def get_helpers(self): from ckanext.spatial import helpers as spatial_helpers # CKAN does not allow to define two helpers with the same name # As this plugin can be loaded independently of the main spatial one # We define a different helper pointing to the same function return { 'get_common_map_config_geojson' : spatial_helpers.get_common_map_config, } <file_sep>d3.timeFormatDefaultLocale({ "decimal": ",", "thousands": ".", "grouping": [3], "currency": ["€", ""], "dateTime": "%a %b %e %X %Y", "date": "%d.%m.%Y", "time": "%H:%M:%S", "periods": ["AM", "PM"], "days": ["Domenica", "Lunedi", "Martedi", "Mercoledi", "Giovedi", "Venerdi", "Sabato"], "shortDays": ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"], "months": ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"], "shortMonths": ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"] }); moment.locale('it'); var infograph_config = JSON.parse(document.getElementById('infograph_config').getAttribute('data')); // console.log('infograph_config', infograph_config); // infograph_config.graph_type = 'bar'; console.log('graph_type:',infograph_config.graph_type); console.log('axis1:',infograph_config.axis1); console.log('axis2:',infograph_config.axis2); var infograph_data = JSON.parse(document.getElementById('infograph_data').getAttribute('data')); console.log('infograph_data', infograph_data); var sum = d3.sum(infograph_data.map(function(d) { return d.axis2; })); var margin = {top: 20, right: 20, bottom: 30, left: 80}; var tooltip = d3.select("body").append("div").attr("class", "toolTip"); var tooltip_show = function(d){ if(d.data) d = d.data; tooltip .style("left", d3.event.pageX - 50 + "px") .style("top", d3.event.pageY - 90 + "px") .style("display", "inline-block") .html("<strong>" + infograph_config.axis1 + ": </strong>" + d.axis1 + "<br><strong>" + infograph_config.axis2 + ": </strong>" + d.axis2.toLocaleString('it') + (infograph_config.graph_type=='pie' ? " (" + (Math.round((d.axis2/sum*100) * 100) / 100) + "%)" : "") ); }; var tooltip_hide = function(d){ tooltip .style("display", "none"); }; var hide_label_percentage = infograph_config.hide_label_percentage ? infograph_config.hide_label_percentage : 0.00; var aggregation_percentage = infograph_config.aggregation_percentage ? infograph_config.aggregation_percentage : 0.00; function aggregate(data){ var aggregated = []; var other = {axis1: "Altro", axis2: 0} infograph_data.map(function(d) { if(d.axis2/sum<aggregation_percentage){ // aggregation other.axis2+=d.axis2; }else{ aggregated.push(d); } }); if(other.axis2!=0) aggregated.push(other); return aggregated; } if(infograph_config.graph_type=='pie'){ /* * PIE CHART */ var svg_pie = d3.select("svg.pie_chart"); var pie_margin = 200; if(infograph_config.margin) pie_margin+=infograph_config.margin; var width_pie = +svg_pie.attr("width") - pie_margin; // - margin.left - margin.right; var height_pie = +svg_pie.attr("height") - pie_margin; // - margin.top - margin.bottom; var radius = Math.min(width_pie, height_pie) / 2; var r = (Math.min(width_pie, height_pie) - 50) / 2; var pie_data = aggregate(infograph_data); var g_pie = svg_pie.append("g") .attr("transform", "translate(" + ((width_pie/2) + (pie_margin/2)) + "," + ((height_pie/2) + (pie_margin/2)) + ")"); var pie = d3.pie().sort(null).value(function(d) { return d.axis2; }); var path = d3.arc() .outerRadius(radius - 10) .innerRadius(0); var outerArc = d3.arc() .innerRadius(radius * 0.9) .outerRadius(radius * 0.9); var arc = d3.arc() .outerRadius(r - 12) .innerRadius(2); var labelArc = d3.arc() .outerRadius(r + 20) .innerRadius(r-5); var label_margin = -100; if(infograph_config.label_margin) label_margin+=infograph_config.label_margin; var label = d3.arc() .outerRadius(radius -40)//+ label_margin) .innerRadius(radius -40)//+ label_margin); var arc = g_pie.selectAll(".arc") .data(pie(pie_data)) .enter().append("g") .attr("class", "arc") .on("mousemove", tooltip_show) .on("mouseout", tooltip_hide); var gradient = jsgradient.generateGradient( infograph_config.gradient_start ? infograph_config.gradient_start : '#002742', infograph_config.gradient_end ? infograph_config.gradient_end : '#a3a3a3', pie_data.length); var color = d3.scaleOrdinal(gradient) .domain(pie_data.map(function(d) { return d.axis1+"_"+d.axis2; })); arc.append("path") .attr("d", path) .attr("fill", function(d) { console.log(color(d.data.axis1+"_"+d.data.axis2)); return color(d.data.axis1+"_"+d.data.axis2); }); function midAngle(d) { return d.startAngle + (d.endAngle - d.startAngle) / 2; } arc.append("text") // .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; }) // .attr("dy", "0.35em") .style('fill', function(d){ return d.data.axis2/sum<hide_label_percentage ? "none" : "black"; }) .text(function(d) { return d.data.axis1; }) .attr("transform", function(d,i){ var pos = outerArc.centroid(d); pos[0] = radius * 1.1 * (midAngle(d) < Math.PI ? 1 : -1); return "translate("+ pos +")"; }) .attr("text-anchor", function(d){ return midAngle(d) < Math.PI ? 'start' : 'end'; }) .attr("dy", 5 ); var polyline = g_pie.selectAll("polyline") .data(pie(pie_data), function(d) { return d.data.currency; }) .enter() .append("polyline") .attr("points", function(d,i) { var pos = outerArc.centroid(d); pos[0] = radius * 1.05 * (midAngle(d) < Math.PI ? 1 : -1); var o = outerArc.centroid(d); //return [label.centroid(d),[o[0],0[1]] , pos]; return [label.centroid(d),[o[0],pos[1]] , pos]; }) .style("fill", "none") .attr('stroke', function(d){ return d.data.axis2/sum<hide_label_percentage ? "none" : "black"; }) .style("stroke-width", "2px"); } else if(infograph_config.graph_type=='line'){ /* * LINE CHART */ var svg_line = d3.select("svg.line_chart"); var width_line = +svg_line.attr("width") - margin.left - margin.right; var height_line = +svg_line.attr("height") - margin.top - margin.bottom; var g_line = svg_line.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // var x_line = d3.scaleBand() // .rangeRound([0, width_line]) // .padding(1); var x_line = d3.scaleTime() .rangeRound([0, width_line]); var y_line = d3.scaleLinear() .rangeRound([height_line, 0]); var line = d3.line() .x(function(d) { return x_line(d.axis1); }) .y(function(d) { return y_line(d.axis2); }) var parseTime = d3.timeParse("%Y-%m-%dT%H:%M:%S"); // var parseTime = d3.timeParse("%d-%m-%Y"); var line_data = infograph_data.map(function(d) { //console.log(d.axis1.replace(/\//g, "-"), d.axis1.replace(/\//g, "-"), d.axis1.replace(/\//g, "-"), d.axis1.replace(/\//g, "-")) return { 'axis1': parseTime(moment(d.axis1).tz("Europe/Rome").format("YYYY-MM-DDTHH:mm:ss")), // 'axis1': parseTime(moment(d.axis1.replace(/\//g, "-")).tz("Europe/Rome").format("DD-MM-YYYY")), 'axis2': d.axis2 }; }) x_line.domain(d3.extent(line_data, function(d) { return d.axis1; })); y_line.domain(d3.extent(line_data, function(d) { return d.axis2; })); g_line.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height_line + ")") .call(d3.axisBottom(x_line) // .tickFormat(d3.timeFormatLocale(locale_it).timeFormat("%Y-%m-%d")) ) // .select(".domain") // .remove() ; g_line.append("g") .attr("class", "axis axis--y") .call(d3.axisLeft(y_line)) .append("text") .attr("fill", "#000") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "end") .text(infograph_config.axis2) ; g_line.append("path") .attr("class", "line") .datum(line_data) .attr("d", line); var focus = g_line.append("g") .attr("class", "focus") .style("display", "none"); focus.append("line") .attr("class", "x-hover-line hover-line") .attr("y1", 0) .attr("y2", height_line); focus.append("line") .attr("class", "y-hover-line hover-line") .attr("x1", width_line) .attr("x2", width_line); focus.append("circle") .attr("r", 3); // focus.append("text") // .attr("x", 15) // .attr("dy", ".31em"); svg_line.append("rect") .attr("transform", "translate(" + margin.left + "," + margin.top + ")") .attr("class", "overlay") .attr("width", width_line) .attr("height", height_line) .on("mouseover", function() { focus.style("display", null); }) .on("mouseout", function() { focus.style("display", "none"); }) .on("mousemove", mousemove); var bisectDate = d3.bisector(function(d) { return d.axis1; }).left; function mousemove() { var x0 = x_line.invert(d3.mouse(this)[0]), i = bisectDate(line_data, x0, 1), d0 = line_data[i - 1], d1 = line_data[i], d = x0 - d0.axis1 > d1.axis1 - x0 ? d1 : d0; focus.attr("transform", "translate(" + x_line(d.axis1) + "," + y_line(d.axis2) + ")"); // focus.select("text").text(function() { return d.axis2; }); focus.select(".x-hover-line").attr("y2", height_line - y_line(d.axis2)); focus.select(".y-hover-line").attr("x2", width_line + width_line); tooltip_show({ 'axis1': moment(d.axis1).tz("Europe/Rome").format("D MMM YYYY, HH:mm:ss"), 'axis2': d.axis2 }); } }else if(infograph_config.graph_type=='bar'){ /* * BAR CHART */ if(infograph_config.axis1_margin) margin.bottom+=infograph_config.axis1_margin; var svg_bar = d3.select("svg.bar_chart"); var width_bar = +svg_bar.attr("width") - margin.left - margin.right; var height_bar = +svg_bar.attr("height") - margin.top - margin.bottom; var x_bar = d3.scaleBand() .rangeRound([0, width_bar]) .padding(0.1); var y_bar = d3.scaleLinear() .rangeRound([height_bar, 0]); var g_bar = svg_bar.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // var bar_data = aggregate(infograph_data); var bar_data = infograph_data; x_bar.domain(bar_data.map(function(d) { return d.axis1; })); var bar_data_max = d3.max(bar_data.map(function(d) { return d.axis2; })); y_bar.domain([0, bar_data_max]); g_bar.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height_bar + ")") .call(d3.axisBottom(x_bar)); if(infograph_config.axis1_orientation && infograph_config.axis1_orientation=="vertical"){ g_bar.selectAll("g text") .attr("y", 0) .attr("x", 9) .attr("dy", "0.35em") .attr("transform", "rotate(90)") .style("text-anchor", "start"); } g_bar.append("g") .attr("class", "axis axis--y") .call(d3.axisLeft(y_bar)) .append("text") .attr("fill", "#000") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "end") .text(infograph_config.axis2) ; g_bar.selectAll(".bar") .data(bar_data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x_bar(d.axis1); }) .attr("y", function(d) { return y_bar(d.axis2); }) .attr("width", x_bar.bandwidth()) .attr("height", function(d) { return height_bar - y_bar(d.axis2); }) .on("mousemove", tooltip_show) .on("mouseout", tooltip_hide); } // $(document).ready(function() {}); /* // Set-up the export button var svg = d3.select("svg"); console.log("svg",svg); d3.select("#svg-download").on("click", function (){ var svgString = getSVGString(svg.node()); console.log("svgString",svgString); svgString2Image( svgString, 2*svg.attr("width"), 2*svg.attr("height"), 'png', save ); // passes Blob and filesize String to the callback function save( dataBlob, filesize ){ saveAs( dataBlob, 'D3 vis exported to PNG.png' ); // FileSaver.js function } }); // Below are the functions that handle actual exporting: // getSVGString ( svgNode ) and svgString2Image( svgString, width, height, format, callback ) function getSVGString( svgNode ) { svgNode.setAttribute('xlink', 'http://www.w3.org/1999/xlink'); var cssStyleText = getCSSStyles( svgNode ); appendCSS( cssStyleText, svgNode ); var serializer = new XMLSerializer(); var svgString = serializer.serializeToString(svgNode); svgString = svgString.replace(/(\w+)?:?xlink=/g, 'xmlns:xlink='); // Fix root xlink without namespace svgString = svgString.replace(/NS\d+:href/g, 'xlink:href'); // Safari NS namespace fix return svgString; function getCSSStyles( parentElement ) { var selectorTextArr = []; // Add Parent element Id and Classes to the list selectorTextArr.push( '#'+parentElement.id ); for (var c = 0; c < parentElement.classList.length; c++) if ( !contains('.'+parentElement.classList[c], selectorTextArr) ) selectorTextArr.push( '.'+parentElement.classList[c] ); // Add Children element Ids and Classes to the list var nodes = parentElement.getElementsByTagName("*"); for (var i = 0; i < nodes.length; i++) { var id = nodes[i].id; if ( !contains('#'+id, selectorTextArr) ) selectorTextArr.push( '#'+id ); var classes = nodes[i].classList; for (var c = 0; c < classes.length; c++) if ( !contains('.'+classes[c], selectorTextArr) ) selectorTextArr.push( '.'+classes[c] ); } // Extract CSS Rules var extractedCSSText = ""; for (var i = 0; i < document.styleSheets.length; i++) { var s = document.styleSheets[i]; try { if(!s.cssRules) continue; } catch( e ) { if(e.name !== 'SecurityError') throw e; // for Firefox continue; } var cssRules = s.cssRules; for (var r = 0; r < cssRules.length; r++) { if ( contains( cssRules[r].selectorText, selectorTextArr ) ) extractedCSSText += cssRules[r].cssText; } } return extractedCSSText; function contains(str,arr) { return arr.indexOf( str ) === -1 ? false : true; } } function appendCSS( cssText, element ) { var styleElement = document.createElement("style"); styleElement.setAttribute("type","text/css"); styleElement.innerHTML = cssText; var refNode = element.hasChildNodes() ? element.children[0] : null; element.insertBefore( styleElement, refNode ); } } function svgString2Image( svgString, width, height, format, callback ) { var format = format ? format : 'png'; var imgsrc = 'data:image/svg+xml;base64,'+ btoa( unescape( encodeURIComponent( svgString ) ) ); // Convert SVG string to data URL var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); canvas.width = width; canvas.height = height; var image = new Image(); image.onload = function() { context.clearRect ( 0, 0, width, height ); context.drawImage(image, 0, 0, width, height); canvas.toBlob( function(blob) { var filesize = Math.round( blob.length/1024 ) + ' KB'; if ( callback ) callback( blob, filesize ); }); }; image.src = imgsrc; } */ <file_sep>{% ckan_extends %} {% block extras %} {% if pkg_dict.category %} <tr> <th scope="row" class="dataset-label">{{ _("Category") }}</th> <td class="dataset-details">{{ pkg_dict.category }}</td> </tr> {% endif %} {% endblock %} <file_sep>$(document).ready(function() { $('.dropbtn').click(function (event) { event.preventDefault(); var dropDown = $(event.currentTarget).next('.dropdown-content'); var isOpen = false; if ($(dropDown).hasClass('show')) { isOpen = true; } closeDropDowns(); if (!isOpen) { $(dropDown).toggleClass('show') $(event.currentTarget).find('.caret-custom').toggleClass("caret-up"); } }); window.onclick = function(event) { if (!event.target.matches('.dropbtn') && !event.target.matches('.caret-custom')) { closeDropDowns(); } } function closeDropDowns() { var dropdowns = $(".dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); $('.caret-custom').removeClass("caret-up"); } } } });<file_sep>from logging import getLogger import ckan.plugins as p import ckan.plugins.toolkit as toolkit log = getLogger(__name__) class ReclinePreview(p.SingletonPlugin): """This extension previews resources using recline This extension implements two interfaces - ``IConfigurer`` allows to modify the configuration - ``IResourcePreview`` allows to add previews """ p.implements(p.IConfigurer, inherit=True) p.implements(p.IResourcePreview, inherit=True) def update_config(self, config): ''' Set up the resource library, public directory and template directory for the preview ''' toolkit.add_public_directory(config, 'theme/public') toolkit.add_template_directory(config, 'theme/templates') toolkit.add_resource('theme/public', 'ckanext-reclinepreview') def can_preview(self, data_dict): # if the resource is in the datastore then we can preview it with recline if data_dict['resource'].get('datastore_active'): return True format_lower = data_dict['resource']['format'].lower() return format_lower in ['csv', 'xls', 'tsv'] def preview_template(self, context, data_dict): return 'recline_lait.html' <file_sep>'''A collection of interfaces that CKAN plugins can implement to customize and extend CKAN. ''' __all__ = [ 'Interface', 'IGenshiStreamFilter', 'IRoutes', 'IMapper', 'ISession', 'IMiddleware', 'IAuthFunctions', 'IDomainObjectModification', 'IGroupController', 'IOrganizationController', 'IPackageController', 'IPluginObserver', 'IConfigurable', 'IConfigurer', 'IActions', 'IResourceUrlChange', 'IDatasetForm', 'IResourcePreview', 'IResourceController', 'IGroupForm', 'ITagController', 'ITemplateHelpers', 'IFacets', 'IAuthenticator', ] from inspect import isclass from pyutilib.component.core import Interface as _pca_Interface class Interface(_pca_Interface): @classmethod def provided_by(cls, instance): return cls.implemented_by(instance.__class__) @classmethod def implemented_by(cls, other): if not isclass(other): raise TypeError("Class expected", other) try: return cls in other._implements except AttributeError: return False class IMiddleware(Interface): '''Hook into Pylons middleware stack ''' def make_middleware(self, app, config): '''Return an app configured with this middleware ''' return app class IGenshiStreamFilter(Interface): ''' Hook into template rendering. See ckan.lib.base.py:render ''' def filter(self, stream): """ Return a filtered Genshi stream. Called when any page is rendered. :param stream: Genshi stream of the current output document :returns: filtered Genshi stream """ return stream class IRoutes(Interface): """ Plugin into the setup of the routes map creation. """ def before_map(self, map): """ Called before the routes map is generated. ``before_map`` is before any other mappings are created so can override all other mappings. :param map: Routes map object :returns: Modified version of the map object """ return map def after_map(self, map): """ Called after routes map is set up. ``after_map`` can be used to add fall-back handlers. :param map: Routes map object :returns: Modified version of the map object """ return map class IMapper(Interface): """ A subset of the SQLAlchemy mapper extension hooks. See http://www.sqlalchemy.org/docs/05/reference/orm/interfaces.html#sqlalchemy.orm.interfaces.MapperExtension Example:: >>> class MyPlugin(SingletonPlugin): ... ... implements(IMapper) ... ... def after_update(self, mapper, connection, instance): ... log("Updated: %r", instance) """ def before_insert(self, mapper, connection, instance): """ Receive an object instance before that instance is INSERTed into its table. """ def before_update(self, mapper, connection, instance): """ Receive an object instance before that instance is UPDATEed. """ def before_delete(self, mapper, connection, instance): """ Receive an object instance before that instance is DELETEed. """ def after_insert(self, mapper, connection, instance): """ Receive an object instance after that instance is INSERTed. """ def after_update(self, mapper, connection, instance): """ Receive an object instance after that instance is UPDATEed. """ def after_delete(self, mapper, connection, instance): """ Receive an object instance after that instance is DELETEed. """ class ISession(Interface): """ A subset of the SQLAlchemy session extension hooks. """ def after_begin(self, session, transaction, connection): """ Execute after a transaction is begun on a connection """ def before_flush(self, session, flush_context, instances): """ Execute before flush process has started. """ def after_flush(self, session, flush_context): """ Execute after flush has completed, but before commit has been called. """ def before_commit(self, session): """ Execute right before commit is called. """ def after_commit(self, session): """ Execute after a commit has occured. """ def after_rollback(self, session): """ Execute after a rollback has occured. """ class IDomainObjectModification(Interface): """ Receives notification of new, changed and deleted datesets. """ def notify(self, entity, operation): pass class IResourceUrlChange(Interface): """ Receives notification of changed urls. """ def notify(self, resource): pass class IResourcePreview(Interface): '''Add custom data previews for resource file-types. ''' def can_preview(self, data_dict): '''Return info on whether the plugin can preview the resource. This can be done in two ways: 1. The old way is to just return ``True`` or ``False``. 2. The new way is to return a dict with three keys: ``'can_preview'`` (``boolean``) ``True`` if the extension can preview the resource. ``'fixable'`` (``string``) A string explaining how preview for the resource could be enabled, for example if the ``resource_proxy`` plugin was enabled. ``'quality'`` (``int``) How good the preview is: ``1`` (poor), ``2`` (average) or ``3`` (good). When multiple preview extensions can preview the same resource, this is used to determine which extension will be used. :param data_dict: the resource to be previewed and the dataset that it belongs to. :type data_dict: dictionary Make sure to check the ``on_same_domain`` value of the resource or the url if your preview requires the resource to be on the same domain because of the same-origin policy. To find out how to preview resources that are on a different domain, read :ref:`resource-proxy`. ''' def setup_template_variables(self, context, data_dict): ''' Add variables to c just prior to the template being rendered. The ``data_dict`` contains the resource and the package. Change the url to a proxied domain if necessary. ''' def preview_template(self, context, data_dict): ''' Returns a string representing the location of the template to be rendered for the read page. The ``data_dict`` contains the resource and the package. ''' class ITagController(Interface): ''' Hook into the Tag controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. ''' def before_view(self, tag_dict): ''' Extensions will recieve this before the tag gets displayed. The dictionary passed will be the one that gets sent to the template. ''' return tag_dict class IGroupController(Interface): """ Hook into the Group controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. """ def read(self, entity): pass def create(self, entity): pass def edit(self, entity): pass def authz_add_role(self, object_role): pass def authz_remove_role(self, object_role): pass def delete(self, entity): pass def before_view(self, pkg_dict): ''' Extensions will recieve this before the group gets displayed. The dictionary passed will be the one that gets sent to the template. ''' return pkg_dict class IOrganizationController(Interface): """ Hook into the Organization controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. """ def read(self, entity): pass def create(self, entity): pass def edit(self, entity): pass def authz_add_role(self, object_role): pass def authz_remove_role(self, object_role): pass def delete(self, entity): pass def before_view(self, pkg_dict): ''' Extensions will recieve this before the organization gets displayed. The dictionary passed will be the one that gets sent to the template. ''' return pkg_dict class IPackageController(Interface): """ Hook into the package controller. (see IGroupController) """ def read(self, entity): pass def create(self, entity): pass def edit(self, entity): pass def authz_add_role(self, object_role): pass def authz_remove_role(self, object_role): pass def delete(self, entity): pass def after_create(self, context, pkg_dict): ''' Extensions will receive the validated data dict after the package has been created (Note that the create method will return a package domain object, which may not include all fields). Also the newly created package id will be added to the dict. ''' pass def after_update(self, context, pkg_dict): ''' Extensions will receive the validated data dict after the package has been updated (Note that the edit method will return a package domain object, which may not include all fields). ''' pass def after_delete(self, context, pkg_dict): ''' Extensions will receive the data dict (tipically containing just the package id) after the package has been deleted. ''' pass def after_show(self, context, pkg_dict): ''' Extensions will receive the validated data dict after the package is ready for display (Note that the read method will return a package domain object, which may not include all fields). ''' pass def before_search(self, search_params): ''' Extensions will receive a dictionary with the query parameters, and should return a modified (or not) version of it. search_params will include an `extras` dictionary with all values from fields starting with `ext_`, so extensions can receive user input from specific fields. ''' return search_params def after_search(self, search_results, search_params): ''' Extensions will receive the search results, as well as the search parameters, and should return a modified (or not) object with the same structure: {'count': '', 'results': '', 'facets': ''} Note that count and facets may need to be adjusted if the extension changed the results for some reason. search_params will include an `extras` dictionary with all values from fields starting with `ext_`, so extensions can receive user input from specific fields. ''' return search_results def before_index(self, pkg_dict): ''' Extensions will receive what will be given to the solr for indexing. This is essentially a flattened dict (except for multli-valued fields such as tags) of all the terms sent to the indexer. The extension can modify this by returning an altered version. ''' return pkg_dict def before_view(self, pkg_dict): ''' Extensions will recieve this before the dataset gets displayed. The dictionary passed will be the one that gets sent to the template. ''' return pkg_dict class IResourceController(Interface): """ Hook into the resource controller. """ def before_show(self, resource_dict): ''' Extensions will receive the validated data dict before the resource is ready for display. ''' return resource_dict def before_edit(self, resource_dict): ''' Extensions will receive the validated data dict before the resource is ready for edit. ''' return resource_dict class IPluginObserver(Interface): """ Plugin to the plugin loading mechanism """ def before_load(self, plugin): """ Called before a plugin is loaded This method is passed the plugin class. """ def after_load(self, service): """ Called after a plugin has been loaded. This method is passed the instantiated service object. """ def before_unload(self, plugin): """ Called before a plugin is loaded This method is passed the plugin class. """ def after_unload(self, service): """ Called after a plugin has been unloaded. This method is passed the instantiated service object. """ class IConfigurable(Interface): """ Pass configuration to plugins and extensions """ def configure(self, config): """ Called by load_environment """ class IConfigurer(Interface): """ Configure CKAN (pylons) environment via the ``pylons.config`` object """ def update_config(self, config): """ Called by load_environment at earliest point when config is available to plugins. The config should be updated in place. :param config: ``pylons.config`` object """ class IActions(Interface): """ Allow adding of actions to the logic layer. """ def get_actions(self): """ Should return a dict, the keys being the name of the logic function and the values being the functions themselves. By decorating a function with the `ckan.logic.side_effect_free` decorator, the associated action will be made available by a GET request (as well as the usual POST request) through the action API. """ class IAuthFunctions(Interface): '''Override CKAN's authorization functions, or add new auth functions.''' def get_auth_functions(self): '''Return the authorization functions provided by this plugin. Return a dictionary mapping authorization function names (strings) to functions. For example:: {'user_create': my_custom_user_create_function, 'group_create': my_custom_group_create} When a user tries to carry out an action via the CKAN API or web interface and CKAN or a CKAN plugin calls ``check_access('some_action')`` as a result, an authorization function named ``'some_action'`` will be searched for in the authorization functions registered by plugins and in CKAN's core authorization functions (found in ``ckan/logic/auth/``). For example when a user tries to create a package, a ``'package_create'`` authorization function is searched for. If an extension registers an authorization function with the same name as one of CKAN's default authorization functions (as with ``'user_create'`` and ``'group_create'`` above), the extension's function will override the default one. Each authorization function should take two parameters ``context`` and ``data_dict``, and should return a dictionary ``{'success': True}`` to authorize the action or ``{'success': False}`` to deny it, for example:: def user_create(context, data_dict=None): if (some condition): return {'success': True} else: return {'success': False, 'msg': 'Not allowed to register'} The context object will contain a ``model`` that can be used to query the database, a ``user`` containing the name of the user doing the request (or their IP if it is an anonymous web request) and an ``auth_user_obj`` containing the actual model.User object (or None if it is an anonymous request). See ``ckan/logic/auth/`` for more examples. Note that by default, all auth functions provided by extensions are assumed to require a validated user or API key, otherwise a :py:class:`ckan.logic.NotAuthorized`: exception will be raised. This check will be performed *before* calling the actual auth function. If you want to allow anonymous access to one of your actions, its auth function must be decorated with the ``auth_allow_anonymous_access`` decorator, available on the plugins toolkit. For example:: import ckan.plugins as p @p.toolkit.auth_allow_anonymous_access def my_search_action(context, data_dict): # Note that you can still return {'success': False} if for some # reason access is denied. def my_create_action(context, data_dict): # Unless there is a logged in user or a valid API key provided # NotAuthorized will be raised before reaching this function. ''' class ITemplateHelpers(Interface): '''Add custom template helper functions. By implementing this plugin interface plugins can provide their own template helper functions, which custom templates can then access via the ``h`` variable. See ``ckanext/example_itemplatehelpers`` for an example plugin. ''' def get_helpers(self): '''Return a dict mapping names to helper functions. The keys of the dict should be the names with which the helper functions will be made available to templates, and the values should be the functions themselves. For example, a dict like: ``{'example_helper': example_helper}`` allows templates to access the ``example_helper`` function via ``h.example_helper()``. Function names should start with the name of the extension providing the function, to prevent name clashes between extensions. ''' class IDatasetForm(Interface): '''Customize CKAN's dataset (package) schemas and forms. By implementing this interface plugins can customise CKAN's dataset schema, for example to add new custom fields to datasets. Multiple IDatasetForm plugins can be used at once, each plugin associating itself with different package types using the ``package_types()`` and ``is_fallback()`` methods below, and then providing different schemas and templates for different types of dataset. When a package controller action is invoked, the ``type`` field of the package will determine which IDatasetForm plugin (if any) gets delegated to. When implementing IDatasetForm, you can inherit from ``ckan.plugins.toolkit.DefaultDatasetForm``, which provides default implementations for each of the methods defined in this interface. See ``ckanext/example_idatasetform`` for an example plugin. ''' def package_types(self): '''Return an iterable of package types that this plugin handles. If a request involving a package of one of the returned types is made, then this plugin instance will be delegated to. There cannot be two IDatasetForm plugins that return the same package type, if this happens then CKAN will raise an exception at startup. :rtype: iterable of strings ''' def is_fallback(self): '''Return ``True`` if this plugin is the fallback plugin. When no IDatasetForm plugin's ``package_types()`` match the ``type`` of the package being processed, the fallback plugin is delegated to instead. There cannot be more than one IDatasetForm plugin whose ``is_fallback()`` method returns ``True``, if this happens CKAN will raise an exception at startup. If no IDatasetForm plugin's ``is_fallback()`` method returns ``True``, CKAN will use ``DefaultDatasetForm`` as the fallback. :rtype: boolean ''' def create_package_schema(self): '''Return the schema for validating new dataset dicts. CKAN will use the returned schema to validate and convert data coming from users (via the dataset form or API) when creating new datasets, before entering that data into the database. If it inherits from ``ckan.plugins.toolkit.DefaultDatasetForm``, a plugin can call ``DefaultDatasetForm``'s ``create_package_schema()`` method to get the default schema and then modify and return it. CKAN's ``convert_to_tags()`` or ``convert_to_extras()`` functions can be used to convert custom fields into dataset tags or extras for storing in the database. See ``ckanext/example_idatasetform`` for examples. :returns: a dictionary mapping dataset dict keys to lists of validator and converter functions to be applied to those keys :rtype: dictionary ''' def update_package_schema(self): '''Return the schema for validating updated dataset dicts. CKAN will use the returned schema to validate and convert data coming from users (via the dataset form or API) when updating datasets, before entering that data into the database. If it inherits from ``ckan.plugins.toolkit.DefaultDatasetForm``, a plugin can call ``DefaultDatasetForm``'s ``update_package_schema()`` method to get the default schema and then modify and return it. CKAN's ``convert_to_tags()`` or ``convert_to_extras()`` functions can be used to convert custom fields into dataset tags or extras for storing in the database. See ``ckanext/example_idatasetform`` for examples. :returns: a dictionary mapping dataset dict keys to lists of validator and converter functions to be applied to those keys :rtype: dictionary ''' def show_package_schema(self): ''' Return a schema to validate datasets before they're shown to the user. CKAN will use the returned schema to validate and convert data coming from the database before it is returned to the user via the API or passed to a template for rendering. If it inherits from ``ckan.plugins.toolkit.DefaultDatasetForm``, a plugin can call ``DefaultDatasetForm``'s ``show_package_schema()`` method to get the default schema and then modify and return it. If you have used ``convert_to_tags()`` or ``convert_to_extras()`` in your ``create_package_schema()`` and ``update_package_schema()`` then you should use ``convert_from_tags()`` or ``convert_from_extras()`` in your ``show_package_schema()`` to convert the tags or extras in the database back into your custom dataset fields. See ``ckanext/example_idatasetform`` for examples. :returns: a dictionary mapping dataset dict keys to lists of validator and converter functions to be applied to those keys :rtype: dictionary ''' def setup_template_variables(self, context, data_dict): '''Add variables to the template context for use in templates. This function is called before a dataset template is rendered. If you have custom dataset templates that require some additional variables, you can add them to the template context ``ckan.plugins.toolkit.c`` here and they will be available in your templates. See ``ckanext/example_idatasetform`` for an example. ''' def new_template(self): '''Return the path to the template for the new dataset page. The path should be relative to the plugin's templates dir, e.g. ``'package/new.html'``. :rtype: string ''' def read_template(self): '''Return the path to the template for the dataset read page. The path should be relative to the plugin's templates dir, e.g. ``'package/read.html'``. If the user requests the dataset in a format other than HTML (CKAN supports returning datasets in RDF or N3 format by appending .rdf or .n3 to the dataset read URL, see :doc:`/linked-data-and-rdf`) then CKAN will try to render a template file with the same path as returned by this function, but a different filename extension, e.g. ``'package/read.rdf'``. If your extension doesn't have this RDF version of the template file, the user will get a 404 error. :rtype: string ''' def edit_template(self): '''Return the path to the template for the dataset edit page. The path should be relative to the plugin's templates dir, e.g. ``'package/edit.html'``. :rtype: string ''' def search_template(self): '''Return the path to the template for use in the dataset search page. This template is used to render each dataset that is listed in the search results on the dataset search page. The path should be relative to the plugin's templates dir, e.g. ``'package/search.html'``. :rtype: string ''' def history_template(self): '''Return the path to the template for the dataset history page. The path should be relative to the plugin's templates dir, e.g. ``'package/history.html'``. :rtype: string ''' def package_form(self): '''Return the path to the template for the dataset form. The path should be relative to the plugin's templates dir, e.g. ``'package/form.html'``. :rtype: string ''' class IGroupForm(Interface): """ Allows customisation of the group controller as a plugin. The behaviour of the plugin is determined by 5 method hooks: - package_form(self) - form_to_db_schema(self) - db_to_form_schema(self) - check_data_dict(self, data_dict) - setup_template_variables(self, context, data_dict) Furthermore, there can be many implementations of this plugin registered at once. With each instance associating itself with 0 or more package type strings. When a package controller action is invoked, the package type determines which of the registered plugins to delegate to. Each implementation must implement two methods which are used to determine the package-type -> plugin mapping: - is_fallback(self) - package_types(self) Implementations might want to consider mixing in ckan.lib.plugins.DefaultGroupForm which provides default behaviours for the 5 method hooks. """ ##### These methods control when the plugin is delegated to ##### def is_fallback(self): """ Returns true iff this provides the fallback behaviour, when no other plugin instance matches a package's type. There must be exactly one fallback controller defined, any attempt to register more than one will throw an exception at startup. If there's no fallback registered at startup the ckan.lib.plugins.DefaultGroupForm used as the fallback. """ def group_types(self): """ Returns an iterable of group type strings. If a request involving a package of one of those types is made, then this plugin instance will be delegated to. There must only be one plugin registered to each group type. Any attempts to register more than one plugin instance to a given group type will raise an exception at startup. """ ##### End of control methods ##### Hooks for customising the PackageController's behaviour ##### ##### TODO: flesh out the docstrings a little more. ##### def new_template(self): """ Returns a string representing the location of the template to be rendered for the 'new' page. Uses the default_group_type configuration option to determine which plugin to use the template from. """ def index_template(self): """ Returns a string representing the location of the template to be rendered for the index page. Uses the default_group_type configuration option to determine which plugin to use the template from. """ def read_template(self): """ Returns a string representing the location of the template to be rendered for the read page """ def history_template(self): """ Returns a string representing the location of the template to be rendered for the history page """ def edit_template(self): """ Returns a string representing the location of the template to be rendered for the edit page """ def package_form(self): """ Returns a string representing the location of the template to be rendered. e.g. "group/new_group_form.html". """ def form_to_db_schema(self): """ Returns the schema for mapping group data from a form to a format suitable for the database. """ def db_to_form_schema(self): """ Returns the schema for mapping group data from the database into a format suitable for the form (optional) """ def check_data_dict(self, data_dict): """ Check if the return data is correct. raise a DataError if not. """ def setup_template_variables(self, context, data_dict): """ Add variables to c just prior to the template being rendered. """ ##### End of hooks ##### class IFacets(Interface): ''' Allows specify which facets are displayed and also the names used. facet_dicts are in the form {'facet_name': 'display name', ...} to allow translatable display names use _(...) eg {'facet_name': _('display name'), ...} and ensure that this is created each time the function is called. The dict supplied is actually an ordered dict. ''' def dataset_facets(self, facets_dict, package_type): ''' Update the facets_dict and return it. ''' return facets_dict def group_facets(self, facets_dict, group_type, package_type): ''' Update the facets_dict and return it. ''' return facets_dict def organization_facets(self, facets_dict, organization_type, package_type): ''' Update the facets_dict and return it. ''' return facets_dict class IAuthenticator(Interface): '''EXPERIMENTAL Allows custom authentication methods to be integrated into CKAN. Currently it is experimental and the interface may change.''' def identify(self): '''called to identify the user. If the user is identfied then it should set c.user: The id of the user c.userobj: The actual user object (this may be removed as a requirement in a later release so that access to the model is not required) ''' def login(self): '''called at login.''' def logout(self): '''called at logout.''' def abort(self, status_code, detail, headers, comment): '''called on abort. This allows aborts due to authorization issues to be overriden''' return (status_code, detail, headers, comment) <file_sep>import logging from urllib import quote from urlparse import urlparse from pylons import config import ckan.lib.base as base import ckan.model as model import ckan.lib.helpers as h import ckan.new_authz as new_authz import ckan.logic as logic import ckan.logic.schema as schema import ckan.lib.captcha as captcha import ckan.lib.mailer as mailer import ckan.lib.navl.dictization_functions as dictization_functions import ckan.plugins as p from ckan.common import _, c, g, request log = logging.getLogger(__name__) abort = base.abort render = base.render validate = base.validate check_access = logic.check_access get_action = logic.get_action NotFound = logic.NotFound NotAuthorized = logic.NotAuthorized ValidationError = logic.ValidationError DataError = dictization_functions.DataError unflatten = dictization_functions.unflatten class UserController(base.BaseController): def __before__(self, action, **env): base.BaseController.__before__(self, action, **env) try: context = {'model': model, 'user': c.user or c.author, 'auth_user_obj': c.userobj} check_access('site_read', context) except NotAuthorized: if c.action not in ('login', 'request_reset', 'perform_reset',): abort(401, _('Not authorized to see this page')) ## hooks for subclasses new_user_form = 'user/new_user_form.html' edit_user_form = 'user/edit_user_form.html' def _new_form_to_db_schema(self): return schema.user_new_form_schema() def _db_to_new_form_schema(self): '''This is an interface to manipulate data from the database into a format suitable for the form (optional)''' def _edit_form_to_db_schema(self): return schema.user_edit_form_schema() def _db_to_edit_form_schema(self): '''This is an interface to manipulate data from the database into a format suitable for the form (optional)''' def _setup_template_variables(self, context, data_dict): c.is_sysadmin = new_authz.is_sysadmin(c.user) try: user_dict = get_action('user_show')(context, data_dict) except NotFound: abort(404, _('User not found')) except NotAuthorized: abort(401, _('Not authorized to see this page')) c.user_dict = user_dict c.is_myself = user_dict['name'] == c.user c.about_formatted = h.render_markdown(user_dict['about']) ## end hooks def _get_repoze_handler(self, handler_name): '''Returns the URL that repoze.who will respond to and perform a login or logout.''' return getattr(request.environ['repoze.who.plugins']['friendlyform'], handler_name) def index(self): LIMIT = 20 page = int(request.params.get('page', 1)) c.q = request.params.get('q', '') c.order_by = request.params.get('order_by', 'name') context = {'return_query': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'q': c.q, 'order_by': c.order_by} try: check_access('user_list', context, data_dict) except NotAuthorized: abort(401, _('Not authorized to see this page')) users_list = get_action('user_list')(context, data_dict) c.page = h.Page( collection=users_list, page=page, url=h.pager_url, item_count=users_list.count(), items_per_page=LIMIT ) return render('user/list.html') def read(self, id=None): context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'for_view': True} data_dict = {'id': id, 'user_obj': c.userobj} context['with_related'] = True self._setup_template_variables(context, data_dict) # The legacy templates have the user's activity stream on the user # profile page, new templates do not. if h.asbool(config.get('ckan.legacy_templates', False)): c.user_activity_stream = get_action('user_activity_list_html')( context, {'id': c.user_dict['id']}) return render('user/read.html') def me(self, locale=None): if not c.user: h.redirect_to(locale=locale, controller='user', action='login', id=None) user_ref = c.userobj.get_reference_preferred_for_uri() h.redirect_to(locale=locale, controller='user', action='dashboard', id=user_ref) def register(self, data=None, errors=None, error_summary=None): context = {'model': model, 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj} try: check_access('user_create', context) except NotAuthorized: abort(401, _('Unauthorized to register as a user.')) return self.new(data, errors, error_summary) def new(self, data=None, errors=None, error_summary=None): '''GET to display a form for registering a new user. or POST the form data to actually do the user registration. ''' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'schema': self._new_form_to_db_schema(), 'save': 'save' in request.params} try: check_access('user_create', context) except NotAuthorized: abort(401, _('Unauthorized to create a user')) if context['save'] and not data: return self._save_new(context) if c.user and not data: # #1799 Don't offer the registration form if already logged in return render('user/logout_first.html') data = data or {} errors = errors or {} error_summary = error_summary or {} vars = {'data': data, 'errors': errors, 'error_summary': error_summary} c.is_sysadmin = new_authz.is_sysadmin(c.user) c.form = render(self.new_user_form, extra_vars=vars) return render('user/new.html') def delete(self, id): '''Delete user with id passed as parameter''' context = {'model': model, 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: get_action('user_delete')(context, data_dict) user_index = h.url_for(controller='user', action='index') h.redirect_to(user_index) except NotAuthorized: msg = _('Unauthorized to delete user with id "{user_id}".') abort(401, msg.format(user_id=id)) def _save_new(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') captcha.check_recaptcha(request) user = get_action('user_create')(context, data_dict) except NotAuthorized: abort(401, _('Unauthorized to create user %s') % '') except NotFound, e: abort(404, _('User not found')) except DataError: abort(400, _(u'Integrity Error')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.new(data_dict) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.new(data_dict, errors, error_summary) if not c.user: # Redirect to a URL picked up by repoze.who which performs the # login login_url = self._get_repoze_handler('login_handler_path') # We need to pass the logged in URL as came_from parameter # otherwise we lose the language setting came_from = h.url_for(controller='user', action='logged_in', __ckan_no_root=True) redirect_url = '{0}?login={1}&password={2}&came_from={3}' h.redirect_to(redirect_url.format( login_url, str(data_dict['name']), quote(data_dict['password1'].encode('utf-8')), came_from)) else: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. h.flash_success(_('User "%s" is now registered but you are still ' 'logged in as "%s" from before') % (data_dict['name'], c.user)) return render('user/logout_first.html') def edit(self, id=None, data=None, errors=None, error_summary=None): context = {'save': 'save' in request.params, 'schema': self._edit_form_to_db_schema(), 'model': model, 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj } if id is None: if c.userobj: id = c.userobj.id else: abort(400, _('No user specified')) data_dict = {'id': id} try: check_access('user_update', context, data_dict) except NotAuthorized: abort(401, _('Unauthorized to edit a user.')) if (context['save']) and not data: return self._save_edit(id, context) try: old_data = get_action('user_show')(context, data_dict) schema = self._db_to_edit_form_schema() if schema: old_data, errors = validate(old_data, schema) c.display_name = old_data.get('display_name') c.user_name = old_data.get('name') data = data or old_data except NotAuthorized: abort(401, _('Unauthorized to edit user %s') % '') except NotFound: abort(404, _('User not found')) user_obj = context.get('user_obj') if not (new_authz.is_sysadmin(c.user) or c.user == user_obj.name): abort(401, _('User %s not authorized to edit %s') % (str(c.user), id)) errors = errors or {} vars = {'data': data, 'errors': errors, 'error_summary': error_summary} self._setup_template_variables({'model': model, 'session': model.Session, 'user': c.user or c.author}, data_dict) c.is_myself = True c.show_email_notifications = h.asbool( config.get('ckan.activity_streams_email_notifications')) c.form = render(self.edit_user_form, extra_vars=vars) return render('user/edit.html') def _save_edit(self, id, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') data_dict['id'] = id # MOAN: Do I really have to do this here? if 'activity_streams_email_notifications' not in data_dict: data_dict['activity_streams_email_notifications'] = False user = get_action('user_update')(context, data_dict) h.flash_success(_('Profile updated')) h.redirect_to(controller='user', action='read', id=user['name']) except NotAuthorized: abort(401, _('Unauthorized to edit user %s') % id) except NotFound, e: abort(404, _('User not found')) except DataError: abort(400, _(u'Integrity Error')) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.edit(id, data_dict, errors, error_summary) def login(self, error=None): # Do any plugin login stuff for item in p.PluginImplementations(p.IAuthenticator): item.login() if 'error' in request.params: h.flash_error(request.params['error']) if request.environ['SCRIPT_NAME'] and g.openid_enabled: # #1662 restriction log.warn('Cannot mount CKAN at a URL and login with OpenID.') g.openid_enabled = False if not c.user: came_from = request.params.get('came_from') if not came_from: came_from = h.url_for(controller='user', action='logged_in', __ckan_no_root=True) c.login_handler = h.url_for( self._get_repoze_handler('login_handler_path'), came_from=came_from) if error: vars = {'error_summary': {'': error}} else: vars = {} #return render('user/login.html', extra_vars=vars) # LAit customization return render('_login.html') else: # LAit customization return render('_login.html') def logged_in(self): # redirect if needed came_from = request.params.get('came_from', '') if self._sane_came_from(came_from): return h.redirect_to(str(came_from)) if c.user: context = None data_dict = {'id': c.user} user_dict = get_action('user_show')(context, data_dict) h.flash_success(_("%s is now logged in") % user_dict['display_name']) # LAit customization return render('_home.html') else: err = _('Login failed. Bad username or password.') if g.openid_enabled: err += _(' (Or if using OpenID, it hasn\'t been associated ' 'with a user account.)') if h.asbool(config.get('ckan.legacy_templates', 'false')): h.flash_error(err) h.redirect_to(controller='user', action='login', came_from=came_from) else: return self.login(error=err) def logout(self): # Do any plugin logout stuff for item in p.PluginImplementations(p.IAuthenticator): item.logout() url = h.url_for(controller='user', action='logged_out_page', __ckan_no_root=True) h.redirect_to(self._get_repoze_handler('logout_handler_path') + '?came_from=' + url) def logged_out(self): # redirect if needed came_from = request.params.get('came_from', '') if self._sane_came_from(came_from): return h.redirect_to(str(came_from)) h.redirect_to(controller='user', action='logged_out_page') def logged_out_page(self): # LAit customization return render('_home.html') def request_reset(self): context = {'model': model, 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj} data_dict = {'id': request.params.get('user')} try: check_access('request_reset', context) except NotAuthorized: abort(401, _('Unauthorized to request reset password.')) if request.method == 'POST': id = request.params.get('user') context = {'model': model, 'user': c.user} data_dict = {'id': id} user_obj = None try: user_dict = get_action('user_show')(context, data_dict) user_obj = context['user_obj'] except NotFound: # Try searching the user del data_dict['id'] data_dict['q'] = id if id and len(id) > 2: user_list = get_action('user_list')(context, data_dict) if len(user_list) == 1: # This is ugly, but we need the user object for the # mailer, # and user_list does not return them del data_dict['q'] data_dict['id'] = user_list[0]['id'] user_dict = get_action('user_show')(context, data_dict) user_obj = context['user_obj'] elif len(user_list) > 1: h.flash_error(_('"%s" matched several users') % (id)) else: h.flash_error(_('No such user: %s') % id) else: h.flash_error(_('No such user: %s') % id) if user_obj: try: mailer.send_reset_link(user_obj) h.flash_success(_('Please check your inbox for ' 'a reset code.')) h.redirect_to('/') except mailer.MailerException, e: h.flash_error(_('Could not send reset link: %s') % unicode(e)) return render('user/request_reset.html') def perform_reset(self, id): # FIXME 403 error for invalid key is a non helpful page # FIXME We should reset the reset key when it is used to prevent # reuse of the url context = {'model': model, 'session': model.Session, 'user': id, 'keep_email': True} try: check_access('user_reset', context) except NotAuthorized: abort(401, _('Unauthorized to reset password.')) try: data_dict = {'id': id} user_dict = get_action('user_show')(context, data_dict) user_obj = context['user_obj'] except NotFound, e: abort(404, _('User not found')) c.reset_key = request.params.get('key') if not mailer.verify_reset_link(user_obj, c.reset_key): h.flash_error(_('Invalid reset key. Please try again.')) abort(403) if request.method == 'POST': try: context['reset_password'] = True new_password = self._get_form_password() user_dict['password'] = <PASSWORD> user_dict['reset_key'] = c.reset_key user_dict['state'] = model.State.ACTIVE user = get_action('user_update')(context, user_dict) h.flash_success(_("Your password has been reset.")) h.redirect_to('/') except NotAuthorized: h.flash_error(_('Unauthorized to edit user %s') % id) except NotFound, e: h.flash_error(_('User not found')) except DataError: h.flash_error(_(u'Integrity Error')) except ValidationError, e: h.flash_error(u'%r' % e.error_dict) except ValueError, ve: h.flash_error(unicode(ve)) c.user_dict = user_dict return render('user/perform_reset.html') def _get_form_password(self): password1 = request.params.getone('password1') password2 = request.params.getone('password2') if (password1 is not None and password1 != ''): if not len(password1) >= 4: raise ValueError(_('Your password must be 4 ' 'characters or longer.')) elif not password1 == password2: raise ValueError(_('The passwords you entered' ' do not match.')) return password1 raise ValueError(_('You must provide a password')) def followers(self, id=None): context = {'for_view': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'id': id, 'user_obj': c.userobj} self._setup_template_variables(context, data_dict) f = get_action('user_follower_list') try: c.followers = f(context, {'id': c.user_dict['id']}) except NotAuthorized: abort(401, _('Unauthorized to view followers %s') % '') return render('user/followers.html') def activity(self, id, offset=0): '''Render this user's public activity stream page.''' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'for_view': True} data_dict = {'id': id, 'user_obj': c.userobj} try: check_access('user_show', context, data_dict) except NotAuthorized: abort(401, _('Not authorized to see this page')) self._setup_template_variables(context, data_dict) c.user_activity_stream = get_action('user_activity_list_html')( context, {'id': c.user_dict['id'], 'offset': offset}) return render('user/activity_stream.html') def _get_dashboard_context(self, filter_type=None, filter_id=None, q=None): '''Return a dict needed by the dashboard view to determine context.''' def display_name(followee): '''Return a display name for a user, group or dataset dict.''' display_name = followee.get('display_name') fullname = followee.get('fullname') title = followee.get('title') name = followee.get('name') return display_name or fullname or title or name if (filter_type and filter_id): context = { 'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'for_view': True } data_dict = {'id': filter_id} followee = None action_functions = { 'dataset': 'package_show', 'user': 'user_show', 'group': 'group_show' } action_function = logic.get_action( action_functions.get(filter_type)) # Is this a valid type? if action_function is None: abort(404, _('Follow item not found')) try: followee = action_function(context, data_dict) except NotFound: abort(404, _('{0} not found').format(filter_type)) except NotAuthorized: abort(401, _('Unauthorized to read {0} {1}').format( filter_type, id)) if followee is not None: return { 'filter_type': filter_type, 'q': q, 'context': display_name(followee), 'selected_id': followee.get('id'), 'dict': followee, } return { 'filter_type': filter_type, 'q': q, 'context': _('Everything'), 'selected_id': False, 'dict': None, } def dashboard(self, id=None, offset=0): context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'for_view': True} data_dict = {'id': id, 'user_obj': c.userobj, 'offset': offset} self._setup_template_variables(context, data_dict) q = request.params.get('q', u'') filter_type = request.params.get('type', u'') filter_id = request.params.get('name', u'') c.followee_list = get_action('followee_list')( context, {'id': c.userobj.id, 'q': q}) c.dashboard_activity_stream_context = self._get_dashboard_context( filter_type, filter_id, q) c.dashboard_activity_stream = h.dashboard_activity_stream( c.userobj.id, filter_type, filter_id, offset ) # Mark the user's new activities as old whenever they view their # dashboard page. get_action('dashboard_mark_activities_old')(context, {}) return render('user/dashboard.html') def dashboard_datasets(self): context = {'for_view': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'user_obj': c.userobj} self._setup_template_variables(context, data_dict) return render('user/dashboard_datasets.html') def dashboard_organizations(self): context = {'for_view': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'user_obj': c.userobj} self._setup_template_variables(context, data_dict) return render('user/dashboard_organizations.html') def dashboard_groups(self): context = {'for_view': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'user_obj': c.userobj} self._setup_template_variables(context, data_dict) return render('user/dashboard_groups.html') def follow(self, id): '''Start following this user.''' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: get_action('follow_user')(context, data_dict) user_dict = get_action('user_show')(context, data_dict) h.flash_success(_("You are now following {0}").format( user_dict['display_name'])) except ValidationError as e: error_message = (e.extra_msg or e.message or e.error_summary or e.error_dict) h.flash_error(error_message) except NotAuthorized as e: h.flash_error(e.extra_msg) h.redirect_to(controller='user', action='read', id=id) def unfollow(self, id): '''Stop following this user.''' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: get_action('unfollow_user')(context, data_dict) user_dict = get_action('user_show')(context, data_dict) h.flash_success(_("You are no longer following {0}").format( user_dict['display_name'])) except (NotFound, NotAuthorized) as e: error_message = e.extra_msg or e.message h.flash_error(error_message) except ValidationError as e: error_message = (e.error_summary or e.message or e.extra_msg or e.error_dict) h.flash_error(error_message) h.redirect_to(controller='user', action='read', id=id) def _sane_came_from(self, url): '''Returns True if came_from is local''' if not url or (len(url) >= 2 and url.startswith('//')): return False parsed = urlparse(url) if parsed.scheme: domain = urlparse(h.url_for('/', qualified=True)).netloc if domain != parsed.netloc: return False return True<file_sep>import base64 import datetime import re import os from hashlib import sha1, md5 from sqlalchemy.sql.expression import or_ from sqlalchemy.orm import synonym from sqlalchemy import types, Column, Table import vdm.sqlalchemy import meta import core import types as _types import domain_object from pylons import config user_table = Table('user', meta.metadata, Column('id', types.UnicodeText, primary_key=True, default=_types.make_uuid), Column('name', types.UnicodeText, nullable=False, unique=True), Column('openid', types.UnicodeText), Column('password', types.UnicodeText), Column('fullname', types.UnicodeText), Column('email', types.UnicodeText), Column('apikey', types.UnicodeText, default=_types.make_uuid), Column('created', types.DateTime, default=datetime.datetime.now), Column('reset_key', types.UnicodeText), Column('about', types.UnicodeText), Column('activity_streams_email_notifications', types.Boolean, default=False), Column('sysadmin', types.Boolean, default=False), ) vdm.sqlalchemy.make_table_stateful(user_table) class User(vdm.sqlalchemy.StatefulObjectMixin, domain_object.DomainObject): VALID_NAME = re.compile(r"^[a-zA-Z0-9_\-]{3,255}$") DOUBLE_SLASH = re.compile(':\/([^/])') @classmethod def by_openid(cls, openid): obj = meta.Session.query(cls).autoflush(False) return obj.filter_by(openid=openid).first() @classmethod def by_email(cls, email): return meta.Session.query(cls).filter_by(email=email).all() @classmethod def get(cls, user_reference): # double slashes in an openid often get turned into single slashes # by browsers, so correct that for the openid lookup corrected_openid_user_ref = cls.DOUBLE_SLASH.sub('://\\1', user_reference) query = meta.Session.query(cls).autoflush(False) query = query.filter(or_(cls.name == user_reference, cls.openid == corrected_openid_user_ref, cls.id == user_reference)) return query.first() @classmethod def all(cls): '''Return all users in this CKAN instance. :rtype: list of ckan.model.user.User objects ''' q = meta.Session.query(cls) return q.all() @property def display_name(self): if self.fullname is not None and len(self.fullname.strip()) > 0: return self.fullname return self.name @property def email_hash(self): e = '' if self.email: e = self.email.strip().lower().encode('utf8') return md5(e).hexdigest() def get_reference_preferred_for_uri(self): '''Returns a reference (e.g. name, id, openid) for this user suitable for the user\'s URI. When there is a choice, the most preferable one will be given, based on readability. This is expected when repoze.who can give a more friendly name for an openid user. The result is not escaped (will get done in url_for/redirect_to). ''' if self.name: ref = self.name elif self.openid: ref = self.openid else: ref = self.id return ref def _set_password(self, password): '''Hash password on the fly.''' if isinstance(password, unicode): password_8bit = password.encode('ascii', 'ignore') else: password_8bit = password salt = sha1(os.urandom(60)) hash = sha1(password_8bit + salt.hexdigest()) hashed_password = salt.hexdigest() + hash.hexdigest() if not isinstance(hashed_password, unicode): hashed_password = hashed_password.decode('utf-8') self._password = hashed_password def _get_password(self): '''Return the password hashed''' return self._password def validate_password(self, password): ''' Check the password against existing credentials. :param password: the password that was provided by the user to try and authenticate. This is the clear text version that we will need to match against the hashed one in the database. :type password: unicode object. :return: Whether the password is valid. :rtype: bool ''' if not password or not self.password: return False try: timestamp_string = password[:10] timestamp_int = int(timestamp_string) date = datetime.datetime.fromtimestamp(timestamp_int) now = datetime.datetime.now() now_int = int(now.strftime('%s')) date_int = int(date.strftime('%s')) if now_int>date_int and (now_int-date_int)>100: return False if date_int>now_int and (date_int-now_int)>100: return False secret = config.get('login.secret', '') hash = base64.b64encode(sha1(password[:10]+self.name+secret).digest()) return hash == password[10:] except ValueError as e: if isinstance(password, unicode): password_8bit = password.encode('ascii', 'ignore') else: password_8bit = password hashed_pass = sha1(password_8bit + self.password[:40]) return self.password[40:] == hashed_pass.hexdigest() password = property(_get_password, _set_password) @classmethod def check_name_valid(cls, name): if not name \ or not len(name.strip()) \ or not cls.VALID_NAME.match(name): return False return True @classmethod def check_name_available(cls, name): return cls.by_name(name) == None def as_dict(self): _dict = domain_object.DomainObject.as_dict(self) del _dict['password'] return _dict def number_of_edits(self): # have to import here to avoid circular imports import ckan.model as model revisions_q = meta.Session.query(model.Revision) revisions_q = revisions_q.filter_by(author=self.name) return revisions_q.count() def number_administered_packages(self): # have to import here to avoid circular imports import ckan.model as model q = meta.Session.query(model.PackageRole) q = q.filter_by(user=self, role=model.Role.ADMIN) return q.count() def activate(self): ''' Activate the user ''' self.state = core.State.ACTIVE def set_pending(self): ''' Set the user as pending ''' self.state = core.State.PENDING def is_deleted(self): return self.state == core.State.DELETED def is_pending(self): return self.state == core.State.PENDING def is_in_group(self, group_id): return group_id in self.get_group_ids() def is_in_groups(self, group_ids): ''' Given a list of group ids, returns True if this user is in any of those groups ''' guser = set(self.get_group_ids()) gids = set(group_ids) return len(guser.intersection(gids)) > 0 def get_group_ids(self, group_type=None, capacity=None): ''' Returns a list of group ids that the current user belongs to ''' return [g.id for g in self.get_groups(group_type=group_type, capacity=capacity)] def get_groups(self, group_type=None, capacity=None): import ckan.model as model q = meta.Session.query(model.Group)\ .join(model.Member, model.Member.group_id == model.Group.id and \ model.Member.table_name == 'user').\ join(model.User, model.User.id == model.Member.table_id).\ filter(model.Member.state == 'active').\ filter(model.Member.table_id == self.id) if capacity: q = q.filter(model.Member.capacity == capacity) return q.all() if '_groups' not in self.__dict__: self._groups = q.all() groups = self._groups if group_type: groups = [g for g in groups if g.type == group_type] return groups @classmethod def search(cls, querystr, sqlalchemy_query=None, user_name=None): '''Search name, fullname, email and openid. ''' if sqlalchemy_query is None: query = meta.Session.query(cls) else: query = sqlalchemy_query qstr = '%' + querystr + '%' filters = [ cls.name.ilike(qstr), cls.fullname.ilike(qstr), cls.openid.ilike(qstr), ] # sysadmins can search on user emails import ckan.new_authz as new_authz if user_name and new_authz.is_sysadmin(user_name): filters.append(cls.email.ilike(qstr)) query = query.filter(or_(*filters)) return query meta.mapper(User, user_table, properties={'password': synonym('_password', map_column=True)}, order_by=user_table.c.name)<file_sep>""" The feed controller produces Atom feeds of datasets. * datasets belonging to a particular group. * datasets tagged with a particular tag. * datasets that match an arbitrary search. TODO: document paged feeds Other feeds are available elsewhere in the code, but these provide feeds of the revision history, rather than a feed of datasets. * ``ckan/controllers/group.py`` provides an atom feed of a group's revision history. * ``ckan/controllers/package.py`` provides an atom feed of a dataset's revision history. * ``ckan/controllers/revision.py`` provides an atom feed of the repository's revision history. """ # TODO fix imports import logging import urlparse import webhelpers.feedgenerator from pylons import config import ckan.model as model import ckan.lib.base as base import ckan.lib.helpers as h import ckan.logic as logic from ckan.common import _, g, c, request, response, json # TODO make the item list configurable ITEMS_LIMIT = 20 log = logging.getLogger(__name__) def _package_search(data_dict): """ Helper method that wraps the package_search action. * unless overridden, sorts results by metadata_modified date * unless overridden, sets a default item limit """ context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} if 'sort' not in data_dict or not data_dict['sort']: data_dict['sort'] = 'metadata_modified desc' if 'rows' not in data_dict or not data_dict['rows']: data_dict['rows'] = ITEMS_LIMIT # package_search action modifies the data_dict, so keep our copy intact. query = logic.get_action('package_search')(context, data_dict.copy()) return query['count'], query['results'] def _create_atom_id(resource_path, authority_name=None, date_string=None): """ Helper method that creates an atom id for a feed or entry. An id must be unique, and must not change over time. ie - once published, it represents an atom feed or entry uniquely, and forever. See [4]: When an Atom Document is relocated, migrated, syndicated, republished, exported, or imported, the content of its atom:id element MUST NOT change. Put another way, an atom:id element pertains to all instantiations of a particular Atom entry or feed; revisions retain the same content in their atom:id elements. It is suggested that the atom:id element be stored along with the associated resource. resource_path The resource path that uniquely identifies the feed or element. This mustn't be something that changes over time for a given entry or feed. And does not necessarily need to be resolvable. e.g. ``"/group/933f3857-79fd-4beb-a835-c0349e31ce76"`` could represent the feed of datasets belonging to the identified group. authority_name The domain name or email address of the publisher of the feed. See [3] for more details. If ``None`` then the domain name is taken from the config file. First trying ``ckan.feeds.authority_name``, and failing that, it uses ``ckan.site_url``. Again, this should not change over time. date_string A string representing a date on which the authority_name is owned by the publisher of the feed. e.g. ``"2012-03-22"`` Again, this should not change over time. If date_string is None, then an attempt is made to read the config option ``ckan.feeds.date``. If that's not available, then the date_string is not used in the generation of the atom id. Following the methods outlined in [1], [2] and [3], this function produces tagURIs like: ``"tag:thedatahub.org,2012:/group/933f3857-79fd-4beb-a835-c0349e31ce76"``. If not enough information is provide to produce a valid tagURI, then only the resource_path is used, e.g.: :: "http://thedatahub.org/group/933f3857-79fd-4beb-a835-c0349e31ce76" or "/group/933f3857-79fd-4beb-a835-c0349e31ce76" The latter of which is only used if no site_url is available. And it should be noted will result in an invalid feed. [1] http://web.archive.org/web/20110514113830/http://diveintomark.org/\ archives/2004/05/28/howto-atom-id [2] http://www.taguri.org/ [3] http://tools.ietf.org/html/rfc4151#section-2.1 [4] http://www.ietf.org/rfc/rfc4287 """ if authority_name is None: authority_name = config.get('ckan.feeds.authority_name', '').strip() if not authority_name: site_url = config.get('ckan.site_url', '').strip() authority_name = urlparse.urlparse(site_url).netloc if not authority_name: log.warning('No authority_name available for feed generation. ' 'Generated feed will be invalid.') if date_string is None: date_string = config.get('ckan.feeds.date', '') if not date_string: log.warning('No date_string available for feed generation. ' 'Please set the "ckan.feeds.date" config value.') # Don't generate a tagURI without a date as it wouldn't be valid. # This is best we can do, and if the site_url is not set, then # this still results in an invalid feed. site_url = config.get('ckan.site_url', '') return '/'.join([site_url, resource_path]) tagging_entity = ','.join([authority_name, date_string]) return ':'.join(['tag', tagging_entity, resource_path]) class FeedController(base.BaseController): # LAit customization base_url = config.get('ckan.base_url', '') def _alternate_url(self, params, **kwargs): search_params = params.copy() search_params.update(kwargs) # Can't count on the page sizes being the same on the search results # view. So provide an alternate link to the first page, regardless # of the page we're looking at in the feed. search_params.pop('page', None) return self._feed_url(search_params, controller='package', action='search') def group(self, id): try: context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} group_dict = logic.get_action('group_show')(context, {'id': id}) except logic.NotFound: base.abort(404, _('Group not found')) data_dict, params = self._parse_url_params() data_dict['fq'] = 'groups:"%s"' % id item_count, results = _package_search(data_dict) navigation_urls = self._navigation_urls(params, item_count=item_count, limit=data_dict['rows'], controller='feed', action='group', id=id) feed_url = self._feed_url(params, controller='feed', action='group', id=id) alternate_url = self._alternate_url(params, groups=id) return self.output_feed(results, feed_title=u'%s - Group: "%s"' % (g.site_title, group_dict['title']), feed_description=u'Recently created or ' 'updated datasets on %s by group: "%s"' % (g.site_title, group_dict['title']), feed_link=alternate_url, feed_guid=_create_atom_id (u'/feeds/groups/%s.atom' % id), feed_url=feed_url, navigation_urls=navigation_urls) def tag(self, id): data_dict, params = self._parse_url_params() data_dict['fq'] = 'tags:"%s"' % id item_count, results = _package_search(data_dict) navigation_urls = self._navigation_urls(params, item_count=item_count, limit=data_dict['rows'], controller='feed', action='tag', id=id) feed_url = self._feed_url(params, controller='feed', action='tag', id=id) alternate_url = self._alternate_url(params, tags=id) return self.output_feed(results, feed_title=u'%s - Tag: "%s"' % (g.site_title, id), feed_description=u'Recently created or ' 'updated datasets on %s by tag: "%s"' % (g.site_title, id), feed_link=alternate_url, feed_guid=_create_atom_id (u'/feeds/tag/%s.atom' % id), feed_url=feed_url, navigation_urls=navigation_urls) def general(self): data_dict, params = self._parse_url_params() data_dict['q'] = '*:*' item_count, results = _package_search(data_dict) navigation_urls = self._navigation_urls(params, item_count=item_count, limit=data_dict['rows'], controller='feed', action='general') feed_url = self._feed_url(params, controller='feed', action='general') alternate_url = self._alternate_url(params) return self.output_feed(results, feed_title=g.site_title, feed_description=u'Recently created or ' 'updated datasets on %s' % g.site_title, feed_link=alternate_url, feed_guid=_create_atom_id (u'/feeds/dataset.atom'), feed_url=feed_url, navigation_urls=navigation_urls) # TODO check search params def custom(self): q = request.params.get('q', u'') fq = '' search_params = {} for (param, value) in request.params.items(): if param not in ['q', 'page', 'sort'] \ and len(value) and not param.startswith('_'): search_params[param] = value fq += ' %s:"%s"' % (param, value) try: page = int(request.params.get('page', 1)) except ValueError: base.abort(400, _('"page" parameter must be a positive integer')) if page < 0: base.abort(400, _('"page" parameter must be a positive integer')) limit = ITEMS_LIMIT data_dict = { 'q': q, 'fq': fq, 'start': (page - 1) * limit, 'rows': limit, 'sort': request.params.get('sort', None), } item_count, results = _package_search(data_dict) navigation_urls = self._navigation_urls(request.params, item_count=item_count, limit=data_dict['rows'], controller='feed', action='custom') feed_url = self._feed_url(request.params, controller='feed', action='custom') atom_url = h._url_with_params('/feeds/custom.atom', search_params.items()) alternate_url = self._alternate_url(request.params) return self.output_feed(results, feed_title=u'%s - Custom query' % g.site_title, feed_description=u'Recently created or updated' ' datasets on %s. Custom query: \'%s\'' % (g.site_title, q), feed_link=alternate_url, feed_guid=_create_atom_id(atom_url), feed_url=feed_url, navigation_urls=navigation_urls) def output_feed(self, results, feed_title, feed_description, feed_link, feed_url, navigation_urls, feed_guid): author_name = config.get('ckan.feeds.author_name', '').strip() or \ config.get('ckan.site_id', '').strip() author_link = config.get('ckan.feeds.author_link', '').strip() or \ config.get('ckan.site_url', '').strip() # TODO language feed = _FixedAtom1Feed( title=feed_title, link=feed_link, description=feed_description, language=u'en', author_name=author_name, author_link=author_link, feed_guid=feed_guid, feed_url=feed_url, previous_page=navigation_urls['previous'], next_page=navigation_urls['next'], first_page=navigation_urls['first'], last_page=navigation_urls['last'], ) for pkg in results: feed.add_item( title=pkg.get('title', ''), link=self.base_url + h.url_for(controller='package', action='read', id=pkg['id']), description=pkg.get('notes', ''), updated=h.date_str_to_datetime(pkg.get('metadata_modified')), published=h.date_str_to_datetime(pkg.get('metadata_created')), unique_id=_create_atom_id(u'/dataset/%s' % pkg['id']), author_name=pkg.get('author', ''), author_email=pkg.get('author_email', ''), categories=[t['name'] for t in pkg.get('tags', [])], enclosure=webhelpers.feedgenerator.Enclosure( self.base_url + h.url_for(controller='api', register='package', action='show', id=pkg['name'], ver='2'), unicode(len(json.dumps(pkg))), # TODO fix this u'application/json') ) response.content_type = feed.mime_type return feed.writeString('utf-8') #### CLASS PRIVATE METHODS #### def _feed_url(self, query, controller, action, **kwargs): """ Constructs the url for the given action. Encoding the query parameters. """ path = h.url_for(controller=controller, action=action, **kwargs) return h._url_with_params(self.base_url + path, query.items()) def _navigation_urls(self, query, controller, action, item_count, limit, **kwargs): """ Constructs and returns first, last, prev and next links for paging """ urls = dict((rel, None) for rel in 'previous next first last'.split()) page = int(query.get('page', 1)) # first: remove any page parameter first_query = query.copy() first_query.pop('page', None) urls['first'] = self._feed_url(first_query, controller, action, **kwargs) # last: add last page parameter last_page = (item_count / limit) + min(1, item_count % limit) last_query = query.copy() last_query['page'] = last_page urls['last'] = self._feed_url(last_query, controller, action, **kwargs) # previous if page > 1: previous_query = query.copy() previous_query['page'] = page - 1 urls['previous'] = self._feed_url(previous_query, controller, action, **kwargs) else: urls['previous'] = None # next if page < last_page: next_query = query.copy() next_query['page'] = page + 1 urls['next'] = self._feed_url(next_query, controller, action, **kwargs) else: urls['next'] = None return urls def _parse_url_params(self): """ Constructs a search-query dict from the URL query parameters. Returns the constructed search-query dict, and the valid URL query parameters. """ try: page = int(request.params.get('page', 1)) or 1 except ValueError: base.abort(400, _('"page" parameter must be a positive integer')) if page < 0: base.abort(400, _('"page" parameter must be a positive integer')) limit = ITEMS_LIMIT data_dict = { 'start': (page - 1) * limit, 'rows': limit } # Filter ignored query parameters valid_params = ['page'] params = dict((p, request.params.get(p)) for p in valid_params if p in request.params) return data_dict, params # TODO paginated feed class _FixedAtom1Feed(webhelpers.feedgenerator.Atom1Feed): """ The Atom1Feed defined in webhelpers doesn't provide all the fields we might want to publish. * In Atom1Feed, each <entry> is created with identical <updated> and <published> fields. See [1] (webhelpers 1.2) for details. So, this class fixes that by allow an item to set both an <updated> and <published> field. * In Atom1Feed, the feed description is not used. So this class uses the <subtitle> field to publish that. [1] https://bitbucket.org/bbangert/webhelpers/src/f5867a319abf/\ webhelpers/feedgenerator.py#cl-373 """ def add_item(self, *args, **kwargs): """ Drop the pubdate field from the new item. """ if 'pubdate' in kwargs: kwargs.pop('pubdate') defaults = {'updated': None, 'published': None} defaults.update(kwargs) super(_FixedAtom1Feed, self).add_item(*args, **defaults) def latest_post_date(self): """ Calculates the latest post date from the 'updated' fields, rather than the 'pubdate' fields. """ updates = [item['updated'] for item in self.items if item['updated'] is not None] if not len(updates): # delegate to parent for default behaviour return super(_FixedAtom1Feed, self).latest_post_date() return max(updates) def add_item_elements(self, handler, item): """ Add the <updated> and <published> fields to each entry that's written to the handler. """ super(_FixedAtom1Feed, self).add_item_elements(handler, item) dfunc = webhelpers.feedgenerator.rfc3339_date if(item['updated']): handler.addQuickElement(u'updated', dfunc(item['updated']).decode('utf-8')) if(item['published']): handler.addQuickElement(u'published', dfunc(item['published']).decode('utf-8')) def add_root_elements(self, handler): """ Add additional feed fields. * Add the <subtitle> field from the feed description * Add links other pages of the logical feed. """ super(_FixedAtom1Feed, self).add_root_elements(handler) handler.addQuickElement(u'subtitle', self.feed['description']) for page in ['previous', 'next', 'first', 'last']: if self.feed.get(page + '_page', None): handler.addQuickElement(u'link', u'', {'rel': page, 'href': self.feed.get(page + '_page')})<file_sep>import os import re import mimetypes from logging import getLogger from pylons import config import shapely from ckan import plugins as p from ckan.lib.search import SearchError, PackageSearchQuery from ckan.lib.helpers import json from ckanext.spatial.lib import save_package_extent,validate_bbox, bbox_query, bbox_query_ordered from ckanext.spatial.model.package_extent import setup as setup_model log = getLogger(__name__) def package_error_summary(error_dict): ''' Do some i18n stuff on the error_dict keys ''' def prettify(field_name): field_name = re.sub('(?<!\w)[Uu]rl(?!\w)', 'URL', field_name.replace('_', ' ').capitalize()) return p.toolkit._(field_name.replace('_', ' ')) summary = {} for key, error in error_dict.iteritems(): if key == 'resources': summary[p.toolkit._('Resources')] = p.toolkit._('Package resource(s) invalid') elif key == 'extras': summary[p.toolkit._('Extras')] = p.toolkit._('Missing Value') elif key == 'extras_validation': summary[p.toolkit._('Extras')] = error[0] else: summary[p.toolkit._(prettify(key))] = error[0] return summary class SpatialMetadata(p.SingletonPlugin): p.implements(p.IPackageController, inherit=True) p.implements(p.IConfigurable, inherit=True) p.implements(p.IConfigurer, inherit=True) p.implements(p.ITemplateHelpers, inherit=True) def configure(self, config): if not p.toolkit.asbool(config.get('ckan.spatial.testing', 'False')): setup_model() def update_config(self, config): ''' Set up the resource library, public directory and template directory for all the spatial extensions ''' p.toolkit.add_public_directory(config, 'public') p.toolkit.add_template_directory(config, 'templates') p.toolkit.add_resource('public', 'ckanext-spatial') # Add media types for common extensions not included in the mimetypes # module mimetypes.add_type('application/json', '.geojson') mimetypes.add_type('application/gml+xml', '.gml') def create(self, package): self.check_spatial_extra(package) def edit(self, package): self.check_spatial_extra(package) def check_spatial_extra(self,package): ''' For a given package, looks at the spatial extent (as given in the extra "spatial" in GeoJSON format) and records it in PostGIS. ''' if not package.id: log.warning('Couldn\'t store spatial extent because no id was provided for the package') return # TODO: deleted extra for extra in package.extras_list: if extra.key == 'spatial': if extra.state == 'active' and extra.value: extra.value = extra.value.replace('\n', '').replace('\r', '').replace(' ', '') try: log.debug('Received: %r' % extra.value) geometry = json.loads(extra.value) except ValueError,e: error_dict = {'spatial':[u'Error decoding JSON object: %s' % str(e)]} raise p.toolkit.ValidationError(error_dict, error_summary=package_error_summary(error_dict)) except TypeError,e: error_dict = {'spatial':[u'Error decoding JSON object: %s' % str(e)]} raise p.toolkit.ValidationError(error_dict, error_summary=package_error_summary(error_dict)) try: save_package_extent(package.id,geometry) except ValueError,e: error_dict = {'spatial':[u'Error creating geometry: %s' % str(e)]} raise p.toolkit.ValidationError(error_dict, error_summary=package_error_summary(error_dict)) except Exception, e: if bool(os.getenv('DEBUG')): raise error_dict = {'spatial':[u'Error: %s' % str(e)]} raise p.toolkit.ValidationError(error_dict, error_summary=package_error_summary(error_dict)) elif (extra.state == 'active' and not extra.value) or extra.state == 'deleted': # Delete extent from table save_package_extent(package.id,None) break def delete(self, package): save_package_extent(package.id,None) ## ITemplateHelpers def get_helpers(self): from ckanext.spatial import helpers as spatial_helpers return { 'get_reference_date' : spatial_helpers.get_reference_date, 'get_responsible_party': spatial_helpers.get_responsible_party, 'get_common_map_config' : spatial_helpers.get_common_map_config, } class SpatialQuery(p.SingletonPlugin): p.implements(p.IRoutes, inherit=True) p.implements(p.IPackageController, inherit=True) p.implements(p.IConfigurable, inherit=True) search_backend = None def configure(self, config): self.search_backend = config.get('ckanext.spatial.search_backend', 'postgis') if self.search_backend != 'postgis' and not p.toolkit.check_ckan_version('2.0.1'): msg = 'The Solr backends for the spatial search require CKAN 2.0.1 or higher. ' + \ 'Please upgrade CKAN or select the \'postgis\' backend.' raise p.toolkit.CkanVersionException(msg) def before_map(self, map): map.connect('api_spatial_query', '/api/2/search/{register:dataset|package}/geo', controller='ckanext.spatial.controllers.api:ApiController', action='spatial_query') return map def before_index(self, pkg_dict): if pkg_dict.get('extras_spatial', None) and self.search_backend in ('solr', 'solr-spatial-field'): try: geometry = json.loads(pkg_dict['extras_spatial']) except ValueError, e: log.error('Geometry not valid GeoJSON, not indexing') return pkg_dict if self.search_backend == 'solr': # Only bbox supported for this backend if not (geometry['type'] == 'Polygon' and len(geometry['coordinates']) == 1 and len(geometry['coordinates'][0]) == 5): log.error('Solr backend only supports bboxes, ignoring geometry {0}'.format(pkg_dict['extras_spatial'])) return pkg_dict coords = geometry['coordinates'] pkg_dict['maxy'] = max(coords[0][2][1], coords[0][0][1]) pkg_dict['miny'] = min(coords[0][2][1], coords[0][0][1]) pkg_dict['maxx'] = max(coords[0][2][0], coords[0][0][0]) pkg_dict['minx'] = min(coords[0][2][0], coords[0][0][0]) pkg_dict['bbox_area'] = (pkg_dict['maxx'] - pkg_dict['minx']) * \ (pkg_dict['maxy'] - pkg_dict['miny']) elif self.search_backend == 'solr-spatial-field': wkt = None # Check potential problems with bboxes if geometry['type'] == 'Polygon' \ and len(geometry['coordinates']) == 1 \ and len(geometry['coordinates'][0]) == 5: # Check wrong bboxes (4 same points) xs = [p[0] for p in geometry['coordinates'][0]] ys = [p[1] for p in geometry['coordinates'][0]] if xs.count(xs[0]) == 5 and ys.count(ys[0]) == 5: wkt = 'POINT({x} {y})'.format(x=xs[0], y=ys[0]) else: # Check if coordinates are defined counter-clockwise, # otherwise we'll get wrong results from Solr lr = shapely.geometry.polygon.LinearRing(geometry['coordinates'][0]) if not lr.is_ccw: lr.coords = list(lr.coords)[::-1] polygon = shapely.geometry.polygon.Polygon(lr) wkt = polygon.wkt if not wkt: shape = shapely.geometry.asShape(geometry) if not shape.is_valid: log.error('Wrong geometry, not indexing') return pkg_dict wkt = shape.wkt pkg_dict['spatial_geom'] = wkt return pkg_dict def before_search(self, search_params): if search_params.get('extras', None) and search_params['extras'].get('ext_bbox', None): bbox = validate_bbox(search_params['extras']['ext_bbox']) if not bbox: raise SearchError('Wrong bounding box provided') if self.search_backend == 'solr': search_params = self._params_for_solr_search(bbox, search_params) elif self.search_backend == 'solr-spatial-field': search_params = self._params_for_solr_spatial_field_search(bbox, search_params) elif self.search_backend == 'postgis': search_params = self._params_for_postgis_search(bbox, search_params) return search_params def _params_for_solr_search(self, bbox, search_params): ''' This will add the following parameters to the query: defType - edismax (We need to define EDisMax to use bf) bf - {function} A boost function to influence the score (thus influencing the sorting). The algorithm can be basically defined as: 2 * X / Q + T Where X is the intersection between the query area Q and the target geometry T. It gives a ratio from 0 to 1 where 0 means no overlap at all and 1 a perfect fit fq - Adds a filter that force the value returned by the previous function to be between 0 and 1, effectively applying the spatial filter. ''' variables =dict( x11=bbox['minx'], x12=bbox['maxx'], y11=bbox['miny'], y12=bbox['maxy'], x21='minx', x22='maxx', y21='miny', y22='maxy', area_search = abs(bbox['maxx'] - bbox['minx']) * abs(bbox['maxy'] - bbox['miny']) ) bf = '''div( mul( mul(max(0, sub(min({x12},{x22}) , max({x11},{x21}))), max(0, sub(min({y12},{y22}) , max({y11},{y21}))) ), 2), add({area_search}, mul(sub({y22}, {y21}), sub({x22}, {x21}))) )'''.format(**variables).replace('\n','').replace(' ','') search_params['fq_list'] = ['{!frange incl=false l=0 u=1}%s' % bf] search_params['bf'] = bf search_params['defType'] = 'edismax' return search_params def _params_for_solr_spatial_field_search(self, bbox, search_params): ''' This will add an fq filter with the form: +spatial_geom:"Intersects({minx} {miny} {maxx} {maxy}) ''' search_params['fq_list'] = search_params.get('fq_list', []) search_params['fq_list'].append('+spatial_geom:"Intersects({minx} {miny} {maxx} {maxy})"' .format(minx=bbox['minx'],miny=bbox['miny'],maxx=bbox['maxx'],maxy=bbox['maxy'])) return search_params def _params_for_postgis_search(self, bbox, search_params): # Note: This will be deprecated at some point in favour of the # Solr 4 spatial sorting capabilities if search_params.get('sort') == 'spatial desc' and \ p.toolkit.asbool(config.get('ckanext.spatial.use_postgis_sorting', 'False')): if search_params['q'] or search_params['fq']: raise SearchError('Spatial ranking cannot be mixed with other search parameters') # ...because it is too inefficient to use SOLR to filter # results and return the entire set to this class and # after_search do the sorting and paging. extents = bbox_query_ordered(bbox) are_no_results = not extents search_params['extras']['ext_rows'] = search_params['rows'] search_params['extras']['ext_start'] = search_params['start'] # this SOLR query needs to return no actual results since # they are in the wrong order anyway. We just need this SOLR # query to get the count and facet counts. rows = 0 search_params['sort'] = None # SOLR should not sort. # Store the rankings of the results for this page, so for # after_search to construct the correctly sorted results rows = search_params['extras']['ext_rows'] = search_params['rows'] start = search_params['extras']['ext_start'] = search_params['start'] search_params['extras']['ext_spatial'] = [ (extent.package_id, extent.spatial_ranking) \ for extent in extents[start:start+rows]] else: extents = bbox_query(bbox) are_no_results = extents.count() == 0 if are_no_results: # We don't need to perform the search search_params['abort_search'] = True else: # We'll perform the existing search but also filtering by the ids # of datasets within the bbox bbox_query_ids = [extent.package_id for extent in extents] q = search_params.get('q','').strip() or '""' new_q = '%s AND ' % q if q else '' new_q += '(%s)' % ' OR '.join(['id:%s' % id for id in bbox_query_ids]) search_params['q'] = new_q return search_params def after_search(self, search_results, search_params): # Note: This will be deprecated at some point in favour of the # Solr 4 spatial sorting capabilities if search_params.get('extras', {}).get('ext_spatial') and \ p.toolkit.asbool(config.get('ckanext.spatial.use_postgis_sorting', 'False')): # Apply the spatial sort querier = PackageSearchQuery() pkgs = [] for package_id, spatial_ranking in search_params['extras']['ext_spatial']: # get package from SOLR pkg = querier.get_index(package_id)['data_dict'] pkgs.append(json.loads(pkg)) search_results['results'] = pkgs return search_results class CatalogueServiceWeb(p.SingletonPlugin): p.implements(p.IConfigurable) p.implements(p.IRoutes) def configure(self, config): config.setdefault("cswservice.title", "Untitled Service - set cswservice.title in config") config.setdefault("cswservice.abstract", "Unspecified service description - set cswservice.abstract in config") config.setdefault("cswservice.keywords", "") config.setdefault("cswservice.keyword_type", "theme") config.setdefault("cswservice.provider_name", "Unnamed provider - set cswservice.provider_name in config") config.setdefault("cswservice.contact_name", "No contact - set cswservice.contact_name in config") config.setdefault("cswservice.contact_position", "") config.setdefault("cswservice.contact_voice", "") config.setdefault("cswservice.contact_fax", "") config.setdefault("cswservice.contact_address", "") config.setdefault("cswservice.contact_city", "") config.setdefault("cswservice.contact_region", "") config.setdefault("cswservice.contact_pcode", "") config.setdefault("cswservice.contact_country", "") config.setdefault("cswservice.contact_email", "") config.setdefault("cswservice.contact_hours", "") config.setdefault("cswservice.contact_instructions", "") config.setdefault("cswservice.contact_role", "") config["cswservice.rndlog_threshold"] = float(config.get("cswservice.rndlog_threshold", "0.01")) def before_map(self, route_map): c = "ckanext.spatial.controllers.csw:CatalogueServiceWebController" route_map.connect("/csw", controller=c, action="dispatch_get", conditions={"method": ["GET"]}) route_map.connect("/csw", controller=c, action="dispatch_post", conditions={"method": ["POST"]}) return route_map def after_map(self, route_map): return route_map class HarvestMetadataApi(p.SingletonPlugin): ''' Harvest Metadata API (previously called "InspireApi") A way for a user to view the harvested metadata XML, either as a raw file or styled to view in a web browser. ''' p.implements(p.IRoutes) def before_map(self, route_map): controller = "ckanext.spatial.controllers.api:HarvestMetadataApiController" # Showing the harvest object content is an action of the default # harvest plugin, so just redirect there route_map.redirect('/api/2/rest/harvestobject/{id:.*}/xml', '/harvest/object/{id}', _redirect_code='301 Moved Permanently') route_map.connect('/harvest/object/{id}/original', controller=controller, action='display_xml_original') route_map.connect('/harvest/object/{id}/html', controller=controller, action='display_html') route_map.connect('/harvest/object/{id}/html/original', controller=controller, action='display_html_original') # Redirect old URL to a nicer and unversioned one route_map.redirect('/api/2/rest/harvestobject/:id/html', '/harvest/object/{id}/html', _redirect_code='301 Moved Permanently') return route_map def after_map(self, route_map): return route_map<file_sep>/* Module for handling the spatial querying */ L.Icon.Default.imagePath = '../img/leaflet'; this.ckan.module('geolocalization', function ($, _) { return { options: { i18n: { }, style: { color: '#F06F64', weight: 2, opacity: 1, fillColor: '#F06F64', fillOpacity: 0.1 }, default_extent: [[90, 180], [-90, -180]] }, template: {}, initialize: function () { var module = this; $.proxyAll(this, /_on/); var user_default_extent = this.el.data('default_extent'); if (user_default_extent ){ if (user_default_extent instanceof Array) { // Assume it's a pair of coords like [[90, 180], [-90, -180]] this.options.default_extent = user_default_extent; } else if (user_default_extent instanceof Object) { // Assume it's a GeoJSON bbox this.options.default_extent = new L.GeoJSON(user_default_extent).getBounds(); } } this.options.messageGeoJsonNotValid = this.el.attr('messageGeoJsonNotValid'); this.el.ready(this._onReady); }, _getParameterByName: function (name) { var match = RegExp('[?&]' + name + '=([^&]*)') .exec(window.location.search); return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null; }, _drawExtentFromCoords: function(xmin, ymin, xmax, ymax) { if ($.isArray(xmin)) { var coords = xmin; xmin = coords[0]; ymin = coords[1]; xmax = coords[2]; ymax = coords[3]; } return new L.Rectangle([[ymin, xmin], [ymax, xmax]], this.options.style); }, _drawExtentFromGeoJSON: function(geom) { return new L.GeoJSON(geom, {style: this.options.style}); }, _onReady: function() { var module = this; var map; var extentLayer; var previous_box; var previous_extent; var is_exanded = false; var should_zoom = true; var buttons; //Aggiunto evento per sincronizzazione su mappa $('#field-spatial').on("blur", syncroMap ) // OK map time map = ckan.commonLeafletMap('geolocalization-map-container', this.options.map_config, {attributionControl: false}); var drawnItems = new L.FeatureGroup(); map.addLayer(drawnItems); // Initialize the draw control map.addControl(new L.Control.Draw({ draw: { polyline: { metric: true }, polygon: { allowIntersection: false, showArea: true, drawError: { color: '#b00b00', timeout: 1000 }, shapeOptions: { color: '#bada55' } }, rectangle: false, circle: false, marker: true }, edit: { featureGroup: drawnItems, remove: true } })); map.on('draw:created', function (e) { var type = e.layerType, layer = e.layer; /*if (type === 'marker') { layer.bindPopup('A popup!'); }*/ $('#field-spatial')[0].value = JSON.stringify(layer.toGeoJSON().geometry); drawnItems.clearLayers(); drawnItems.addLayer(layer); }); map.on('draw:edited', function (e) { $('#field-spatial')[0].value = JSON.stringify(drawnItems.getLayers()[0].toGeoJSON().geometry); }); map.on('draw:deleted', function (e) { $('#field-spatial')[0].value = ''; }); if ($('#field-spatial')[0].value != '') { syncroMap(); } // Record the current map view so we can replicate it after submitting map.on('moveend', function(e) { $('#ext_prev_extent').val(map.getBounds().toBBoxString()); }); $('#mapDiv').show(); // Ok setup the default state for the map var previous_bbox; setPreviousBBBox(); setPreviousExtent(); $('#mapDiv').hide(); // OK, when we expand we shouldn't zoom then map.on('zoomstart', function(e) { should_zoom = false; }); // Is there an existing box from a previous search? function setPreviousBBBox() { previous_bbox = module._getParameterByName('ext_bbox'); if (previous_bbox) { $('#ext_bbox').val(previous_bbox); extentLayer = module._drawExtentFromCoords(previous_bbox.split(',')) map.addLayer(extentLayer); map.fitBounds(extentLayer.getBounds()); } } // Is there an existing extent from a previous search? function setPreviousExtent() { previous_extent = module._getParameterByName('ext_prev_extent'); if (previous_extent) { coords = previous_extent.split(','); map.fitBounds([[coords[1], coords[0]], [coords[3], coords[2]]]); } else { if (!previous_bbox){ map.fitBounds(module.options.default_extent); } } } function syncroMap() { var json = null; try { json = jQuery.parseJSON($('#field-spatial')[0].value); } catch (e) { alert(module.options.messageGeoJsonNotValid); return; } drawnItems.clearLayers(); var geoJsonLayer = L.geoJson(json, {}); if (geoJsonLayer.getLayers().length > 0){ if (geoJsonLayer.getLayers()[0].feature.geometry.type == 'Polygon') { var layer = L.polygon( geoJsonLayer.getLayers()[0].getLatLngs(), {} ) drawnItems.addLayer(layer); } else if (geoJsonLayer.getLayers()[0].feature.geometry.type == 'LineString') { var layer = L.polyline( geoJsonLayer.getLayers()[0].getLatLngs(), {} ) drawnItems.addLayer(layer); } else if (geoJsonLayer.getLayers()[0].feature.geometry.type == 'Point') { var layer = L.marker( geoJsonLayer.getLayers()[0].getLatLng(), {} ) drawnItems.addLayer(layer); } else { alert(module.options.messageGeoJsonNotValid); } } } // Reset map view function resetMap() { L.Util.requestAnimFrame(map.invalidateSize, map, !1, map._container); } // Add the loading class and submit the form function submitForm() { setTimeout(function() { form.submit(); }, 800); } var QueryString = function () { // This function is anonymous, is executed immediately and // the return value is assigned to QueryString! var query_string = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); // If first entry with this name if (typeof query_string[pair[0]] === "undefined") { query_string[pair[0]] = pair[1]; // If second entry with this name } else if (typeof query_string[pair[0]] === "string") { var arr = [ query_string[pair[0]], pair[1] ]; query_string[pair[0]] = arr; // If third or later entry with this name } else { query_string[pair[0]].push(pair[1]); } } return query_string; } (); // Simulating click on expand button if(QueryString._exp=='true') $('.leaflet-control-draw a', module.el).click(); } } }); /* PAOLO: added for comobox comuni */ var comuni = document.getElementById('field-comuni'); for (var i = getcomuni().length - 1; i >= 0; i--) { var current = getcomuni()[i]; var option = document.createElement("option"); option.text = current.display; option.value = current.nome; comuni.add(option); } comuni.onchange = function() { var selected = comuni.options[comuni.selectedIndex].value; for (var i = getcomuni().length - 1; i >= 0; i--) { var current = getcomuni()[i]; if(current.nome==selected){ $('#field-spatial')[0].value = JSON.stringify(current.geometry); if ("createEvent" in document) { var evt = document.createEvent("HTMLEvents"); evt.initEvent("blur", false, true); $('#field-spatial')[0].dispatchEvent(evt); } else $('#field-spatial')[0].fireEvent("onblur"); break; } }; } function getcomuni(){ var geojson_comuni = '[{"nome":"roma","display":"Roma","geometry":{"type": "Polygon","coordinates": [[[12.3486328125,41.78462507573973],[12.3486328125,41.999304591234996],[12.627410888671875,41.999304591234996],[12.627410888671875, 41.78462507573973],[12.3486328125,41.78462507573973 ]]]}}, {"nome":"latina","display":"Latina","geometry":{"type": "Polygon","coordinates": [[[ 12.77435302734375, 41.37165592008984], [ 12.77435302734375, 41.545589036668105 ], [ 13.039398193359375, 41.545589036668105 ], [ 13.039398193359375, 41.37165592008984 ], [12.77435302734375, 41.37165592008984 ]] ]}}]'; return eval('(' + geojson_comuni + ')'); }<file_sep>// recline preview module var current_lang = parent.document.getElementById("current-lang").innerHTML; this.ckan.module('reclinepreview', function (jQuery, _) { return { options: { i18n: { errorLoadingPreview: "Could not load preview", errorDataProxy: "DataProxy returned an error", errorDataStore: "DataStore returned an error", previewNotAvailableForDataType: "Preview not available for data type: " }, site_url: "" }, initialize: function () { jQuery.proxyAll(this, /_on/); this.el.ready(this._onReady); // hack to make leaflet use a particular location to look for images L.Icon.Default.imagePath = this.options.site_url + 'js/vendor/leaflet/images'; //Inizializzazione dei parametri di pagina this.options.user = this.el.attr('user'); this.options.id_dataset = this.el.attr('id_dataset'); this.options.id_risorsa = this.el.attr('id_risorsa'); this.options.messagePuntualPropositionInsert = this.el.attr('message_puntual_proposition_insert'); this.options.messagePropositionDescription = this.el.attr('message_proposition_description'); this.options.message_description = this.el.attr('message_description'); this.options.message_user=this.el.attr('message_user'); this.options.message_status=this.el.attr('message_status'); }, _onReady: function() { this.loadPreviewDialog(preload_resource); }, // **Public: Loads a data preview** // // Fetches the preview data object from the link provided and loads the // parsed data from the webstore displaying it in the most appropriate // manner. // // link - Preview button. // // Returns nothing. loadPreviewDialog: function (resourceData) { var self = this; function showError(msg){ msg = msg || _('error loading preview'); window.parent.ckan.pubsub.publish('data-viewer-error', msg); } recline.Backend.DataProxy.timeout = 10000; // will no be necessary any more with https://github.com/okfn/recline/pull/345 recline.Backend.DataProxy.dataproxy_url = '//jsonpdataproxy.appspot.com'; // 2 situations // a) something was posted to the datastore - need to check for this // b) csv or xls (but not datastore) resourceData.formatNormalized = this.normalizeFormat(resourceData.format); resourceData.url = this.normalizeUrl(resourceData.url); if (resourceData.formatNormalized === '') { var tmp = resourceData.url.split('/'); tmp = tmp[tmp.length - 1]; tmp = tmp.split('?'); // query strings tmp = tmp[0]; var ext = tmp.split('.'); if (ext.length > 1) { resourceData.formatNormalized = ext[ext.length-1]; } } var errorMsg, dataset; if (resourceData.datastore_active) { resourceData.backend = 'ckan'; // Set endpoint of the resource to the datastore api (so it can locate // CKAN DataStore) resourceData.endpoint = jQuery('body').data('site-root') + 'api'; dataset = new recline.Model.Dataset(resourceData); errorMsg = this.options.i18n.errorLoadingPreview + ': ' + this.options.i18n.errorDataStore; dataset.fetch() .done(function(dataset){ self.initializeDataExplorer(dataset); }) .fail(function(error){ if (error.message) errorMsg += ' (' + error.message + ')'; showError(errorMsg); }); } else if (resourceData.formatNormalized in {'csv': '', 'xls': ''}) { // set format as this is used by Recline in setting format for DataProxy resourceData.format = resourceData.formatNormalized; resourceData.backend = 'dataproxy'; dataset = new recline.Model.Dataset(resourceData); errorMsg = this.options.i18n.errorLoadingPreview + ': ' +this.options.i18n.errorDataProxy; dataset.fetch() .done(function(dataset){ dataset.bind('query:fail', function (error) { jQuery('.data-view-container', self.el).hide(); jQuery('.header', self.el).hide(); }); self.initializeDataExplorer(dataset); }) .fail(function(error){ if (error.message) errorMsg += ' (' + error.message + ')'; showError(errorMsg); }); } }, initializeDataExplorer: function (dataset) { var self = this; var ricerca = parent.$("#field-geometric-search"); var mapView = new recline.View.Map({ model: dataset }); var views = [ { id: 'grid', label: 'Grid', view: new recline.View.SlickGrid({ model: dataset }) }, { id: 'map', label: 'Map', view: mapView } ]; var sidebarViews = [ { id: 'valueFilter', label: 'Filters', view: new recline.View.ValueFilter({ model: dataset }) } ]; var dataExplorer = new recline.View.MultiView({ el: this.el, model: dataset, views: views, sidebarViews: sidebarViews, config: { readOnly: true } }); var layers = {}; layers.drawnItems = new L.FeatureGroup(); layers.markersLayer = new L.FeatureGroup(); mapView.map.addLayer(layers.drawnItems); mapView.map.addLayer(layers.markersLayer); mapView.map.setView([41.9737037522, 12.7773122216], 8); ricerca.on("select2-selecting", function(e){ var coordinates = e.val.split(" "); if (coordinates.length > 1) { dataExplorer.updateNav("map"); layers.markersLayer.clearLayers(); L.marker([coordinates[0], coordinates[1]]).addTo(layers.markersLayer).bindPopup(e.object.text).openPopup(); mapView.map.fitBounds([[coordinates[0], coordinates[1]],[coordinates[0], coordinates[1]]]); mapView.map.zoomOut(4); e.object.id=""; } }); var yellowIcon = L.icon({ iconUrl: L.Icon.Default.imagePath + '/marker-icon-yellow.png', iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34] }); var greenIcon = L.icon({ iconUrl: L.Icon.Default.imagePath + '/marker-icon-green.png', iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34] }); var baseUrl = "http://" + document.domain; // Initialize the WFST layer layers.commentApproved = L.wfst( null,{ // Required url : baseUrl + '/LaitExtension-hook/api/service/wfsProxy?targetUrl=' + baseUrl + '/geoserver/wfs', featureNS : 'opendata', featureType : 'comment', primaryKeyField : 'id', onEachFeature: function (feature, layer) { if (feature.properties) { var popupContent; popupContent = "<table><tr><td><b>"+self.options.message_description+" :</b></td><td>" + feature.properties.testo + "</td></tr>"+ "<tr><td><b>"+self.options.message_user+" :</b></td><td>" + feature.properties.id_utente + "</td></tr>"; if (feature.properties.stato && feature.properties.stato == "NOT APPROVED") { popupContent += "<tr><td><b>"+self.options.message_status+" :</b></td><td>" + feature.properties.stato + "</td></tr>"; } popupContent +="</table>"; } layer.bindPopup(popupContent); }, pointToLayer: function (feature, latlng) { var marker = L.marker(latlng, {icon: yellowIcon}); marker.on('add', function (evt){ L.DomUtil.addClass(evt.target._icon, "commentPoint"); $(evt.target._icon).hide(); }, this); return marker; }, wfsFilter: '<Filter>'+ '<And>'+ '<PropertyIsEqualTo><PropertyName>id_dataset</PropertyName><Literal>'+self.options.id_dataset+'</Literal></PropertyIsEqualTo>'+ '<PropertyIsEqualTo><PropertyName>id_risorsa</PropertyName><Literal>'+self.options.id_risorsa+'</Literal></PropertyIsEqualTo>'+ '<Or>'+ '<PropertyIsEqualTo><PropertyName>stato</PropertyName><Literal>APPROVED</Literal></PropertyIsEqualTo>'+ '<PropertyIsEqualTo><PropertyName>id_utente</PropertyName><Literal>'+self.options.user+'</Literal></PropertyIsEqualTo>'+ '</Or>'+ '</And>'+ '</Filter>' }).addTo(mapView.map); // Initialize the draw control and pass it the // FeatureGroup of editable layers L.drawLocal.draw.toolbar.buttons.marker = self.options.messagePuntualPropositionInsert; var drawControl = new L.Control.Draw({ draw : { polyline : false, polygon : false, circle : false, rectangle : false, marker : {icon: greenIcon} }, edit : { featureGroup : layers.drawnItems, edit : false, remove: false } }); mapView.map.addControl(drawControl); $('.leaflet-draw').hide(); /** ------- Funzioni sovrascritte per gestione specifica dei popup ----- */ mapView.map.openPopup = function (popup, latlng, options) { this.closePopup(); if (!(popup instanceof L.Popup)) { var content = popup; popup = new L.Popup(options) .setLatLng(latlng) .setContent(content); } popup._isOpen = true; this._popup = popup; var returnPopup = this.addLayer(popup); if (popup.descrizione) { $('#miglioraDatoInputText')[0].value = popup.descrizione; } $("#miglioraDatoInput" ).on("click", function() { layers.drawnItems.getLayers()[0].feature.properties['testo'] = $('#miglioraDatoInputText')[0].value; var currentLayer = layers.drawnItems.getLayers()[0]; //Copia l'oggetto come feature nel layer del wfst var newFeature = currentLayer.toGeoJSON(); newFeature.id = 'comment.0'; newFeature.type = "Feature"; newFeature.geometry_name= "the_geom"; newFeature._wfstSaved=false; layers.commentApproved.addData(newFeature); currentLayer.closePopup(); mapView.map.removeLayer(currentLayer); var feature = currentLayer.feature; var popupContent = "<table><tr><td><b>"+self.options.message_description+" :</b></td><td>" + feature.properties.testo + "</td></tr>"+ "<tr><td><b>"+self.options.message_user+" :</b></td><td>" + feature.properties.id_utente + "</td></tr>"+ "<tr><td><b>"+self.options.message_status+" :</b></td><td>" + feature.properties.stato + "</td></tr>"+ "</table>"; var justInserted = layers.commentApproved.getLayers().length-1; layers.commentApproved.getLayers()[justInserted].bindPopup(popupContent); layers.commentApproved.getLayers()[justInserted].addTo(mapView.map); $('.commentPoint').show(); }); $("#miglioraDatoAnnullaInput" ).on("click", function() { var currentLayer = layers.drawnItems.getLayers()[0]; currentLayer.closePopup(); mapView.map.removeLayer(currentLayer); }); return returnPopup; }; mapView.map.closePopup = function (popup) { if ($('#miglioraDatoInputText').length > 0 && popup) { popup.descrizione = $('#miglioraDatoInputText')[0].value; } if (!popup || popup === this._popup) { popup = this._popup; this._popup = null; } if (!this.oldDescrizione && popup) { this.oldDescrizione = popup.descrizione; } if (popup) { this.removeLayer(popup); popup._isOpen = false; } return this; }; /** -------------------------------------------------------------- */ mapView.map.on('draw:created', function (e) { var layer = e.layer; layers.drawnItems.clearLayers(); if (!layer.feature) { layer.feature = {}; } if (!layer.feature.properties) { layer.feature.properties = {}; } layer.feature.properties['id_dataset'] = self.options.id_dataset; layer.feature.properties['id_risorsa'] = self.options.id_risorsa; layer.feature.properties['stato'] = 'NOT APPROVED'; layer.feature.properties['id_utente'] = self.options.user; layers.drawnItems.addLayer(layer); L.DomUtil.addClass(layer._icon, "commentPoint"); var popup = e.layer.bindPopup('<label for="miglioraDatoInputText">'+self.options.messagePropositionDescription+'</label><input id="miglioraDatoInputText" type="text"/></br><input class="btn" id="miglioraDatoInput" type="button" value="Salva"/><input class="btn" id="miglioraDatoAnnullaInput" type="button" value="Annulla"/>',{closeButton:false,closeOnClick: false}).openPopup(); }); var improveButton = $('#improve', parent.document.body); improveButton.click( function() { if (improveButton.attr('class').indexOf('active')>=0) { $('.leaflet-draw').show(); $('.commentPoint').show(); } else { $('.leaflet-draw').hide(); $('.commentPoint').hide(); mapView.map.closePopup(); } }); }, normalizeFormat: function (format) { var out = format.toLowerCase(); out = out.split('/'); out = out[out.length-1]; return out; }, normalizeUrl: function (url) { if (url.indexOf('https') === 0) { return 'http' + url.slice(5); } else { return url; } } }; }); <file_sep>var requestObj = false; if (window.XMLHttpRequest) { requestObj = new XMLHttpRequest(); } else if (window.ActiveXObject) { requestObj = new ActiveXObject("Microsoft.XMLHTTP"); } if(document.getElementById("user")!=undefined){ var user = document.getElementById("user").innerHTML; var api_key = document.getElementById("api-key").innerHTML; //alert(user+' '+api_key); if(user != ''){ //enabling the rating document.getElementById("star5").addEventListener('click', function (){ rate(5)}); document.getElementById("star4").addEventListener('click', function (){ rate(4)}); document.getElementById("star3").addEventListener('click', function (){ rate(3)}); document.getElementById("star2").addEventListener('click', function (){ rate(2)}); document.getElementById("star1").addEventListener('click', function (){ rate(1)}); }else{ //if no user is logged in the rating is disabled document.querySelector('.rating-new').className = "rating-new-disabled"; } //getting the current rate (with no params) rate(); } function rate(star_num){ if (requestObj) { var ds = window.location.pathname; ds = ds.substring(ds.lastIndexOf("/")+1); var query = 'ds='+ds; var method = 'GET'; if(user!='') query = query + '&user='+user; if(star_num!=undefined) { //insert new rate method = 'POST'; query = query + '&rating='+star_num; } doAjax(method, '/CKANAPIExtension/', 'rate', query, null, true, function(result){ //alert(result); var rating_obj = eval('(' + result + ')'); //reset current rating document.querySelector("#star5").className = ""; document.querySelector("#star4").className = ""; document.querySelector("#star3").className = ""; document.querySelector("#star2").className = ""; document.querySelector("#star1").className = ""; //show the current/updated rating if(rating_obj.rating>0) document.querySelector('#star'+rating_obj.rating).className = "rating-new-selected"; } ); } } function doAjax(method, host, service, query, data, asynch, callback){ var requestObj = false; if (window.XMLHttpRequest) { requestObj = new XMLHttpRequest(); } else if (window.ActiveXObject) { requestObj = new ActiveXObject("Microsoft.XMLHTTP"); } if (requestObj) { //document.getElementsByTagName("body")[0].className = "loading"; $('#loaderModal').modal('show'); requestObj.onreadystatechange = function (){ if (requestObj.readyState == 4){ try { if (requestObj.status == 200){ var result = requestObj.responseText; if(callback) callback(result); }else if(requestObj.status == 500){ //alert(requestObj.responseText); } }catch(err){ //alert(err); }finally{ $('#loaderModal').modal('hide'); } } }; requestObj.open(method, host+service+'?'+query, asynch); requestObj.setRequestHeader("Content-type", "application/json"); requestObj.setRequestHeader("Authorization", api_key); requestObj.send(data); } }
ef2f8d0f801bc6fde071901bb014e108841a14bd
[ "Markdown", "Python", "JavaScript", "HTML" ]
22
Python
lynxlab/ckanext-lait
baee73a89ca587c391befaf9a95f070ff77f49ec
220ccf4e3c0f70a44da2741a3db3a07a24471f2a
refs/heads/master
<repo_name>TycXdd/CarDemo1<file_sep>/src/main/java/com/qfedu/demo/user/dao/IOrderDao.java package com.qfedu.demo.user.dao; import com.qfedu.demo.user.pojo.Order; import com.qfedu.demo.user.pojo.VOrder; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface IOrderDao { int add(Order order); List<VOrder> selectAll(Integer uid); } <file_sep>/src/main/java/com/qfedu/demo/user/pojo/VCity.java package com.qfedu.demo.user.pojo; public class VCity { private City getCity; private City backCity; public City getGetCity() { return getCity; } public void setGetCity(City getCity) { this.getCity = getCity; } public City getBackCity() { return backCity; } public void setBackCity(City backCity) { this.backCity = backCity; } @Override public String toString() { return "VCity{" + "getCity=" + getCity + ", backCity=" + backCity + '}'; } } <file_sep>/src/main/java/com/qfedu/demo/user/controller/UserController.java package com.qfedu.demo.user.controller; import com.qfedu.demo.common.JsonBean; import com.qfedu.demo.common.JsonUtils; import com.qfedu.demo.user.pojo.Code; import com.qfedu.demo.user.pojo.User; import com.qfedu.demo.user.service.IUserService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; @Controller @RequestMapping("/user") public class UserController { private static final Logger logger = LogManager.getLogger(UserController.class); @Autowired private IUserService userService; // /* 用户注册 */ // @RequestMapping("/add") // public String insert(User user) { // userService.insert(user); // return "page/register"; // } /* 用户注册 */ @RequestMapping("/add") @ResponseBody public Code insert(User user) { userService.insert(user); Code code = new Code(); code.setCode(1); return code; } /* UserInfo */ @RequestMapping("/denglu") @ResponseBody public JsonBean denglu(HttpSession session) { JsonBean bean = null; User user = (User) session.getAttribute("user"); if (user == null) { bean = JsonUtils.createJsonBean(0, 0); } else { bean = JsonUtils.createJsonBean(1, user); } return bean; } /* 修改用户Tel */ @RequestMapping("/update") @ResponseBody public JsonBean update(HttpSession session, String tel) { JsonBean bean = null; User user = (User) session.getAttribute("user"); user.setTel(tel); try { if (user.getId() != null) { userService.update(user); bean = JsonUtils.createJsonBean(1, "修改成功!"); } else { bean = JsonUtils.createJsonBean(1, "未登录"); } } catch (Exception e) { bean = JsonUtils.createJsonBean(0, e.getMessage()); } return bean; } /* 用户登录 */ @RequestMapping("/login") @ResponseBody public Code login(User user, HttpSession session) { User user1 = userService.login(user.getTel()); Code code = new Code(); logger.info(user1); if (user1 != null && user.getPassword().equals(user1.getPassword())) { session.setAttribute("user", user1); code.setCode(1); return code; } else { code.setCode(2); code.setResult("账号或密码错误"); return code; } } @RequestMapping("/index") public String index2() { return "index"; } @RequestMapping("/shortrent") @ResponseBody public String shortrent() { return "shortrent"; } } <file_sep>/src/main/java/com/qfedu/demo/user/dao/IUserDao.java package com.qfedu.demo.user.dao; import com.qfedu.demo.user.pojo.User; import org.springframework.stereotype.Repository; @Repository public interface IUserDao { public void insert(User user); // public User getTel(String tel); public User login(String tel); int update(User user); // int delete(User user); // // public User selectByPrimaryKey(Integer id); } <file_sep>/src/main/java/com/qfedu/demo/user/service/Impl/UserServiceImpl.java package com.qfedu.demo.user.service.Impl; import com.qfedu.demo.user.dao.IUserDao; import com.qfedu.demo.user.pojo.User; import com.qfedu.demo.user.service.IUserService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements IUserService { public static final Logger logger = LogManager.getLogger(UserServiceImpl.class); @Autowired private IUserDao userDao; @Override public void insert(User user) { userDao.insert(user); } @Override public User login(String tel) { return userDao.login(tel); } @Override public void update(User user) { userDao.update(user); } } <file_sep>/src/main/java/com/qfedu/demo/sysView/ViewController.java package com.qfedu.demo.sysView; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ViewController { @RequestMapping("/") public String index1() { return "page/index"; } @RequestMapping("/index") public String index2() { return "page/index"; } @RequestMapping("/login") public String login() { return "page/login"; } // @RequestMapping("/loginSuccess") // public String loginSuccess() { // return "page/loginsuccess"; // } @RequestMapping("/mymain") public String mymain() { return "myMain/mymain"; } @RequestMapping("/myinfo") public String myinfo() { return "myMain/myinfo"; } } <file_sep>/src/main/java/com/qfedu/demo/user/service/ICityService.java package com.qfedu.demo.user.service; import com.qfedu.demo.user.pojo.City; import com.qfedu.demo.user.pojo.VCity; import java.util.List; public interface ICityService { public List<City> select(int pid); VCity selectPrimaryKey (Integer getid, Integer backid); } <file_sep>/src/main/java/com/qfedu/demo/user/service/Impl/CityServiceImpl.java package com.qfedu.demo.user.service.Impl; import com.qfedu.demo.user.dao.ICityDao; import com.qfedu.demo.user.pojo.City; import com.qfedu.demo.user.pojo.VCity; import com.qfedu.demo.user.service.ICityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CityServiceImpl implements ICityService { @Autowired private ICityDao cityDao; @Override public List<City> select(int pid) { return cityDao.select(pid); } @Override public VCity selectPrimaryKey(Integer getid, Integer backid) { City getCity = cityDao.selectPrimaryKey(getid); City backCity = cityDao.selectPrimaryKey(backid); VCity vcity = new VCity(); vcity.setGetCity(getCity); vcity.setBackCity(backCity); return vcity; } } <file_sep>/src/main/java/com/qfedu/demo/user/service/IUserService.java package com.qfedu.demo.user.service; import com.qfedu.demo.user.pojo.User; public interface IUserService { public void insert(User user); // public User login(User user); public User login(String tel); public void update(User user); // public void delete(User user); // public User selectByPrimaryKey(Integer id); } <file_sep>/src/main/java/com/qfedu/demo/sysView/sysInterceptor.java package com.qfedu.demo.sysView; import com.qfedu.demo.user.pojo.User; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class sysInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { Object User = httpServletRequest.getSession().getAttribute("user"); if (User != null) { return true; } else { httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/index"); } return false; // HttpSession session = httpServletRequest.getSession(false); // User user = (User) session.getAttribute("user"); // String contextPath = httpServletRequest.getContextPath(); // if (user == null) { // httpServletResponse.sendRedirect(contextPath + "/"); // // } else { // if (user == null) { // httpServletResponse.sendRedirect(contextPath + "/"); // } else { // return true; // } // } // return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
924913affd615874a641f62ff99763cd45b9ded3
[ "Java" ]
10
Java
TycXdd/CarDemo1
a520351d4929f31968a706a9989bb41c33d19bba
a2a143ab810573464a3337ae7be71dfd282d1c70
refs/heads/master
<file_sep>package com.xxxx.seckill.service; import com.baomidou.mybatisplus.extension.service.IService; import com.xxxx.seckill.pojo.User; import com.xxxx.seckill.vo.LoginVo; import com.xxxx.seckill.vo.RespBean; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public interface IUserService extends IService<User> { RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response); User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response); RespBean updatePassword(String userTicket, String password, HttpServletRequest request, HttpServletResponse response); } <file_sep>package com.xxxx.seckill.service; import com.baomidou.mybatisplus.extension.service.IService; import com.xxxx.seckill.pojo.Goods; import com.xxxx.seckill.pojo.Order; import com.xxxx.seckill.pojo.User; import com.xxxx.seckill.vo.OrderDetailVo; /** * <p> * 服务类 * </p> * * @author muggle * @since 2021-07-29 */ public interface IOrderService extends IService<Order> { Order seckill(User user, Goods goods); OrderDetailVo detail(Long orderId); }
bd19df021ffe379ecbdb71d7eb3ac5a70c7a91cf
[ "Java" ]
2
Java
muggle1997/project_sigma
83c4d6f6bb91451a6ef73dfb9658a89140490328
a59a22b30e86ba34711592c762cebf9c83af817d
refs/heads/master
<repo_name>wrf/map_code_in_R<file_sep>/europe_map.R # experimentation with world maps library(maps) library(mapdata) # needed for Hires ( hi-res ) grayscale = colorRampPalette(c("#999999","#eeeeee"))(4) png(filename="~/git/map_code_in_R/images/test_world_map.png", width=800,height=400) map('world', fill=TRUE, col=grayscale, mar=c(1,1,1,1)) dev.off() oceancol = "#4466bb" # make map of europe png(filename="~/git/map_code_in_R/images/test_europe_map.png", width=600,height=600) map('world', ylim=c(30,60), xlim=c(-10,30), fill=TRUE, col=grayscale, mar=c(1,1,1,1)) dev.off() png(filename="~/git/map_code_in_R/images/test_europe_map_blue_bg_cities.png", width=600,height=600) map('worldHires', ylim=c(40,55), xlim=c(-5,18), fill=TRUE, col=grayscale, mar=c(1,1,1,1), bg=oceancol) points(11.566,48.133, pch=18, cex=3, col="#0098d4") text(11.566,48.633,"LMU") dev.off() slats = c(49.4166,48.783,47.586331,43.2964) slons = c(08.716,09.183,9.5988717,5.37) citynames = c("Heidelberg","Stuttgart","Kressbronn","Marseille") points(slons, slats, pch=19, col="#ee8400", cex=3) text(slons+0.5, slats, citynames, pos=4) # to plot swiss flag on geneva points(6.15,46.20, pch=15, col="red", cex=3) points(6.15,46.20, pch=3, col="white", cex=1.1, lwd=4) # to plot swiss flag on zurich points(8.55,47.366, pch=15, col="red", cex=3) points(8.55,47.366, pch=3, col="white", cex=1.1, lwd=4) dummymap = map("world") which(dummymap$names=="Russia") # [1] 1323 whitevec = rep("#ffffff",1679) whitevec[1323]="green" # colored world map by index countries = c("Italy", "Russia", "Germany", "Brazil") countrynums = match(countries, dummymap$names) vecbycountry = rep("#ffffff",length(dummymap$names)) vecbycountry[countrynums]="green" euromap = map("world", ylim=c(30,60), xlim=c(-10,30), mar=c(1,1,1,1)) #countries = c("Italy", "Russia", "Germany", "UK:Great Britain", "UK:Northern Ireland") ukisles = grep("UK", euromap$names) euronums = match(countries, euromap$names) vecbycountry = rep("#ffffff",length(euromap$names) ) vecbycountry[euronums]="green" lakes = match("Lake Constance", euromap$names) vecbycountry[lakes]=oceancol euromap = map("world", fill=TRUE, ylim=c(30,60), xlim=c(-10,30), mar=c(1,1,1,1), col=vecbycountry, bg=oceancol ) # colored europe by OECD phd data png(filename="~/git/images/test_europe_map_oecd_phd_by_country_w_islands.png", width=600,height=600) euromap = map("world", ylim=c(35,65), xlim=c(-10,35), mar=c(1,1,1,1)) phdsbycountry = read.table("~/git/map_code_in_R//data/oecd_phds_by_country.csv",header=TRUE,sep=",") phdsnoNA = phdsbycountry[phdsbycountry[,4]>0,] countries = trimws(phdsnoNA[,5]) euronums = match(countries,euromap$names) #euronums = na.omit(euronums) euronumnoNA = euronums[!is.na(euronums)] countriesnoNA = countries[!is.na(euronums)] fractionwomennoNA = phdsnoNA[!is.na(euronums),4] #fwomencolors = colorRampPalette(c("#edb700","#15cd00"))(max(fractionwomennoNA)-min(fractionwomennoNA)+1) fwomencolors = colorRampPalette(c("#edb700","#15de00"))(5) #cbyfwcolored = fwomencolors[(fractionwomennoNA-min(fractionwomennoNA)+1)] cbyfwcolored = fwomencolors[floor((fractionwomennoNA-min(fractionwomennoNA))/5)+1] ukisles = grep("UK", euromap$names) greekisles = grep("Greece", euromap$names) danishisles = grep("Denmark", euromap$names) itisles = grep("Italy", euromap$names) spanishisles = grep("Spain", euromap$names) frisles = grep("France", euromap$names) vecbycountry = rep("#ffffff",length(euromap$names) ) vecbycountry[euronumnoNA]=cbyfwcolored for (ctry in countriesnoNA){ vecbycountry[grep(ctry, euromap$names)]=cbyfwcolored[grep(ctry,countriesnoNA)] } vecbycountry[ukisles]=cbyfwcolored[grep("UK",countriesnoNA)] vecbycountry[greekisles]=cbyfwcolored[grep("Greece",countriesnoNA)] vecbycountry[danishisles]=cbyfwcolored[grep("Denmark",countriesnoNA)] vecbycountry[itisles]=cbyfwcolored[grep("Italy",countriesnoNA)] vecbycountry[spanishisles]=cbyfwcolored[grep("Spain",countriesnoNA)] vecbycountry[frisles]=cbyfwcolored[grep("France",countriesnoNA)] euromap = map("world", fill=TRUE, ylim=c(35,65), xlim=c(-10,35), mar=c(1,1,1,1), col=vecbycountry, lwd=1.4) dev.off() <file_sep>/README.md # map_code_in_R code for map plotting ## fun with maps ## There are many reasons to need figures of world or regional maps, the most obvious being distributions of species or collected samples. R has a world maps package which can be installed in the R shell. Also install the mapdata package. ``` > install.packages("maps") > install.packages("mapdata") ``` Starting up the library maps with the command produces a comical warning: ``` > library(maps) ATTENTION: maps v3.0 has an updated 'world' map. Many country borders and names have changed since 1990. Type '?world' or 'news(package="maps")'. See README_v3. ``` Making a world map is easy with the `map()` command in this package, but first make a color palette that not hard on the eyes. I choose a grayscale, but this could be a rainbow, or any other color vector, based on say population or cheese production. `> grayscale = colorRampPalette(c("#999999","#eeeeee"))(4)` `> map('world', fill=TRUE, col=grayscale, mar=c(1,1,1,1))` ![test_world_map.png](https://github.com/wrf/map_code_in_R/blob/master/images/test_world_map.png) I set the margins small to avoid too much white space. The map allows zooming in by latitude (`ylim`) and longitude (`xlim`), so I can select an arbitrary region like in europe: `> map('world', ylim=c(30,60), xlim=c(-10,30), fill=TRUE, col=grayscale, mar=c(1,1,1,1))` ![test_europe_map.png](https://github.com/wrf/map_code_in_R/blob/master/images/test_europe_map.png) The ocean looks bad as white space, so it can be colored blue with `bg`: `> map('world', ylim=c(40,55), xlim=c(-5,18), fill=TRUE, col=grayscale, mar=c(1,1,1,1), bg="#4466bb")` Points can be added as well by lat/lon, say for my university in Munich. I extract the color from the Bavarian flag, and use a diamond. ``` > points(11.566,48.133, pch=18, cex=3, col="#0098d4") > text(11.566,48.633,"LMU") ``` Various people had given me samples to work on, and those locations can be plotted the same way: ``` > slats = c(49.4166,48.783,47.586331,43.2964) > slons = c(08.716,09.183,9.5988717,5.37) > citynames = c("Heidelberg", "Stuttgart", "Kressbronn", "Marseille") > points(slons, slats, pch=19, col="#ee8400", cex=3) > text(slons+0.5, slats, citynames, pos=4) ``` ![test_europe_map_blue_bg_cities.png](https://github.com/wrf/map_code_in_R/blob/master/images/test_europe_map_blue_bg_cities.png) ## finer coloring of countries with real data ## For just plotting points, the maps function like any other plot where points or lines can be overlaid. However, for coloring by country, the color vector has to be set before creating the map. In the previous example, this was done with a gray scale, which results in a more or less random gray color for each country, but enough to give contrast. To make something more interesting, the data has to be converted into a color, say as a log of population density or endangered species. To do this, individual countries have to be assigned a color in the vector. To find out what countries we have, we start by creating a map. `> dummymap = map("world")` This will both display the world map with no parameters, and also generate the object dummymap of class "`map`". To get a list of countries, and some lakes, we can look at the attributes to get a list: ``` > attributes(dummymap) $names [1] "x" "y" "range" "names" $class [1] "map" ``` These all have different lengths: ``` > length(dummymap$x) [1] 12711 > length(dummymap$y) [1] 12711 > length(dummymap$range) [1] 4 > length(dummymap$names) [1] 1679 ``` `$names` is the one with a list of all countries, islands, lakes, and some regional divisions. Of around 200 countries in the world, it is clear that some of them have to double up to get to 1679 things. For example, to get a list of everything that is part of the UK: ``` > dummymap$names[grep("UK",dummymap$names)] [1] "UK:Isle of Wight" [2] "UK:Wales:Anglesey" [3] "UK:Northern Ireland" [4] "UK:Scotland:Island of Arran" [5] "UK:Scotland:Islay" [6] "UK:Scotland:Jura" [7] "UK:Scotland:Isle of Mull" [8] "UK:Scotland:Coll" [9] "UK:Scotland:Barra" [10] "UK:Scotland:Ruhm" [11] "UK:Scotland:South Uist" [12] "UK:Scotland:Island of Skye" [13] "UK:Scotland:North Uist" [14] "UK:Scotland:Isle of Lewis" [15] "UK:Great Britain" [16] "UK:Scotland:Orkney Islands:South Ronaldsay" [17] "UK:Scotland:Orkney Islands:Hoy" [18] "UK:Scotland:Orkney Islands:Mainland" [19] "UK:Scotland:Orkney Islands:Sanday" [20] "UK:Scotland:Orkney Islands:Westray" [21] "UK:Scotland:Shetland Islands:Mainland" [22] "UK:Scotland:Shetland Islands:Yell" [23] "UK:Scotland:Shetland Islands:Unst" ``` For a small country, there are indeed a lot of entries. The `grep()` command returns a list of indexes that contain "UK", and these are pulled out of the big list of countries. In terms of country specific data, I take some from the OECD from 2009 [regarding doctoral degrees by country](http://www.oecd-ilibrary.org/sites/sti_scoreboard-2011-en/02/01/index.html?contentType=/ns/StatisticalPublication,/ns/Chapter&itemId=/content/chapter/sti_scoreboard-2011-12-en&containerItemId=/content/serial/20725345&mimeType=text/html). There may be more recent data, but not for all countries. For simplicity, I download the data and convert just the table to csv, so it can be read easily by R. I made some manual changes to the data (such as removing years by some countries) to make the matching step easier. Because these data concern mostly European countries, I restrict my map: `> euromap = map("world", fill=TRUE, ylim=c(35,65), xlim=c(-10,35), mar=c(1,1,1,1))` The result of this is that $names has changed to contain only what is displayed: ``` > length(euromap$names) [1] 203 ``` This is important since the index used by the world map is not the same as a regional map. The countries have to be determined dynamically for each map. `> phdsbycountry = read.table("~/Documents/oecd_phds_by_country.csv", header=TRUE, sep=",")` So I choose the 4th column, which is percentage of PhDs awarded to women by country. I converted all #N/A to 0 for the csv, so I will first remove countries that have no data in that column. `> phdsnoNA = phdsbycountry[phdsbycountry[,4]>0,]` I then remove any whitespace from the country names and extract the index: ``` > countries = trimws(phdsnoNA[,5]) > euronums = match(countries, euromap$names) ``` I then exclude any entries that did not match by country. For example, United Kingdom and Slovak Republic find nothing, but UK:Great Britain and Slovakia are in the `$names`. ``` > euronumnoNA = euronums[!is.na(euronums)] > countriesnoNA = countries[!is.na(euronums)] > fractionwomennoNA = phdsnoNA[!is.na(euronums),4] ``` I want the map to be colorized by percentage of women, but the number of colors depends on the spread. Five or six colors might be suitable to provide reasonable contrast. ``` > range(fractionwomennoNA) [1] 38 62 ``` Since the range is 24, this could be done as a gradient. However, it is visually easier to understand as bins of percentage. I divide the data into 5 partitions of 5, making five colors including the first and last. Here I use yellow to green, since blue to pink is not effective for this dataset. ``` > fwcolors = colorRampPalette(c("#edb700","#15de00"))(5) > floor((fractionwomennoNA-min(fractionwomennoNA))/5)+1 [1] 1 3 5 4 2 3 2 2 1 2 2 2 2 1 1 2 1 3 3 3 2 3 2 > colorbyfw = fwcolors[floor((fractionwomennoNA-min(fractionwomennoNA))/5)+1] ``` The floor effectively bins the countries, and adding 1 is needed since these numbers are used to index the colors, and we cannot have an index of 0. The bulk of the countries end up with values of 1, 2 or 3, with only one country each with 4 or 5, Finland and Portugal, respectively. I next make a blank vector for the colors; all countries are white until given a color. Then I add the colors for each country to the indexes defined by euronumnoNA. Finally, the map is generated. ``` > vecbycountry = rep("#ffffff", length(euromap$names) ) > vecbycountry[euronumnoNA]=colorbyfw > euromap = map("world", fill=TRUE, ylim=c(35,65), xlim=c(-10,35), mar=c(1,1,1,1), col=vecbycountry, lwd=1.4) ``` ![test_europe_map_oecd_phd_by_country.png](https://github.com/wrf/map_code_in_R/blob/master/images/test_europe_map_oecd_phd_by_country.png) ## fixing colors of islands ## In the previous map, one obvious mistake is that Northern Ireland is not counted as part of the UK, nor any other British Isle. The same is true for Greece, Italy, France, Spain and Denmark. This can be done the slow way, by going through each country one by one. For instance, the indexes can be retrieved for all countries and islands of the UK with grep. Then those indexes can be assigned whatever color the UK has. ``` > ukisles = grep("UK", euromap$names) > vecbycountry[ukisles]=colorbyfw[grep("UK",countriesnoNA)] ``` Instead, after creating the blank color vector and assigning colors, I create a loop to go through each country and add any islands the same way. ``` > vecbycountry = rep("#ffffff", length(euromap$names) ) > vecbycountry[euronumnoNA]=colorbyfw > for (ctry in countriesnoNA){ > vecbycountry[grep(ctry,euromap$names)] = colorbyfw[ grep(ctry,countriesnoNA)] > } ``` The final map looks like this, where all islands correspond to their mainland (incidentally except the UK, which was renamed in the original data table to UK:Great Britain; this is added on for completeness.) ![test_europe_map_oecd_phd_by_country_w_islands.png](https://github.com/wrf/map_code_in_R/blob/master/images/test_europe_map_oecd_phd_by_country_w_islands.png)
7f1ef8b40811187c1d2b09092fbe9dcae786e9df
[ "Markdown", "R" ]
2
R
wrf/map_code_in_R
db7763a0f849316ae068ec9a757b6bc38ce46dcb
e69cf65e7a8c4776626adc0c53584562aacc9bda
refs/heads/master
<file_sep> 中文 | [English](https://github.com/cnlon/smart-observe/blob/master/README.en.md) # smart-observe [![Build Status](https://travis-ci.org/cnlon/smart-observe.svg?branch=master)](https://travis-ci.org/cnlon/smart-observe) [![npm version](https://badge.fury.io/js/smart-observe.svg)](https://badge.fury.io/js/smart-observe) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com) **smart-observe** 来自 [**Vue.js**](https://github.com/vuejs/vue),是一个小巧、高效,用于监测 javascript 对象、数组、类 变化的库 ## 安装 ``` bash npm install --save smart-observe ``` 或 ``` bower install --save smart-observe ``` ## 使用 #### 监测属性 `observe.watch(target, expression, callback)` 或 `observe(target, expression, callback)` 试一试: [codepen](http://codepen.io/lon/pen/rrqLLk?editors=0010#0) [jsfiddle](https://jsfiddle.net/lon/x4n2yjLn/) ``` javascript const target = {a: 1} observe(target, 'a', function (newValue, oldValue) { console.log(newValue, oldValue) }) target.a = 3 // 3 1 ``` #### 添加计算属性 `observe.compute(target, name, getter)` 试一试: [codepen](http://codepen.io/lon/pen/dpgXLN?editors=0010#0) [jsfiddle](https://jsfiddle.net/lon/q402v3jd/) ``` javascript const target = {a: 1} observe.compute(target, 'b', function () { return this.a * 2 }) console.log(target.b) // 2 target.a = 3 console.log(target.b) // 6 ``` #### 监测属性并添加计算属性 `observe.react(options)` 试一试: [codepen](http://codepen.io/lon/pen/zKmKqA?editors=0010#0) [jsfiddle](https://jsfiddle.net/lon/ufth8xpe/) ``` javascript const options = { data: { PI: Math.PI, radius: 1, }, computed: { 'area': function () { return this.PI * this.square(this.radius) // πr² }, }, watchers: { 'area': function (newValue, oldValue) { console.log(`area: ${newValue}`) }, }, methods: { square (num) { return num * num }, }, } const target = observe.react(options) target.radius = 3 // area: 28.274333882308138 ``` ## API #### 属性 | 名称 | 类型 | 值 | 说明 | | --- | --- | --- | --- | | `observe.deep` | `boolean` | 默认为 `false` | 如果为 `true`,`observe.watch(target, expression, callback)` 将会对 `target` 深度监测 | | `observe.sync` | `boolean` | 默认为 `false` | 如果为 `true`,`observe.watch(target, expression, callback)` 监测到属性变化时,立即调用回调函数 | | `observe.default` | `function` | 只能为 `observe.react`,`observe.watch` 或 `observe.compute`, 默认为 `observe.watch` | 设置 `observe(...)` 实际调用的方法,写起来简洁一些 | #### 方法 **`observe(...)`** - 为方法 `observe.default` 的语法糖,`observe.default` 参见属性 **`observe.watch(target, expression, callback)`** - `target`: 任意对象 - `expression`: `string` 或 `function` - `callback`: `function` - 返回 `Watcher`,调用 `watcher.teardown()` 可以取消监测 **`observe.compute(target, name, accessor, cache)`** - `target`: 任意对象 - `name`: `string` - `accessor`: - `function`: 会作为 `getter`,等同传入 {get: accessor} - `Object`: 可以包含:(其中,至少包含 `get` 或 `set`) - `get`: `function` - `set`: `function` - `cache`: `boolean`,可选,默认为 `true`,如果设为 `false`,每次读取计算属性都要重新计算 - `cache`: `boolean`,可选,默认为 `true`,仅当 `accessor` 为 `function` 时有效。 **`observe.react(options, target)`** - `options`: `Object`,要配置的参数集合,可以包含: - `data`: 要附加的字段 - `computed`: 要附加的计算属性 - `watchers`: 要监测的属性和计算属性 - `methods`: 要附加的方法,这些方法将会自动绑定 `target` - `target`: 任意对象,可选,默认为空对象,`options` 的参数将附加到此对象上 - 返回 `target` ## License [MIT](https://github.com/cnlon/smart-observe/blob/master/LICENSE) <file_sep>import resolve from 'rollup-plugin-node-resolve' import babel from 'rollup-plugin-babel' import uglify from 'rollup-plugin-uglify' const needMin = !!process.env.MIN let file = 'dist/smart-observe.js' const plugins = [ resolve({ jsnext: true, browser: true, }), babel({ presets: [ ['env', { targets: { browsers: ['last 3 versions', 'IE >= 9'], node: '4' }, modules: false }] ], plugins: [ 'transform-class-properties', 'external-helpers' ], }) ] if (needMin) { file = 'dist/smart-observe.min.js' plugins.push(uglify()) } export default { input: 'src/index.js', output: { file, format: 'umd', name: 'observe', banner: `/** * smart-observe --- By lon * https://github.com/cnlon/smart-observe */`, }, plugins, } <file_sep>import nextTick from 'smart-next-tick' let queue = [] let has = {} let waiting = false let queueIndex /** * Reset the batcher's state. */ function resetBatcherState () { queue = [] has = {} waiting = false } /** * Flush queue and run the watchers. */ function flushBatcherQueue () { runBatcherQueue(queue) resetBatcherState() } /** * Run the watchers in a single queue. * * @param {Array} queue */ function runBatcherQueue (queue) { // do not cache length because more watchers might be pushed // as we run existing watchers for (queueIndex = 0; queueIndex < queue.length; queueIndex++) { const watcher = queue[queueIndex] const id = watcher.id has[id] = null watcher.run() } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. * * @param {Watcher} watcher * properties: * - {number} id * - {function} run */ export default function batch (watcher) { const id = watcher.id if (has[id] == null) { has[id] = queue.length queue.push(watcher) // queue the flush if (!waiting) { waiting = true nextTick(flushBatcherQueue) } } }
d88a2b32bbf91ad8b9c22528882ac132d6c43401
[ "Markdown", "JavaScript" ]
3
Markdown
J-env/smart-observe
e29c853a4ea744d13a9731524e9e981f0939dca6
498abee02b2c353f14e02bcb9a01d9292dd3ac8a
refs/heads/main
<file_sep>#include <stdio.h> #include <stdlib.h> float signF(float t){ if(t==0)return 0; else if(t>0)return 1; else return -1; } float fFunc(float t, float *xyc, int k){ int i; int n=xyc[0]; int ncr[n];// = (int*)malloc(sizeof(int)*n); float tarr[n];// = (int*)malloc(sizeof(int)*n); float t_1arr[n];// = (int*)malloc(sizeof(int)*n); ncr[0]=1; tarr[0]=1; t_1arr[n-1]=1; for(i=1;i<n;i++){ ncr[i]=(ncr[i-1]*(n-i))/i; tarr[i]=tarr[i-1]*t; t_1arr[n-i-1]=t_1arr[n-i]*(1-t); } float upperterm = 0; for(i=0;i<n;i++){ upperterm += ncr[i]*tarr[i]*t_1arr[i]*xyc[i+k]; } return upperterm; } float diffFunc(float t, float *xyc, float d,int k){ int i; int n=xyc[0]; int ncr[n];// = (int*)malloc(sizeof(int)*n); float tarr[n];// = (int*)malloc(sizeof(int)*n); float t_1arr[n];// = (int*)malloc(sizeof(int)*n); ncr[0]=1; tarr[0]=1; t_1arr[n-1]=1; for(i=1;i<n;i++){ ncr[i]=(ncr[i-1]*(n-i))/i; tarr[i]=tarr[i-1]*t; t_1arr[n-i-1]=t_1arr[n-i]*(1-t); } float upperterm = 0; for(i=0;i<n;i++){ upperterm += ncr[i]*tarr[i]*t_1arr[i]*xyc[i+k]; } int n2=n-1; int ncr2[n2]; ncr2[0]=1; for(i=1;i<n2;i++) ncr2[i]=(ncr2[i-1]*(n2-i))/i; float lowerterm = 0; for(i=0;i<n2;i++){ lowerterm += ncr2[i]*tarr[i]*t_1arr[i+1]*(xyc[i+k+1]-xyc[i+k]); } if(lowerterm == 0)return 0; float tnew = (upperterm-d)/((n-1)*lowerterm); return tnew; } int *Bezier(int w,int h,float *xyc){ /*int *c; int (*k)[w]; int (*canvas)[w] = (int (*)[w])malloc(sizeof(int)*h*w); c = (int *)canvas; c[7] = 1; printf("canvas[0][0]%d\n",canvas[0][0]); k = (int (*)[w])c; k[1][0] = -1; printf("canvas[0][0]%d\n",canvas[1][0]);*/ int i,j; int n=xyc[0]; int *ncr = (int*)malloc(sizeof(int)*n); ncr[0]=1; for(i=1;i<n;i++) ncr[i]=(ncr[i-1]*(n-i))/i; float x0 = xyc[1]; float y0 = xyc[n+1]; int walls[4]; walls[0] = x0; walls[1] = walls[0]+1; walls[2] = y0; walls[3] = walls[2]+1; float wallsT[4]; for(i=0;i<4;i++){ wallsT[i]=0; for(j=0;j<10;j++){ wallsT[i] -= diffFunc(wallsT[i],xyc,walls[i],(i/2)*n+1); } } float cwall = 1; int cin = -1; for(i=0;i<4;i++){ if(wallsT[i]>=0&&wallsT[i]<cwall){ cwall=wallsT[i]; cin = i; } } printf("%f\n",cwall); printf("%d\n",cin); float cy = walls[cin]; float cx = fFunc(cwall,xyc,1); printf("%f\n",cx); int walls2[3]; walls2[0]=cx; walls2[1]=walls2[0]+1; walls2[2]=cy+signF(cy-y0); float wallsT2[3]; for(i=0;i<3;i++){ wallsT2[i]=cwall; for(j=0;j<10;j++){ wallsT2[i] -= diffFunc(wallsT2[i],xyc,walls2[i],(i/2)*n+1); } } cwall = 1; cin = -1; for(i=0;i<4;i++){ if(wallsT2[i]>=0&&wallsT2[i]<cwall){ cwall=wallsT2[i]; cin = i; } } printf("%f\n",cwall); printf("%d\n",cin); return NULL; } void main(){ int w=7,h=5,i,j; int *k; float xyc[]={6,6.46,5.46,5.34,3.97,2.93,2.45,3.46,0.57,0.89,5.09,5.02,2.57}; int n = xyc[0]; float *xycp; xycp = (float *)malloc(sizeof(float)*(xyc[0]*2)+1); for(i=0;i<=2*xyc[0];i++) xycp[i]=xyc[i]; Bezier(w,h,xycp); //for(i=0;i<n;i++)printf("%d ",k[i]); /*for(i=0;i<h;i++){ for(j=0;j<w;j++){ //canvas[w][h]=1; printf("%p ",&(canvas[i][j])); } printf("\n"); } printf("%p \n",&(canvas[0][0]));*/ }
aecbe38c914fc7aff1440640b78adff8e2242d0a
[ "C" ]
1
C
infsml/shape_c
6a0afd572bb16b02910a9f4d1d853e1c2a8756c3
2b253b09d774febb03cfd33ddce47ce270f540bd
refs/heads/master
<file_sep>{% extends 'master.html' %} {% load crispy_forms_tags %} {% load i18n %} {% block Title %} {% translate 'Password Reset Done' %} {% endblock %} {% block Content %} <section class="container"> <div class="row justify-content-md-center"> <div class="col-md-4"> <div class="card" id="account_box"> <div class="card-header text-center"> {% translate 'Password Reset Done' %} </div> <div class="card-body"> <blockquote class="blockquote text-lg-left"> We've emailed you instructions for setting your password, if an account exists with the email you entered. You should receive them shortly. </blockquote> <blockquote class="blockquote text-lg-left"> If you don't receive an email, please make sure you've entered the address you registered with, and check your spam folder. </blockquote> </div> </div> </div> </div> </section> {% endblock %}<file_sep>from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ from extensions.custom_validations import image_validation_by_size from colorfield.fields import ColorField class SainaLink(models.Model): title = models.CharField( verbose_name=_('Title'), max_length=128, null=False, blank=False ) description = models.CharField( verbose_name=_('Description'), max_length=265, null=False, blank=False ) slug = models.SlugField( verbose_name=_('Slug'), max_length=32, null=False, blank=False, unique=True ) logo = models.ImageField( verbose_name=_('Logo'), upload_to='logos', default='logos/default_logo.png', help_text=_('Max file size is %(size)d MB.') % {'size': settings.MAX_IMAGE_SIZE}, validators=[image_validation_by_size], null=False, blank=True ) create_time = models.DateTimeField( verbose_name=_('Create Time'), auto_now_add=True, null=False, blank=False, editable=False ) last_update_time = models.DateTimeField( verbose_name=_('Last Update Time'), auto_now=True, null=False, blank=False, editable=False ) create_user = models.ForeignKey( User, verbose_name=_('Create User'), null=False, blank=False, editable=False, on_delete=models.PROTECT, related_name='sainalink_create_user' ) last_update_user = models.ForeignKey( User, verbose_name=_('Last Update User'), null=False, blank=False, editable=False, on_delete=models.PROTECT, related_name='sainalink_last_update_user' ) def __str__(self): return self.title class Meta: verbose_name = _("Saina Link") verbose_name_plural = _("Saina Links") def get_absolute_url(self): return f'/{self.slug}' class SocialNetworksButton(models.Model): title = models.CharField( verbose_name=_('Title'), max_length=128, null=False, blank=False ) icon = models.CharField( verbose_name=_('Icon'), max_length=16, null=False, blank=False ) url = models.URLField( verbose_name=_('URL'), null=False, blank=False ) color = ColorField( default='#FF0000' ) def __str__(self): return self.title class Meta: verbose_name = _("Social Networks Button") verbose_name_plural = _("Social Networks Buttons") class SocialNetworksIcon(models.Model): title = models.CharField( verbose_name=_('Title'), max_length=128, null=False, blank=False ) icon = models.CharField( verbose_name=_('Icon'), max_length=16, null=False, blank=False ) url = models.URLField( verbose_name=_('URL'), null=False, blank=False ) color = ColorField( default='#FF0000' ) def __str__(self): return self.title class Meta: verbose_name = _("Social Networks Icon") verbose_name_plural = _("Social Networks Icons") class Link(models.Model): title = models.CharField( verbose_name=_('Title'), max_length=128, null=False, blank=False ) url = models.URLField( verbose_name=_('URL'), null=False, blank=False ) def __str__(self): return self.title class Meta: verbose_name = _("Link") verbose_name_plural = _("Links") class Contact(models.Model): icon = models.CharField( verbose_name=_('Icon'), max_length=16, null=False, blank=False ) content = models.CharField( verbose_name=_('Content'), max_length=32, null=False, blank=False ) def __str__(self): return self.content class Meta: verbose_name = _("Contact") verbose_name_plural = _("Contacts") class FAQ(models.Model): question = models.CharField( verbose_name=_('Question'), max_length=128, null=False, blank=False ) answer = models.CharField( verbose_name=_('Answer'), max_length=128, null=False, blank=False ) def __str__(self): return self.question class Meta: verbose_name = _("FAQ") verbose_name_plural = _("FAQs") <file_sep>from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.conf import settings def image_validation_by_size(image_file): image_file = image_file.file.size if image_file > settings.MAX_IMAGE_SIZE*1024*1024: raise ValidationError(_('Max file size is %(size)d MB.') % {'size': settings.MAX_IMAGE_SIZE})
3a1c0299176fc9f6d624d61b91b954b965b09db8
[ "Python", "HTML" ]
3
HTML
mavenium/Saina
a624713ac02a2609c01d6a3c16a0555d54026a88
d8a1b6cb588d27fab6a5b59dc3d6b19501d3193e
refs/heads/master
<file_sep><?php include 'controllers/update_controller.php'; ?> <div class="row"> <div class="col-md-12"> <div class="card mb-3"> <div class="card-header"> Row Details </div> <form class="form-horizontal" method="POST" enctype="multipart/form-data"> <div class="card-body"> <div class="row"> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpTeam">Journey Team</label> <select class="form-control" name="inpTeam" id="inpTeam" required="true" disabled="true"> <?php echo $list_teams; ?> </select> </div> </div> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpEnv">Environment</label> <select class="form-control" name="inpEnv" id="inpEnv" required="true" disabled="true"> <?php echo $list_env; ?> </select> </div> </div> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpTech">Cloud/DevOps Technology</label> <select class="form-control" name="inpTech" id="inpTech" required="true" disabled="true"> <?php echo $list_tech; ?> </select> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-12"> <div class="form-group"> <label for="inpType">Cost Savings Type</label> <select class="form-control" name="inpType" id="inpType" required="true" disabled="true"> <?php echo $list_type; ?> </select> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpInitial">Initial Cost</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input class="form-control" type="text" name="inpInitial" id="inpInitial" value="<?php echo $csInitial; ?>" required="true" disabled="true" /> </div> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpFinal">Final Cost</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input class="form-control" type="text" name="inpFinal" id="inpFinal" value="<?php echo $csFinal; ?>" required="true" disabled="true" /> </div> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpCause">Root Cause</label> <textarea class="form-control" rows="10" name="inpCause" id="inpCause" maxlength="800" placeholder="Details of the problem encountered..." required="true" disabled="true"><?php echo $csCause; ?></textarea> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpSteps">Solution/s Implemented</label> <textarea class="form-control" rows="10" name="inpSteps" id="inpSteps" maxlength="800" placeholder="Steps taken in order to resolve the issue/s encountered..." required="true" disabled="true"><?php echo $csSteps; ?></textarea> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpName">Action Executed By</label> <input class="form-control" type="text" name="inpName" id="inpName" maxlength="50" placeholder="Enter a name..." value="<NAME>*" required="true" disabled="true"> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpDate">Completion Date</label> <input class="form-control" type="test" name="inpDate" id="inpDate" min="2018-01-01" max="<?php echo date('Y-m-d'); ?>" value="<?php echo $displayDate->format('Y-m-d'); ?>" required="true" disabled="true"> </div> </div> </div> </div> <div class="card-footer"> <a href="view.php" class="btn btn-primary"> <span><i class="fa fa-fw fa-angle-left"></i></span> </a> <button type="button" class="btn btn-primary float-right" name="btnSubmit" id="btnSubmit">Update Record</button> </div> </form> </div> </div> </div> <script type="text/javascript"> $(function() { $('#inpSave').maskMoney({allowZero: true}); }) </script> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php include('config.php'); include('function.php'); if(isset($_POST['btnLogin'])) { /* Account status numbers: 0 - inactive/deactivated, 1 - active, 2 - pending (for confirmation) */ # Get the input from the form $inpEmail = inpcheck($_POST['inpEmail']); $inpPassword = inpcheck($_POST['inpPassword']); # Validate the input: email and password must be valid and not empty if(empty(trim($inpEmail)) || empty(trim($inpPassword))) { $msgDisplay = errorAlert("Please make sure that the entries are valid."); } else { # SELECT statement to get the account records from the database $sql_account = "SELECT accountID, accountUN, accountPW, accountStatus FROM accounts"; $result_account = $con->query($sql_account) or die(mysqli_error($con)); $ucount = 0; #Check through the database records while($row = mysqli_fetch_array($result_account)) { # Get the information for each row $accountID = $row['accountID']; $accountUN = $row['accountUN']; $accountPW = $row['accountPW']; $accountStatus = $row['accountStatus']; # Compare between the input and the stored record (returns boolean) $compAccount = password_verify($inpEmail, $accountUN); $compPass = password_verify($inpPassword, $accountPW); # Look for the account and password that match if($compAccount == 1 && $compPass == 1) { # The input match the stored values $ucount = $ucount + 1; # End the loop when a match has been found break; } } # If the count is >= 1, a record has been found if($ucount >= 1) { if($accountStatus == 1) { session_start(); $_SESSION['accID'] = $accountID; $accID = $_SESSION['accID']; $txtEvent = "Logged in into the system"; logEvent($con, $accID, $txtEvent); header('location: index.php'); } else if($accountStatus == 2) { # Account status is pending... $msgDisplay = warningAlert("Your account currently does not have access."); } else if($accountStatus == 0) { # Account status is disabled/inavtive... $msgDisplay = errorAlert("Your account is currently disabled/inactive."); } } else { # There are no records that match the input creentials... $msgDisplay = errorAlert("Incorrect email/password. Please check your input and try again."); } } } /* Account status numbers: 0 - inactive/deactivated, 1 - active, 2 - pending (for confirmation) */ ?><file_sep><?php $pageTitle = "Dashboard"; $metaTitle = "Cost Savings Dashboard"; # This is used by Slack as a default title for the share text $metaTitle = "Cost Savings Knowledge Base - Dashboard"; # This is used by Facebook as its default title in the share card/link $metaDescription = "View analytical data from the cost savings entries."; # if 'viewonly' is set in the url, # it loads the page with the same css and js but without the header/navbar if(isset($_GET['viewonly'])) { include 'controllers/includes/header_viewonly.php'; $animation = "animation: { duration: 0 },"; } else { include 'includes/header.php'; $animation = ""; } # SQL query to get the list of teams for the filter dropdown $sql_listTeams = "SELECT teamID, teamName FROM journeyteams"; $result_listTeams = $con->query($sql_listTeams) or die(mysqli_error($con)); $list_teams = ""; while($rt = mysqli_fetch_array($result_listTeams)) { $teamID = $rt['teamID']; $teamName = htmlspecialchars($rt['teamName']); # Determine which of the options should have the 'active' attribute when the records are filtered if(isset($_GET['filter']) && $teamID == $_GET['filter']) { $isActive = "selected='true'"; } else { $isActive = ""; } $list_teams .= "<option value='?filter=$teamID' $isActive>$teamName</option>"; } # These queries are used for both the filtered and non-filtered outputs # SQL - for the doughnut chart (breakdown by team) $sql_team = "SELECT j.teamName, SUM(c.csSavings) AS 'totSavings' FROM costsavings c INNER JOIN journeyteams j ON c.teamID = j.teamID WHERE MONTH(c.csDate) = MONTH(CURRENT_DATE())"; $teamArray = array(); $tsavingsArray = array(); # SQL - for the doughnut chart (breakdown by team - by project) $sql_proj = "SELECT p.projectName, SUM(c.csSavings) AS 'totSavings' FROM costsavings c INNER JOIN projects p ON c.projectID = p.projectID WHERE MONTH(c.csDate) = MONTH(CURRENT_DATE())"; $projArray = array(); $psavingsArray = array(); # SQL - for doughnut chart (breakdown by environment) $sql_env = "SELECT v.envName, SUM(c.csSavings) AS 'totSavings' FROM costsavings c INNER JOIN environments v ON c.envID = v.envID WHERE MONTH(c.csDate) = MONTH(CURRENT_DATE())"; $envArray = array(); $esavingsArray = array(); # SQL - for doughnut chart (breakdown by Technology) $sql_tech = "SELECT h.techName, SUM(c.csSavings) AS 'totSavings' FROM costsavings c INNER JOIN technologies h ON c.techID = h.techID WHERE MONTH(c.csDate) = MONTH(CURRENT_DATE())"; $techArray = array(); $hsavingsArray = array(); # SQL - for doughnut chart (breakdown by savings type) $sql_type = "SELECT y.typeName, SUM(c.csSavings) AS 'totSavings' FROM costsavings c INNER JOIN savingtypes y ON c.typeID = y.typeID WHERE MONTH(c.csDate) = MONTH(CURRENT_DATE())"; $typeArray = array(); $ysavingsArray = array(); # SQL - for the 10 latest initiatives $sql_latest = "SELECT c.csID, c.csDate, j.teamName, h.techName, v.envName, y.typeName, c.csSavings FROM costsavings c INNER JOIN journeyteams j ON c.teamID = j.teamID INNER JOIN technologies h ON c.techID = h.techID INNER JOIN environments v ON c.envID = v.envID INNER JOIN savingtypes y ON c.typeID = y.typeID"; # Initialization of the values for the bar chart # This is shared by the filtered and non-filtered outputs $valMonth = date('n'); # numeric month without leading zeros $data_bar = "["; # start of the variable to be passed to the js $bar_cs = 0; # holds the total for the month; defaulted to 0 in case of empty result sets # Mics. variables (this is used mostly for muted text/card footers) $thisMon = date('Y-m-d', strtotime("monday this week")); $thisFri = date('Y-m-d', strtotime("sunday this week")); $lastMon = date('Y-m-d', strtotime("monday last week")); $lastFri = date('Y-m-d', strtotime("friday last week")); $headerDisplay = ""; $pieDisplay = "Breakdown by Team"; $tableDisplay = ""; $mon = date_create($thisMon); $fri = date_create($thisFri); $cstotalDate = date_format($mon, 'F d') . ' - ' . date_format($fri, 'd, Y'); # -------- # Check if the filter value is set... if(isset($_GET['filter'])) { # Bind the value to a variable $valFilter = $_GET['filter']; # SQL query to validate if the record being requested by the filter exists #$sql_validate = $con->prepare("SELECT csID FROM costsavings WHERE teamID = ?"); #$sql_validate->bind_param("i", $valFilter); #$sql_validate->execute(); $sql_validate = $con->prepare("SELECT teamName FROM journeyteams WHERE teamID = ?"); $sql_validate->bind_param("i", $valFilter); $sql_validate->execute(); $result_validate = $sql_validate->get_result(); # if the validation query returns more than 0 rows (i.e. the record exists) if(mysqli_num_rows($result_validate) > 0) { # Display a header/label and change the text of one of the graphs when the data is filtered $sql_label = $con->prepare("SELECT teamName FROM journeyteams WHERE teamID = ?"); $sql_label->bind_param("i", $valFilter); $sql_label->execute(); $result_label = $sql_label->get_result(); while($rl = mysqli_fetch_array($result_label)) { $labelTeam = htmlspecialchars($rl['teamName']); } $headerDisplay = "Team " . $labelTeam; # adds a header that displays the current filtered team $pieDisplay = "Team " . $labelTeam; # changes the display of the team doughnut chart $tableDisplay = " from Team " . $labelTeam; # appends the team name in the latest initiatives table # Filtered values - weekly total (current and prev. week, including percentage values) $sql_total = $con->prepare("SELECT SUM(csSavings) AS 'sumSavings' FROM costsavings WHERE teamID = ? AND csDate >= ? AND csDate <= ?"); $sql_total->bind_param("iss", $valFilter, $thisMon, $thisFri); $sql_total->execute(); $result_total = $sql_total->get_result() or die(mysqli_error($con)); while($row = mysqli_fetch_array($result_total)) { $sumSavings = $row['sumSavings']; } if(empty($sumSavings) || $sumSavings === NULL) { $sumSavings = '0.00'; # a default value for when there are no records yet } # we get the data for the previous week for comparison $sql_last = $con->prepare("SELECT SUM(csSavings) AS 'sumLast' FROM costsavings WHERE teamID = ? AND csDate >= ? AND csDate <= ?"); $sql_last->bind_param("iss", $valFilter, $lastMon, $lastFri); $sql_last->execute(); $result_last = $sql_last->get_result(); while($t_row = mysqli_fetch_array($result_last)) { $sumLast = $t_row['sumLast']; } if(empty($sumLast)) { $sumLast = '0.00'; } # Filtered values - largest input for the current week $sql_largest_filtered = $con->prepare("SELECT m.teamName, h.techName, y.typeName, v.envName, c.csCause, c.csSteps, c.csSavings, c.csDate, u.userFN, u.userLN FROM costsavings c INNER JOIN journeyteams m ON c.teamID = m.teamID INNER JOIN technologies h ON c.techID = h.techID INNER JOIN savingtypes y ON c.typeID = y.typeID INNER JOIN environments v ON c.envID = v.envID INNER JOIN users u ON c.userID = c.userID WHERE c.csDate >= ? AND c.csDate <= ? AND c.teamID = ? ORDER BY c.csSavings DESC LIMIT 1"); $sql_largest_filtered->bind_param("ssi", $thisMon, $thisFri, $valFilter); $sql_largest_filtered->execute(); $result_largest = $sql_largest_filtered->get_result(); if(mysqli_num_rows($result_largest) == 0) { # Setting the default values for when there are no existing records for the current week $lar_teamName = "-"; $lar_techName = "-"; $lar_typeName = "-"; $lar_envName = "-"; $lar_csCause = "No data available"; $lar_csSteps = "No data available"; $lar_csSavings = "-"; $lar_csActor = ""; $lar_csDate = "No data available"; } else { while($row_largest = mysqli_fetch_array($result_largest)) { $lar_teamName = htmlspecialchars($row_largest['teamName']); $lar_techName = htmlspecialchars($row_largest['techName']); $lar_typeName = htmlspecialchars($row_largest['typeName']); $lar_envName = htmlspecialchars($row_largest['envName']); $lar_csCause = htmlspecialchars($row_largest['csCause']); $lar_csSteps = htmlspecialchars($row_largest['csSteps']); $lar_csSavings = htmlspecialchars($row_largest['csSavings']); $lar_csActor = htmlspecialchars($row_largest['userFN']) . ' ' . htmlspecialchars($row_largest['userLN']); $lar_csDate = htmlspecialchars($row_largest['csDate']); } } # Filtered values - total savings per month (bar chart) for($i = 1; $i <= $valMonth; $i++) { # The SQL queries are looped to get the data for each month $sql_barData = "SELECT SUM(csSavings) AS 'totSavings' FROM costsavings WHERE MONTH(csDate) = $i AND teamID = $valFilter GROUP BY MONTH(csDate)"; $result_barData = $con->query($sql_barData) or die(mysqli_error($con)); while($bar_row = mysqli_fetch_array($result_barData)) { $bar_cs = $bar_row['totSavings']; if(empty($bar_cs) || $bar_cs === NULL) { $bar_cs = 0; } else { $bar_cs = $bar_row['totSavings']; } } $data_bar .= $bar_cs . ","; } $data_bar .= "],"; # Filtered values - doughnut charts # Filtered breakdown by team $sql_team_filtered = $sql_team . " AND c.teamID = $valFilter GROUP BY c.teamID"; $result_team = $con->query($sql_team_filtered) or die(mysqli_error($con)); while($row = mysqli_fetch_array($result_team)) { $teamArray[] = $row['teamName']; $tsavingsArray[] = $row['totSavings']; } # These variables will be passed to the js of the pie chart as their data set $tsavings_list = '[' . implode(', ', $tsavingsArray) . '],'; # Output: [val1, val2, ...], $teams_list = '["' . implode('", "', $teamArray) . '"],'; # Output: ['team1', 'team2', ...], # Filtered breakdown by projects (will replace the team pie chart when the filter is set) $sql_proj_filtered = $sql_proj . " AND c.teamID = $valFilter GROUP BY c.projectID"; $result_proj = $con->query($sql_proj_filtered) or die(mysqli_error($con)); while($row = mysqli_fetch_array($result_proj)) { $projArray[] = $row['projectName']; $psavingsArray[] = $row['totSavings']; } # Variables to be passed to the output # ** Will replace the team pie chart on filter $tsavings_list = '[' . implode(', ', $psavingsArray) . '],'; $teams_list = '["' . implode('", "', $projArray) . '"],'; #$pieDisplay = "Breakdown by Project - Team " . $labelTeam; $pieDisplay = "Breakdown by Project"; # Filtered breakdown by environment $sql_env_filtered = $sql_env . " AND c.teamID = $valFilter GROUP BY c.envID"; $result_env = $con->query($sql_env_filtered) or die(mysqli_error($con)); while($e_row = mysqli_fetch_array($result_env)) { $envArray[] = $e_row['envName']; $esavingsArray[] = $e_row['totSavings']; } # Variables for the environments chart $esavings_list = '[' . implode(', ', $esavingsArray) . '],'; $env_list = '["' . implode('", "', $envArray) . '"],'; # Filtered breakdown by technology $sql_tech_filtered = $sql_tech . " AND c.teamID = $valFilter GROUP BY c.techID"; $result_tech = $con->query($sql_tech_filtered) or die(mysqli_error($con)); while($h_row = mysqli_fetch_array($result_tech)) { $techArray[] = $h_row['techName']; $hsavingsArray[] = $h_row['totSavings']; } # Variables for the technology chart $hsavings_list = '[' . implode(', ', $hsavingsArray) . '],'; $tech_list = '["' . implode('", "', $techArray) . '"],'; # Filtered breakdown by savings type $sql_type_filtered = $sql_type . " AND c.teamID = $valFilter GROUP BY c.typeID"; $result_type = $con->query($sql_type_filtered) or die(mysqli_error($con)); while($y_row = mysqli_fetch_array($result_type)) { $typeArray[] = $y_row['typeName']; $ysavingsArray[] = $y_row['totSavings']; } # Variables for the savings type chart $ysavings_list = '[' . implode(', ', $ysavingsArray) . '],'; $type_list = '["' . implode('", "', $typeArray) . '"],'; # Filtered values - latest initiavies/entries $sql_latest_filtered = $con->prepare($sql_latest . " WHERE c.teamID = ? ORDER BY csDate DESC LIMIT 10"); $sql_latest_filtered->bind_param("i", $valFilter); $sql_latest_filtered->execute(); $result_latest = $sql_latest_filtered->get_result(); $list_latest = ""; while($l_row = mysqli_fetch_array($result_latest)) { $csID = $l_row['csID']; $csDate = htmlspecialchars($l_row['csDate']); $teamName = htmlspecialchars($l_row['teamName']); $techName = htmlspecialchars($l_row['techName']); $typeName = htmlspecialchars($l_row['typeName']); $envName = htmlspecialchars($l_row['envName']); $csSavings = htmlspecialchars($l_row['csSavings']); # Display the date on the table without the year $displayDate = date_format(date_create($csDate), 'm/d'); # Class .clickable-row allows the table row to act as a button/hyperlink # that opens the details page for the selected record $list_latest .= " <tr class='clickable-row' data-href='details.php?rid=$csID' style='cursor: pointer;'> <td>$displayDate</td> <td>$teamName</td> <td>$techName</td> <td>$envName</td> <td>$typeName</td> <td> <span class='float-left'>$</span> <span class='float-right'>$csSavings</span> </td> </tr>"; } } else { #validate if the record exists in the list of teams #if it does, display 'no recrds yet' value/s #else, redirect to the error page # The validation query returned 0 rows (no records match) # Display (redirect to) an error page #header('location: error.php'); } } else #...display the "default"/unfiltered values (show all) { # Default values - weekly total (current and prev. week w/ percentages) $sql_total = $con->prepare("SELECT SUM(csSavings) AS 'sumSavings' FROM costsavings WHERE csDate >= ? AND csDate <= ?"); $sql_total->bind_param("ss", $thisMon, $thisFri); $sql_total->execute(); $result_total = $sql_total->get_result(); while($row = mysqli_fetch_array($result_total)) { $sumSavings = $row['sumSavings']; } if(empty($sumSavings)) { $sumSavings = '0.00'; } $sql_last = $con->prepare("SELECT SUM(csSavings) AS 'sumLast' FROM costsavings WHERE csDate >= ? AND csDate <= ?"); $sql_last->bind_param("ss", $lastMon, $lastFri); $sql_last->execute(); $result_last = $sql_last->get_result(); while($t_row = mysqli_fetch_array($result_last)) { $sumLast = $t_row['sumLast']; } if(empty($sumLast)) { $sumLast = 0; } # Default values - largest input for the current week $sql_largest = $con->prepare("SELECT m.teamName, h.techName, y.typeName, v.envName, c.csCause, c.csSteps, c.csSavings, c.csDate, u.userFN, u.userLN FROM costsavings c INNER JOIN journeyteams m ON c.teamID = m.teamID INNER JOIN technologies h ON c.techID = h.techID INNER JOIN savingtypes y ON c.typeID = y.typeID INNER JOIN environments v ON c.envID = v.envID INNER JOIN users u ON c.userID = u.userID WHERE c.csDate >= ? AND c.csDate <= ? ORDER BY c.csSavings DESC LIMIT 1"); $sql_largest->bind_param("ss", $thisMon, $thisFri); $sql_largest->execute(); $result_largest = $sql_largest->get_result(); if(mysqli_num_rows($result_largest) == 0) { # Default values in case there are no records yet $lar_teamName = "-"; $lar_techName = "-"; $lar_typeName = "-"; $lar_envName = "-"; $lar_csCause = "No data available"; $lar_csSteps = "No data available"; $lar_csSavings = "-"; $lar_csActor = ""; $lar_csDate = "No data available"; } else { while($row_largest = mysqli_fetch_array($result_largest)) { $lar_teamName = htmlspecialchars($row_largest['teamName']); $lar_techName = htmlspecialchars($row_largest['techName']); $lar_typeName = htmlspecialchars($row_largest['typeName']); $lar_envName = htmlspecialchars($row_largest['envName']); $lar_csCause = htmlspecialchars($row_largest['csCause']); $lar_csSteps = htmlspecialchars($row_largest['csSteps']); $lar_csSavings = htmlspecialchars($row_largest['csSavings']); $lar_csActor = htmlspecialchars($row_largest['userFN']) . ' ' . htmlspecialchars($row_largest['userLN']); $lar_csDate = htmlspecialchars($row_largest['csDate']); } } # Default values - total savings per month for($i = 1; $i <= $valMonth; $i++) { # Set the default value for the bar graph data $bar_cs = 0; #Loop the SQL statement to get the monthly values $sql_barData = "SELECT SUM(csSavings) AS 'totSavings' FROM costsavings WHERE MONTH(csDate) = $i GROUP BY MONTH(csDate)"; $result_barData = $con->query($sql_barData) or die(mysqli_error($con)); while($bar_row = mysqli_fetch_array($result_barData)) { $bar_cs = $bar_row['totSavings']; if(empty($bar_cs) || $bar_cs === NULL) { $bar_cs = 0; } else { $bar_cs = $bar_row['totSavings']; } } $data_bar .= $bar_cs . ","; } $data_bar .= "],"; # Default values - doughnut charts # Default breakdown per team $sql_team_default = $sql_team . " GROUP BY c.teamID"; $result_team = $con->query($sql_team_default) or die(mysqli_error($con)); while($row = mysqli_fetch_array($result_team)) { $teamArray[] = $row['teamName']; $tsavingsArray[] = $row['totSavings']; } # Variables that will be passed to the doughnut chart js $tsavings_list = '[' . implode(', ', $tsavingsArray) . '],'; # Output: [num1, num2, ...], $teams_list = '["' . implode('", "', $teamArray) . '"],'; # Output: ["team1", "team2", ...], # Default breakdown per environment $sql_env_default = $sql_env . " GROUP BY c.envID"; $result_env = $con->query($sql_env_default) or die(mysqli_error($con)); while($e_row = mysqli_fetch_array($result_env)) { $envArray[] = $e_row['envName']; $esavingsArray[] = $e_row['totSavings']; } $esavings_list = '[' . implode(', ', $esavingsArray) . '],'; $env_list = '["' . implode('", "', $envArray) . '"],'; # Default breakdown per technology $sql_tech_default = $sql_tech . " GROUP BY c.techID"; $result_tech = $con->query($sql_tech_default) or die(mysqli_error($con)); while($h_row = mysqli_fetch_array($result_tech)) { $techArray[] = $h_row['techName']; $hsavingsArray[] = $h_row['totSavings']; } $hsavings_list = '[' . implode(', ', $hsavingsArray) . '],'; $tech_list = '["' . implode('", "', $techArray) . '"],'; # Default breakdown per savings type $sql_type_default = $sql_type . " GROUP BY c.typeID"; $result_type = $con->query($sql_type_default) or die(mysqli_error($con)); while($y_row = mysqli_fetch_array($result_type)) { $typeArray[] = $y_row['typeName']; $ysavingsArray[] = $y_row['totSavings']; } $ysavings_list = '[' . implode(', ', $ysavingsArray) . '],'; $type_list = '["' . implode('", "', $typeArray) . '"],'; # Default values - latest initiatives/entries $sql_latest_default = $sql_latest . " ORDER BY csDate DESC LIMIT 10"; $result_latest = $con->query($sql_latest_default) or die(mysqli_error($con)); $list_latest = ""; while($l_row = mysqli_fetch_array($result_latest)) { $csID = $l_row['csID']; $csDate = htmlspecialchars($l_row['csDate']); $teamName = htmlspecialchars($l_row['teamName']); $techName = htmlspecialchars($l_row['techName']); $typeName = htmlspecialchars($l_row['typeName']); $envName = htmlspecialchars($l_row['envName']); $csSavings = htmlspecialchars($l_row['csSavings']); #display the date without the year $displayDate = date_format(date_create($csDate), 'm/d'); $list_latest .= " <tr class='clickable-row' data-href='details.php?rid=$csID' style='cursor: pointer;'> <td>$displayDate</td> <td>$teamName</td> <td>$techName</td> <td>$envName</td> <td>$typeName</td> <td> <span class='float-left'>$</span> <span class='float-right'>$csSavings</span> </td> </tr>"; } } # When the filter button is pressed... if(isset($_POST['btnFilter'])) { # Get the value of the selected item in the filter dropdown $filterTeam = $_POST['filterTeam']; # Redirect to self with the filter parameter header('location: ' . $_SERVER['PHP_SELF'] . $filterTeam); } ?><file_sep>LIMITATIONS - Bar chart display is limited to displaying the records for the current year only, starting from January of the current year. - Cost Savings Initiatives table's fit-to-screen design uses CSS that is compatible with modern browsers only (Firefox v19.0+, Chrome v20.0+, IE 9.0+, Safari 6.0+). - The user that inputs the reocrd is automatically set the the record's owner. - Tracking protection (i.e. Firefox's tracking protection in incognito mode) and other blockers prevent the Slack and FB share buttons from displaying on the page. ASSUMPTIONS - The Dashboard's filtering of data is done per team. - Inputting of data for cost savings includes a complete set of data (i.e. there is data for an initial and final cost). ADDITIONAL NOTES - Picture uploading replaced by initial and final cost input - Pagination in the table view disabled - the screenshot link is a potential security breach becauserecords are viewable via the url - currently using PHP's password_hash() function for encryption of password <file_sep><?php $pageTitle = "Record Details"; ini_set('display_errors', 0); $readonly = ""; $msgDisplay = ""; # For the ability to make use of the functions as well as connect to the database include_once str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/controllers/function.php'); include_once str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/controllers/config.php'); if(isset($_GET['rid'])) { # Bind the get value $recordID = $_GET['rid']; # Validate that the ID exists in the records $sql_validate = $con->prepare("SELECT csID FROM costsavings WHERE csID = ?"); $sql_validate->bind_param("i", $recordID); $sql_validate->execute(); $result_validate = $sql_validate->get_result(); if(mysqli_num_rows($result_validate) == 0) { # The record does not exist - show error header('location: error.php'); } else { # The record exists; get the record information $sql_record = $con->prepare("SELECT j.teamName, v.envName, h.techName, y.typeName, u.userFN, u.userLN, c.userID, csDate, csCause, csSteps, csInitial, csFinal, csSavings FROM costsavings c INNER JOIN journeyteams j ON c.teamID = j.teamID INNER JOIN environments v ON c.envID = v.envID INNER JOIN technologies h ON c.techID = h.techID INNER JOIN savingtypes y ON c.typeID = y.typeID INNER JOIN users u ON c.userID = u.userID WHERE csID = ?"); $sql_record->bind_param("i", $recordID); $sql_record->execute() or die(mysqli_error($con)); $result_record = $sql_record->get_result(); while($row = mysqli_fetch_array($result_record)) { $teamName = htmlspecialchars($row['teamName']); $envName = htmlspecialchars($row['envName']); $techName = htmlspecialchars($row['techName']); $typeName = htmlspecialchars($row['typeName']); $csDate = htmlspecialchars($row['csDate']); $userID = htmlspecialchars($row['userID']); $userName = htmlspecialchars($row['userFN']) . ' ' . htmlspecialchars($row['userLN']); $csCause = htmlspecialchars($row['csCause']); $csSteps = htmlspecialchars($row['csSteps']); $csInitial = htmlspecialchars($row['csInitial']); $csFinal = htmlspecialchars($row['csFinal']); $csSavings = htmlspecialchars($row['csSavings']); } # These values will be passed to the header.php for use in the meta tags # Change the displayed format for the date field $displayDate = date('m/d/Y', strtotime($csDate)); # This is used by Slack as a default title for the share text $metaTitle = $userName . " of Team " . $teamName . " applied the solution: '" . $csSteps . "' on " . $techName . " and saved a total of $" . $csSavings . ". Click on the link to view the details."; # This is used by Facebook as its default title in the share card/link $metaDescription = $userName . " implemented '" . $csSteps . "' and saved a total of USD " . $csSavings . ". Click the link to view the details."; if(isset($_GET['viewonly'])) { include_once 'includes/header_viewonly.php'; } else { # Load the regular header # This is loaded after the sql statements so data can be properly passed to the meta tags # (used for the default sharing message) include_once 'includes/header.php'; } # Get the userID of the record. If it matches the session ID, enable editing if($userID == $accID) { # Show the update button $showButton = ""; # If the update button is pressed... if(isset($_POST['btnUpdate'])) { # Get the input values from the form $inpCause = mysqli_real_escape_string($con, $_POST['inpCause']); $inpSteps = mysqli_real_escape_string($con, $_POST['inpSteps']); $inpInitial = str_replace(",", "", mysqli_real_escape_string($con, $_POST['inpInitial'])); $inpFinal = str_replace(",", "", mysqli_real_escape_string($con, $_POST['inpFinal'])); $totSavings = $inpInitial - $inpFinal; # Validation: input for the problem and solution textarea fields must not be empty or all whitespace if(empty(trim($inpCause)) || empty(trim($inpSteps))) { $msgDisplay = errorAlert("Input for the problem and/or solution must not be empty."); } else { # Update the record with the input $sql_update = $con->prepare("UPDATE costsavings SET csCause = ?, csSteps = ?, csInitial = ?, csFinal = ?, csSavings = ? WHERE csID = ?"); $sql_update->bind_param("ssdddi", $inpCause, $inpSteps, $inpInitial, $inpFinal, $totSavings, $recordID); $sql_update->execute() or die(mysqli_error($con)); $txtEvent = "Updated the information of cost savings record #" . $recordID; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("Successfully updated the record."); header('refresh: 1'); } } } else { # Set the readonly property to the input fields $readonly = "readonly"; # Hide the update button $showButton = "style='display: none;'"; if(isset($_POST['btnUpdate'])) { $msgDisplay = errorAlert("You are not allowed to perform any changes on this record."); } } } } else { header('location: error.php'); } ?><file_sep><?php $pageTitle = "Manage Access"; include 'includes/header.php'; # Determine if the current user has access to the page # If not, redirect to the home page $allowAccess = allowAccess($con, $accID); if($allowAccess != 1) { header('location: error.php'); } # Query the records in the database $sql_users = "SELECT a.accountID, u.userFN, u.userLN, a.accountStatus, s.accessRole FROM accounts a INNER JOIN users u ON a.userID = u.userID INNER JOIN access s ON a.accountAccess = s.accessID"; $result_users = $con->query($sql_users) or die(mysqli_error($con)); $list_users = ""; while($row = mysqli_fetch_array($result_users)) { $accountID = $row['accountID']; $userFN = $row['userFN']; $userLN = $row['userLN']; $userName = $userFN . ' ' . $userLN; $accessRole = $row['accessRole']; $def_status = $row['accountStatus']; $statusText = listStatus($con, $def_status); $list_users .= " <tr> <td class='text-center'>$userName</td> <td class='text-center'>$accessRole</td> <td class='text-center'>$statusText</td> <td class='text-center'> <a href='user.php?uid=$accountID' class='float-right'> <i class='fa fa-edit fa-fw'></i> </a> </td> </tr> "; } ?><file_sep><?php include 'controllers/user_controller.php'; # HTML content for the popover $content = " <dl> <dt>Administrator</dt> <dd>Access to all pages.</dd> <dt>User (Elevated)</dt> <dd>User access + <i class='fa fa-folder-open'></i> Manage Data page/s.</dd> <dt>User</dt> <dd>Access to <i class='fa fa-chart-pie'></i> Dashboard and <i class='fa fa-piggy-bank'></i> Cost Savings Initiatives only.</dd> </dl> "; ?> <div class="row"> <div class="col-lg-12"> <div class="card mb-3"> <div class="card-header"> <h5>Edit Access</h5> </div> <div class="card-body"> <h1 class="display-4"><?php echo $userName; ?></h1> <?php echo $msgDisplay; ?> <!-- <div class="row"> <div class="col-sm-12 col-lg-4"> <div class="form-group"> <label for="dispTeam">Journey Team</label> <input type="text" id="dispTeam" name="dispTeam" class="form-control" value="<?php echo $teamName; ?>" readonly="true"> </div> </div> <div class="col-sm-12 col-lg-4"> <div class="form-group"> <label for="dispEnv">Environment</label> <input type="text" id="dispEnv" name="dispEnv" class="form-control" value="<?php echo $envName; ?>" readonly="true"> </div> </div> <div class="col-sm-12 col-lg-4"> <div class="form-group"> <label for="dispTech">Cloud/Dev Ops Technology</label> <input type="text" id="dispTech" name="dispTech" class="form-control" value="<?php echo $techName; ?>" readonly="true"> </div> </div> </div> <hr />--> <br /> <div class="row"> <div class="col-lg-12"> <div class="card-deck"> <div class="card"> <div class="card-body"> <form method="POST"> <div class="form-group"> <label for="inpAccess"> Access Level <span rel="popover" data-placement="right" data-trigger="hover" data-toggle="popover" data-html="true" data-content="<?php echo $content; ?>"><i class="far fa-question-circle fa-fw" style="color: #007bff;"></i></span> </label> <select class="form-control" id="inpAccess" name="inpAccess"> <?php echo listAccess($con, $def_access); ?> </select> </div> <div class="form-group"> <button class="btn btn-primary float-right" id="btnSave" name="btnSave">Save Changes</button> </div> </form> </div> </div> <div class="card"> <div class="card-body"> <div class="form-group"> <label for="inpStatus">Account Status</label> <input type="text" id="dispStatus" name="dispStatus" class="form-control" value="<?php echo listStatus($con, $def_status); ?>" readonly="true"> </div> <div class="form-group"> <?php echo $displayButton; ?> </div> </div> </div> </div> </div> </div> </div> <div class="card-footer"> <a href="manage.php" class="btn btn-secondary"><i class="fa fa-angle-left fa-fw"></i> Back to List</a> </div> </div> </div> </div> <!-- Modal for the archive confirmation prompt --> <div class="modal fade" id="archiveModal" tabindex="-1" role="dialog" aria-labelledby="archiveModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="archiveModalLabel">Confirm Action</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <form class="form-horizontal" method="POST"> <div class="modal-body"> <div class="row"> <div class="col-sm-12 col-md-10 offset-md-1"> <p class="text-center"> Archiving an account will disable its access to the system until reactivated. <br /><br /> Please enter your password to confirm: </p> <input type="password" class="form-control text-center" id="inpConfirm" name="inpConfirm" /> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-danger" name="btnArchive" id="btnArchive">Archive Account</button> </div> </form> </div> </div> </div> <!-- Modal for the confirmation of account activation prompt --> <div class="modal fade" id="activateModal" tabindex="-1" role="dialog" aria-labelledby="activateModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="activateModalLabel">Confirm Action</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <form class="form-horizontal" method="POST"> <div class="modal-body"> <div class="row"> <div class="col-sm-12 col-md-10 offset-md-1"> <p class="text-center"> You are about to activate/re-activate an account. <br /> This will enable it to have access to the system and its features. <br /><br /> Please enter your password to confirm: </p> <input type="password" class="form-control text-center" id="inpConfirm" name="inpConfirm" /> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-success" name="btnActivate" id="btnActivate">Activate Account</button> </div> </form> </div> </div> </div> <?php include 'controllers/includes/footer.php'; ?> <script type="text/javascript"> // Initialization of popover // Ref: https://stackoverflow.com/questions/30051283/ $(function () { $('[data-toggle="popover"]').popover() }); </script><file_sep><?php $pageTitle = "AWS/DevOps Technologies"; include_once 'includes/header.php'; # Echoes a redirect line if the user does not have access to the page accessPage($con, $accID); # Query to get the records $sql_list = "SELECT techID, techName FROM technologies"; $result_list = $con->query($sql_list) or die(mysqli_error($con)); $list_tech = ""; if(mysqli_num_rows($result_list) == 0) { } else { # Display results in a table format while($row = mysqli_fetch_array($result_list)) { $techID = $row['techID']; $techName = htmlspecialchars($row['techName']); $list_tech .= " <tr> <td>$techName <a href='edit_tech.php?id=$techID' class='float-right'> <span class='fa fa-edit fa-fw'></span> </a> </td> </tr>"; } } if(isset($_POST['btnAdd'])) { $inpName = inpcheck($_POST['inpName']); if(empty($inpName)) { $msgDisplay = errorAlert("Please make sure that your input is valid."); } else { # Convert the input into uppercase for validation $tName = strtoupper($inpName); # Validate that the input is not a duplicate $sql_validate = "SELECT techName FROM technologies WHERE UPPER(techName) = '$tName'"; $result_validate = $con->query($sql_validate) or die(mysqli_error($con)); if(mysqli_num_rows($result_validate) > 0) { $msgDisplay = errorAlert("The record you are trying to add already exists."); } else { $stmt_insert = $con->prepare("INSERT INTO technologies(techName) VALUES (?)"); $stmt_insert->bind_param("s", $inpName); $stmt_insert->execute(); $txtEvent = "Added a new aws/dev ops technology: " . $inpName; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("Successfully added a new record."); header('Refresh: 1'); } } } ?><file_sep><?php include 'controllers/view_controller.php'; ?> <div class="row"> <div class="col-md-12"> <?php echo $msgDisplay; ?> <div class="card mb-3"> <div class="card-header"> <h4>Cost Savings Initiatives <button class="btn btn-primary float-right" data-toggle="modal" data-target="#addCSModal"> Add a New Record </button> </h4> </div> <div class="card-body"> <div class="table table-responsive table-hover"> <table class="table-bordered display pageResize" id="savingsTable" width="100%" cellspacing="0"> <thead> <tr> <th class="text-center">Date</th> <th class="text-center">Journey Team</th> <th class="text-center">Cloud/DevOps Technology</th> <th class="text-center">Environment</th> <th class="text-center">Type</th> <th class="text-center">Executed By</th> <th class="text-center">Inital Cost</th> <th class="text-center">Solution/s Implemented</th> <th class="text-center">Final Cost</th> <th class="text-center">Total Savings</th> </tr> </thead> <tbody> <?php echo $cs_list; ?> </tbody> <tfoot> <tr> <th class="text-center"></th> <th class="text-center">Journey Team</th> <th class="text-center">Cloud/DevOps Technology</th> <th class="text-center">Environment</th> <th class="text-center">Type</th> <th class="text-center">Executed By</th> <th class="text-center"></th> <th class="text-center"></th> <th class="text-center"></th> <th class="text-center"></th> </tr> </tfoot> </table> </div> </div> </div> </div> </div> <!-- Modal for creating a new record --> <div class="modal fade" id="addCSModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="addModalLabel">New Cost Savings Data</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <form class="form-horizontal" method="POST" enctype="multipart/form-data"> <div class="modal-body"> <div class="row"> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpTeam">Journey Team</label> <select class="form-control" name="inpTeam" id="inpTeam" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listTeams($con, $def_teamID); ?> </select> </div> </div> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpEnv">Environment</label> <select class="form-control" name="inpEnv" id="inpEnv" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listEnvironments($con, $def_envID); ?> </select> </div> </div> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpTech">Cloud/DevOps Technology</label> <select class="form-control" name="inpTech" id="inpTech" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listTech($con, $def_techID); ?> </select> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpType">Cost Savings Type</label> <select class="form-control" name="inpType" id="inpType" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listTypes($con); ?> </select> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpProj">Project Group</label> <select class="form-control" name="inpProj" id="inpProj" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listProjects($con); ?> </select> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpInitial">Inital Cost</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input class="form-control" type="text" name="inpInitial" id="inpInitial" required="true" /> </div> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpFinal">Final Cost</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input class="form-control" type="text" name="inpFinal" id="inpFinal" required="true" onkeyup="getTotal()" /> </div> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpCause">Root Cause</label> <textarea class="form-control" rows="10" name="inpCause" id="inpCause" maxlength="800" placeholder="Details of the problem encountered..." required="true"></textarea> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpSteps">Solution/s Implemented</label> <textarea class="form-control" rows="10" name="inpSteps" id="inpSteps" maxlength="800" placeholder="Steps taken in order to resolve the issue/s encountered..." required="true"></textarea> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6" style="display: none"> <div class="form-group"> <label for="inpName">Action Executed By</label> <input class="form-control" type="text" name="inpName" id="inpName" maxlength="50" placeholder="Enter a name..." value="<NAME>" required="true"> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpDate">Completion Date</label> <input class="form-control" type="date" name="inpDate" id="inpDate" min="2018-01-01" max="<?php echo $dateToday->format('Y-m-d'); ?>" required="true"> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpDate">Total Savings</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input type="text" class="form-control" id="sampledisp" name="sampledisp" readonly="true" placeholder="0.00"> </div> </div> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary" name="btnAdd" id="btnAdd">Add Record</button> </div> </form> </div> </div> </div> <!-- Update: as of 06/01/2018, image input is replaced with cost input Modal for the image zoom on click <div class="modal" tabindex="-1" role="dialog" id="imgModal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal Title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <img src="images/<?#php echo $displayInitial; ?>" width="100%" /> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> --> <?php #echo $imgModal; ?> <!-- Some custom js for the input masking, default input values, etc. --> <script type="text/javascript" src="js/custom.js"></script> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php include 'controllers/edit_proj_controller.php'; ?> <div class="row"> <div class="col-md-12"> <?php echo $msgDisplay; ?> <div class="card mb-3"> <div class="card-header"> Edit Project Details </div> <form class="form-horizontal" method="POST"> <div class="card-body"> <div class="form-group"> <label for="inpName">Project Name</label> <input class="form-control" type="text" name="inpName" id="inpName" maxlength="50" value="<?php echo $projectName; ?>" required="true"> </div> <div class="form-group"> <label for="inpDesc">Project Description</label> <textarea class="form-control" rows="5" name="inpDesc" id="inpDesc" maxlength="250" placeholder="Short description of the project..." required="true"><?php echo $projectDescription; ?></textarea> </div> </div> <div class="card-footer"> <button class="btn btn-primary float-right" id="btnSave" name="btnSave">Save Changes</button> <a href="add_proj.php" class="btn btn-secondary"><i class="fa fa-angle-left fa-fw"></i> Back to List</a> </div> </form> </div> </div> </div> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php include 'controllers/account_controller.php'; ?> <!-- Nav tabs --> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="account-tab" data-toggle="tab" href="#account" role="tab" aria-controls="account" aria-selected="true">My Account</a> </li> <li class="nav-item"> <a class="nav-link" id="recents-tab" data-toggle="tab" href="#recents" role="tab" aria-controls="recents" aria-selected="false">Cost Savings Entries</a> </li> </ul> <br /> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane active" id="account" role="tabpanel" aria-labelledby="account-tab"> <div class="card mb-3"> <div class="card-header"> Account Details </div> <div class="card-body"> <form class="forn-horizontal" method="POST"> <div class="row"> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpTeam">Journey Team</label> <select class="form-control" name="inpTeam" id="inpTeam"> <option selected="true" disabled="true">Choose one...</option> <option value="0" <?php echo $def_teamID == 0 ? "selected = 'true'" : ""; ?>>None</option> <?php echo listTeams($con, $def_teamID); ?> </select> </div> </div> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpEnv">Environment</label> <select class="form-control" name="inpEnv" id="inpEnv"> <option selected="true" disabled="true">Choose one...</option> <option value="0" <?php echo $def_envID == 0 ? "selected = 'true'" : ""; ?>>None</option> <?php echo listEnvironments($con, $def_envID); ?> </select> </div> </div> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpTech">Cloud/DevOps Technology</label> <select class="form-control" name="inpTech" id="inpTech"> <option selected="true" disabled="true">Choose one...</option> <option value="0" <?php echo $def_techID == 0 ? "selected = 'true'" : ""; ?>>None</option> <?php echo listTech($con, $def_techID); ?> </select> </div> </div> </div> <div class="row"> <div class="col-sm-12"> <small class="form-text text-muted align-bottom">The saved data will be used as the default values in the add form.</small> </div> <div class="col-sm-12"> <button type="submit" class="btn btn-primary float-right" id="btnSave" name="btnSave">Save Changes</button> </div> </div> </form> </div> </div> <?php echo $msgDisplay; ?> </div> <div class="tab-pane" id="recents" role="tabpanel" aria-labelledby="recents-tab"> <div class="table table-responsive table-hover"> <table class="table-bordered" id="recentsTable" width="100%" cellspacing="0"> <thead> <tr> <th class="text-center">Date</th> <th class="text-center">Journey Team</th> <th class="text-center">Cloud/DevOps Technology</th> <th class="text-center">Environment</th> <th class="text-center">Type</th> <th class="text-center">Inital Cost</th> <th class="text-center">Solution/s Implemented</th> <th class="text-center">Final Cost</th> <th class="text-center">Total Savings</th> </tr> </thead> <tbody> <?php echo $list_records; ?> </tbody> <tfoot> <tr> <th class="text-center"></th> <th class="text-center"></th> <th class="text-center"></th> <th class="text-center"></th> <th class="text-center"></th> <th class="text-center"></th> <th class="text-center"></th> <th class="text-center"></th> <th class="text-center"></th> </tr> </tfoot> </table> </div> </div> </div> <script type="text/javascript"> $(document).ready(function() { $('#recentsTable').DataTable( { "order": [[ 0, "desc" ]], pageResize: true, scrollY: '55vh', scrollX: '100%', scrollCollapse: true, paging: false, initComplete: function () { this.api().columns([1,2,3,4]).every( function () { var column = this; var title = $(this).text(); var select = $('<select class="form-control"><option value="">Show All</option></select>') .appendTo( $(column.footer()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option value="'+d+'">'+d+'</option>' ) } ); } ); } } ); } ); $(document).ready(function () { $('.dataTables_filter input[type="search"]'). attr('placeholder','Enter a keyword...'). css({'width':'300px','display':'inline-block'}); }); </script> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php $pageTitle = "Cost Savings Types"; include_once 'includes/header.php'; # Echoes a redirect line if the user does not have access to the page accessPage($con, $accID); # Query to display records $sql_list = "SELECT typeID, typeName FROM savingtypes"; $result_list = $con->query($sql_list) or die(mysqli_error($con)); $list_types = ""; if(mysqli_num_rows($result_list) == 0) { } else { while($row = mysqli_fetch_array($result_list)) { $typeID = $row['typeID']; $typeName = htmlspecialchars($row['typeName']); $list_types .= " <tr> <td>$typeName <a href='edit_type.php?id=$typeID' class='float-right'><span class='fa fa-edit fa-fw'></span></a></td> </tr>"; } } if(isset($_POST['btnAdd'])) { $inpName = inpcheck($_POST['inpName']); if(empty($inpName)) { $msgDisplay = errorAlert("Please make sure that your input is valid and try again."); } else { # Convert to uppercase for validation $tName = strtoupper($inpName); # Validate duplication of records $sql_validate = "SELECT typeName FROM savingtypes WHERE UPPER(typeName) = '$tName'"; $result_validate = $con->query($sql_validate) or die(mysqli_error($con)); if(mysqli_num_rows($result_validate) > 0) { $msgDisplay = errorAlert("The team you are adding already exists."); } else { $stmt_insert = $con->prepare("INSERT INTO savingtypes (typeName) VALUES (?)"); $stmt_insert->bind_param("s", $inpName); $stmt_insert->execute(); $txtEvent = "Added a new cost saving type: " . $inpName; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("Successfully added a new savings type."); header('Refresh: 1'); } } } ?><file_sep><?php #localhost paameters $server = "127.0.0.1"; # Host name or IP address $username = "root"; # MySQL username $password = ""; # MySQL password $database = "aws-csi"; # Database name # syntax: mysqli_connect(host, username, password, dbname, port, socket) $con = mysqli_connect($server, $username, $password, $database); # For testing # if(!$con) # { # echo "Database connection error."; # } ?><file_sep><?php $pageTitle = "My Account"; include_once 'includes/header.php'; ini_set('display_errors', 0); $userID = getUserID($con, $accID); $selected = ""; $msgDisplay = ""; # Get the data for the recent entries for the current user $sql_recent = $con->prepare("SELECT s.csID, s.csCause, s.csSteps, s.csDate, s.csSavings, s.csInitial, s.csFinal, m.teamName, h.techName, e.envName, y.typeName FROM costsavings s INNER JOIN journeyteams m ON s.teamID = m.teamID INNER JOIN technologies h ON s.techID = h.techID INNER JOIN environments e ON s.envID = e.envID INNER JOIN savingtypes y ON s.typeID = y.typeID WHERE s.userID = ? ORDER BY s.csDate DESC"); $sql_recent->bind_param("i", $accID); $sql_recent->execute(); $result_recent = $sql_recent->get_result(); # Display the results in a table format $list_records = ""; while($row = mysqli_fetch_array($result_recent)) { $csID = htmlspecialchars($row['csID']); $csCause = htmlspecialchars($row['csCause']); $csSteps = htmlspecialchars($row['csSteps']); $csDate = htmlspecialchars($row['csDate']); $displayDate = date('m/d/Y', strtotime($csDate)); $csSavings = htmlspecialchars($row['csSavings']); $csInitial = htmlspecialchars($row['csInitial']); $csFinal = htmlspecialchars($row['csFinal']); $teamName = htmlspecialchars($row['teamName']); $techName = htmlspecialchars($row['techName']); $envName = htmlspecialchars($row['envName']); $typeName = htmlspecialchars($row['typeName']); $list_records .= " <tr class='clickable-row' data-href='details.php?rid=$csID' style='cursor: pointer;'> <td>$displayDate</td> <td>$teamName</td> <td>$techName</td> <td>$envName</td> <td>$typeName</td> <td> <span class='float-left'>$</span> <span class='float-right'>$csInitial</span> </td> <td>$csSteps</td> <td> <span class='float-left'>$</span> <span class='float-right'>$csFinal</span> </td> <td> <span class='float-left'>$</span> <span class='float-right'>$csSavings</span> </td> </tr>"; } # Get the default values for the dropdowns $sql_default = $con->prepare("SELECT envID, teamID, techID FROM users WHERE userID = ?"); $sql_default->bind_param("i", $userID); $sql_default->execute(); $result_default = $sql_default->get_result(); while ($row = mysqli_fetch_array($result_default)) { # Get the values... $def_envID = $row['envID']; $def_teamID = $row['teamID']; $def_techID = $row['techID']; } # Code for saving/updating the dropdown values if(isset($_POST['btnSave'])) { # Get the value from the form (set default to 0 if there is no input) $inpTeam = htmlspecialchars($_POST['inpTeam']); if(empty($inpTeam)) { $inpTeam = 0; } $inpEnv = htmlspecialchars($_POST['inpEnv']); if(empty($inpEnv)) { $inpEnv = 0; } $inpTech = htmlspecialchars($_POST['inpTech']); if(empty($inpTech)) { $inpTech = 0; } # Update the values in the database $sql_update = $con->prepare("UPDATE users SET envID = ?, teamID = ?, techID = ? WHERE userID = ?"); $sql_update->bind_param("iiii", $inpEnv, $inpTeam, $inpTech, $userID); $sql_update->execute(); $txtEvent = "Updated their account information."; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("You have successfully updated your account information."); header('refresh: 1'); } ?><file_sep><?php $pageTitle = "Audit Logs"; include_once 'includes/header.php'; # Determine if the current user has access to the page # If not, redirect to the home page $allowAccess = allowAccess($con, $accID); if($allowAccess != 1) { header('location: error.php'); } # Get the records from the logs table $sql_logs = "SELECT logDate, logUser, logEvent FROM logs ORDER BY logDate DESC"; $result_logs = $con->query($sql_logs) or die(mysqli_error($con)); $list_logs = ""; while($row = mysqli_fetch_array($result_logs)) { # Change the output format for the date $logDate = date('m/d/Y H:i:s', strtotime($row['logDate'])); $logUser = $row['logUser']; $logEvent = $row['logEvent']; # Display the results as a table format $list_logs .= " <tr> <td>$logDate</td> <td>$logUser</td> <td>$logEvent</td> </tr> "; } ?><file_sep><?php $pageTitle = "Cost Savings Initiatives"; include_once 'includes/header.php'; $userID = getUserID($con, $accID); # Date to display as the default value in the add record form $dateToday = new DateTime(date("Y-m-d")); # Get the records for the table $sql_list = "SELECT s.csID, s.csCause, s.csSteps, s.csDate, s.csSavings, s.csInitial, s.csFinal, m.teamName, h.techName, e.envName, y.typeName, u.userFN, u.userLN FROM costsavings s INNER JOIN journeyteams m ON s.teamID = m.teamID INNER JOIN technologies h ON s.techID = h.techID INNER JOIN environments e ON s.envID = e.envID INNER JOIN savingtypes y ON s.typeID = y.typeID INNER JOIN users u ON s.userID = u.userID ORDER BY s.csDate DESC"; $result_list = $con->query($sql_list) or die(mysqli_error($con)); $cs_list = ""; # $imgModal = ""; -- image uploading removed (06/01/2018) while($row = mysqli_fetch_array($result_list)) { $csID = htmlspecialchars($row['csID']); $csCause = htmlspecialchars($row['csCause']); $csSteps = htmlspecialchars($row['csSteps']); $csDate = htmlspecialchars($row['csDate']); $displayDate = date('m/d/Y', strtotime($csDate)); $csSavings = htmlspecialchars($row['csSavings']); $csInitial = htmlspecialchars($row['csInitial']); $csFinal = htmlspecialchars($row['csFinal']); $teamName = htmlspecialchars($row['teamName']); $techName = htmlspecialchars($row['techName']); $envName = htmlspecialchars($row['envName']); $typeName = htmlspecialchars($row['typeName']); $userName = htmlspecialchars($row['userFN']) . ' ' . htmlspecialchars($row['userLN']); # $displayInitial = ($csInitial === null || empty($csInitial)) ? "placeholder.jpg" : $csInitial; # $displayFinal = ($csFinal === null || empty($csFinal)) ? "placeholder.jpg" : $csFinal; # -- removed (06/01/2018) $cs_list .= " <tr class='clickable-row' data-href='details.php?rid=$csID' style='cursor: pointer;'> <td>$displayDate</td> <td>$teamName</td> <td>$techName</td> <td>$envName</td> <td>$typeName</td> <td>$userName</td> <td> <span class='float-left'>$</span> <span class='float-right'>$csInitial</span> </td> <td>$csSteps</td> <td> <span class='float-left'>$</span> <span class='float-right'>$csFinal</span> </td> <td> <span class='float-left'>$</span> <span class='float-right'>$csSavings</span> </td> </tr>"; # Update 06/01/2018 -- image input is replaced with cost (number) input /*$imgModal .= " <div class='modal fade' tabindex='-1' role='dialog' id='imgModal$csID'> <div class='modal-dialog modal-lg' role='document'> <div class='modal-content'> <div class='modal-header'> <p class='modal-title'></p> <button type='button' class='close' data-dismiss='modal' aria-label='Close'> <span aria-hidden='true'>&times;</span> </button> </div> <div class='modal-body'> <div id='imgCarousel$csID' class='carousel slide' data-ride='carousel'> <ul class='carousel-indicators'> <li data-target='#imgCarousel$csID' data-slide-to='0' class='active'></li> <li data-target='#imgCarousel$csID' data-slide-to='1'></li> </ul> <div class='carousel-inner'> <div class='carousel-item active'> Initial Screenshot ($displayInitial) <img class='img-fluid' src='images/$displayInitial' width='100%'> </div> <div class='carousel-item'> FInal Screenshot ($displayFinal) <img class='img-fluid' src='images/$displayFinal' width='100%'> </div> </div> <a class='carousel-control-prev' data-target='#imgCarousel$csID' data-slide='prev'> <span class='carousel-control-prev-icon'></span> </a> <a class='carousel-control-next' data-target='#imgCarousel$csID' data-slide='next'> <span class='carousel-control-next-icon'></span> </a> </div> </div> <div class='modal-footer'> <button type='button' class='btn btn-secondary' data-dismiss='modal'>Close</button> </div> </div> </div> </div>";*/ } # Get the default values for the dropdowns $sql_default = $con->prepare("SELECT envID, teamID, techID FROM users WHERE userID = ?"); $sql_default->bind_param("i", $userID); $sql_default->execute(); $result_default = $sql_default->get_result(); while ($row = mysqli_fetch_array($result_default)) { # Get the values... $def_envID = $row['envID']; $def_teamID = $row['teamID']; $def_techID = $row['techID']; } # Insert the input into the database if(isset($_POST['btnAdd'])) { # Get the userID value based on the session's accID value $userID = getUserID($con, $accID); # Retrieve the input data from the form $inpTeam = mysqli_real_escape_string($con, $_POST['inpTeam']); $inpEnv = mysqli_real_escape_string($con, $_POST['inpEnv']); $inpTech = mysqli_real_escape_string($con, $_POST['inpTech']); $inpType = mysqli_real_escape_string($con, $_POST['inpType']); $inpProj = mysqli_real_escape_string($con, $_POST['inpProj']); # Rremove the commas from the money input $inpInitial = str_replace(",", "", mysqli_real_escape_string($con, $_POST['inpInitial'])); $inpFinal = str_replace(",", "", mysqli_real_escape_string($con, $_POST['inpFinal'])); $totSavings = $inpInitial - $inpFinal; $inpCause = mysqli_real_escape_string($con, $_POST['inpCause']); $inpSteps = mysqli_real_escape_string($con, $_POST['inpSteps']); #$inpName = mysqli_real_escape_string($con, $_POST['inpName']); -- will be automatically added via session ID $inpDate = mysqli_real_escape_string($con, $_POST['inpDate']); /* Update 06/01/2018 -- image input is replaced with cost (number) input #check the image uploaded if(!isset($_FILES['inpPhoto']) || $_FILES['inpPhoto']['error']) { #there is no input #1 - do not include in the insertion of records (current) || 2 - show an error prompt #CURRENT: inert 'placeholder.jpg' into the csInitial column $stmt_insert = $con->prepare("INSERT INTO costsavings (csCause, csActor, csDate, csSavings, csInitial, teamID, techID, envID, typeID) VALUES (?, ?, ?, ?, 'placeholder.jpg', ?, ?, ?, ?)"); $stmt_insert->bind_param("sssdiiii", $inpDesc, $inpName, $inpDate, $inpSave, $inpTeam, $inpTech, $inpEnv, $inpType); } else { #validate that the file is a valid image (to be added) #accepted file types: ??? $imgName = $_FILES['inpPhoto']['name']; #name of the image file $imgDir = $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . "/images/"; #file save location $imgNew = date('YmdHis') . "_" . basename($imgName); #add timestamp to filename $imgFile = $imgDir . $imgNew; #move the file to the new destination with the new file name move_uploaded_file($_FILES['inpPhoto']['tmp_name'], $imgFile); #insert the data into the database #the image itself will not be inserted directly in the database #instead, only the image name will be saved in the db while the file is saved locally $stmt_insert = $con->prepare("INSERT INTO costsavings (csCause, csActor, csDate, csSavings, csInitial, teamID, techID, envID, typeID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); $stmt_insert->bind_param("sssdsiiii", $inpDesc, $inpName, $inpDate, $inpSave, $imgNew, $inpTeam, $inpTech, $inpEnv, $inpType); } */ addRecord($con, $inpTeam, $inpEnv, $inpTech, $inpType, $inpInitial, $inpFinal, $totSavings, $inpCause, $inpSteps, $inpDate, $inpProj, $userID); $projName = getProjectName($con, $inpProj); $txtEvent = "Added a new cost savings entry for the project " . $projName . ", with a total savings of $" . $totSavings; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("Successfully inserted a new record."); header('Refresh: 1'); } ?><file_sep><?php $pageTitle = "Edit Access"; include_once 'includes/header.php'; $msgDisplay = ""; # Determine if the current user has access to the page # If not, redirect to the home page $allowAccess = allowAccess($con, $accID); if($allowAccess != 1) { header('location: error.php'); } # Check if the user id parameter has been passed if(isset($_GET['uid'])) { $uid = $_GET['uid']; # Validate that the uid value is valid/existing $sql_validate = $con->prepare("SELECT userID FROM users WHERE userID = ?"); $sql_validate->bind_param("i", $uid); $sql_validate->execute(); $result_validate = $sql_validate->get_result(); if(mysqli_num_rows($result_validate) == 0) { # No record with the requested ID exists header('location: error.php'); } else { # Get the display name $sql_name = $con->prepare("SELECT userFN, userLN FROM users WHERE userID = ?"); $sql_name->bind_param("i", $uid); $sql_name->execute(); $result_name = $sql_name->get_result(); while($acn = mysqli_fetch_array($result_name)) { $userFN = $acn['userFN']; $userLN = $acn['userLN']; $userName = $userFN . ' ' . $userLN; } # Get the data for the team, env, and tech /* $sql_details = $con->prepare("SELECT v.envName, m.teamName, t.techName FROM users u INNER JOIN environments v ON u.envID = v.envID INNER JOIN journeyteams m ON u.teamID = m.teamID INNER JOIN technologies t ON u.techID = t.techID WHERE userID = ?"); $sql_details->bind_param("i", $uid); $sql_details->execute(); $result_details = $sql_details->get_result(); while($row = mysqli_fetch_array($result_details)) { $envName = $row['envName']; $teamName = $row['teamName']; $techName = $row['techName']; } */ # Get the account status and access $sql_account = $con->prepare("SELECT accountAccess, accountStatus FROM accounts WHERE userID = ?"); $sql_account->bind_param("i", $uid); $sql_account->execute(); $result_account = $sql_account->get_result(); # Get the user's data for account status and access while($act = mysqli_fetch_array($result_account)) { $def_status = $act['accountStatus']; $def_access = $act['accountAccess']; } # Change the button being displayed depending on the account status value # (Display 'Archive' for active accounts, 'Activate' for archived accounts) $displayButton = ""; if($def_status == 0) { # Account is inactive/disabled; display 'Activate' button instead $displayButton = "<button class='btn btn-success float-right' data-toggle='modal' data-target='#activateModal' id='btnActive' name='btnActive'>Activate Account</button>"; } else { # Account is active; display 'Archive' (also as default display) $displayButton = "<button class='btn btn-danger float-right' data-toggle='modal' data-target='#archiveModal' id='btnModal' name='btnModal'>Archive Account</button>"; } # Save the changes on the access level on button press if(isset($_POST['btnSave'])) { # Get the access level value $inpAccess = $_POST['inpAccess']; # Update the value in the database $sql_update = $con->prepare("UPDATE accounts SET accountAccess = ? WHERE userID = ?"); $sql_update->bind_param("ii", $inpAccess, $uid); $sql_update->execute() or die(msqli_error($con)); $txtEvent = "Changed the access level of " . $userName . " from " . $def_access . " to " . $inpAccess; logEvent($con, $accID, $txtEvent); $msgText = "Successfully updated the access level."; $msgDisplay = successAlert($msgText); header('refresh: 1'); } # Password re-entry verification on archiving of account if(isset($_POST['btnArchive'])) { # Get the input password $inpPassword = $_POST['inpConfirm']; # Verify that the input and stored values are the same if(confirmPassword($con, $accID, $inpPassword) == 1) { # Update the account's status value to 0 (inactive/archived) $sql_archive = $con->prepare("UPDATE accounts SET accountStatus = 0 WHERE userID = ?"); $sql_archive->bind_param("i", $uid); $sql_archive->execute(); $txtEvent = "Archived " . $userName . "'s account (account ID #" . $uid . ")"; logEvent($con, $accID, $txtEvent); $msgText = "Successfully archived the account."; $msgDisplay = successAlert($msgText); header('refresh: 1'); } else { $msgText = "Your password input is incorrect."; $msgDisplay = errorAlert($msgText); } } # Password re-entry verification on activating/re-activating of account if(isset($_POST['btnActivate'])) { # Get the input password $inpPassword = $_POST['inpConfirm']; # Verify the input vs the stored if(confirmPassword($con, $accID, $inpPassword) == 1) { # Update the account status value to 1 (active) $sql_active = $con->prepare("UPDATE accounts SET accountStatus = 1 WHERE userID = ?"); $sql_active->bind_param("i", $uid); $sql_active->execute(); $txtEvent = ""; logEvent($con, $accID, $txtEvent); $msgText = "Successfully activated the account."; $msgDisplay = successAlert($msgText); header('refresh: 1'); } else { $msgText = "Your password input is incorrect."; $msgDisplay = errorAlert($msgText); } } } } else { header('location: error.php'); } ?><file_sep><?php include 'controllers/index_controller.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <!-- For IE 9 and below. ICO should be 32x32 pixels in size --> <!--[if IE]><link rel="shortcut icon" href="images/icons/awslogo.png"><![endif]--> <!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> <link rel="apple-touch-icon-precomposed" href="images/icons/awslogo.png"> <!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. --> <link rel="icon" href="images/icons/awslogo.png"> <link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="lib/fontawesome/css/fontawesome-all.css" rel="stylesheet" type="text/css"> <link href="css/sb-admin.css" rel="stylesheet"> <title>AWS Cost Savings Knowledge Base</title> <style type="text/css"> body { position: fixed; top: 0; left: 0; width: 100%; height: 100%; /* background-image: url('images/background.jpg'); */ background-repeat: no-repeat; background-attachment: fixed; background-size: 100%; opacity: 0.9; } .vertical-center { min-height: 100%; min-height: 100vh; display: flex; align-items: center; } </style> </head> <body> <div class="jumbotron jumbotron-fluid vertical-center"> <div class="container"> <h1 class="display-3 text-center"><strong>AWS Cost Savings Knowledge Base</strong></h1> <br class="my-3" /> <div class="col-lg-8 offset-lg-2"> <p class="lead text-center"> <form class="form-horizontal" method="POST" action="search.php"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fa fa-search fa-fw"></i></span> </div> <input type="text" class="form-control" placeholder="Enter a keyword..." name="inpSearch" id="inpSearch"> <div class="input-group-append"> <button class="btn btn-dark" name="btnSearch" id="btnSearch">&emsp; Search &emsp;</button> </div> </div> </form> </p> <p class="lead text-center"> <a href="view.php" class="btn btn-outline-dark" class="form-control"><i class="fa fa-fw fa-list-ul"></i> View All Records</a> <button class="btn btn-outline-dark" data-toggle="modal" data-target="#addCSModal" name="btnAdd" id="btnAdd"><i class="fa fa-fw fa-plus"></i> Add New</button> </p> </div> <div class="col-lg-8 offset-lg-2"> <?php echo $msgDisplay; ?> </div> </div> </div> <!-- Modal for creating a new record --> <div class="modal fade" id="addCSModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="addModalLabel">New Cost Savings Data</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <form class="form-horizontal" method="POST" enctype="multipart/form-data"> <div class="modal-body"> <div class="row"> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpTeam">Journey Team</label> <select class="form-control" name="inpTeam" id="inpTeam" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listTeams($con, $def_teamID); ?> </select> </div> </div> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpEnv">Environment</label> <select class="form-control" name="inpEnv" id="inpEnv" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listEnvironments($con, $def_envID); ?> </select> </div> </div> <div class="col-sm-12 col-md-4"> <div class="form-group"> <label for="inpTech">Cloud/DevOps Technology</label> <select class="form-control" name="inpTech" id="inpTech" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listTech($con, $def_techID); ?> </select> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpType">Cost Savings Type</label> <select class="form-control" name="inpType" id="inpType" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listTypes($con); ?> </select> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpProj">Project Group</label> <select class="form-control" name="inpProj" id="inpProj" required="true"> <option selected="true" disabled="true">Choose one...</option> <?php echo listProjects($con); ?> </select> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpInitial">Inital Cost</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input class="form-control" type="text" name="inpInitial" id="inpInitial" required="true" /> </div> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpFinal">Final Cost</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input class="form-control" type="text" name="inpFinal" id="inpFinal" required="true" onkeyup="getTotal()" /> </div> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpCause">Root Cause</label> <textarea class="form-control" rows="10" name="inpCause" id="inpCause" maxlength="800" placeholder="Details of the problem encountered..." required="true"></textarea> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpSteps">Solution/s Implemented</label> <textarea class="form-control" rows="10" name="inpSteps" id="inpSteps" maxlength="800" placeholder="Steps taken in order to resolve the issue/s encountered..." required="true"></textarea> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-md-6" style="display: none"> <div class="form-group"> <label for="inpName">Action Executed By</label> <input class="form-control" type="text" name="inpName" id="inpName" maxlength="50" placeholder="Enter a name..." value="<NAME>" required="true"> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpDate">Completion Date</label> <input class="form-control" type="date" name="inpDate" id="inpDate" min="2018-01-01" max="<?php echo $dateToday->format('Y-m-d'); ?>" required="true"> </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> <label for="inpDate">Total Savings</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input type="text" class="form-control" id="sampledisp" name="sampledisp" readonly="true" placeholder="0.00"> </div> </div> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary" name="btnAdd" id="btnAdd">Add Record</button> </div> </form> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="js/jquery-3.3.1.min.js"></script> <script src="lib/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="js/jquery.easing.min.js"></script> <!-- sb-admin template js --> <script src="js/sb-admin.min.js"></script> <script src="js/sb-admin-datatables.min.js"></script> <script src="js/sb-admin-charts.min.js"></script> <!-- input masking --> <script src="js/jquery.maskMoney.min.js"></script> <!-- Some custom js for the input masking, default input values, etc. --> <script type="text/javascript" src="js/custom.js"></script> </body> </html><file_sep>-- phpMyAdmin SQL Dump -- version 4.8.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Aug 01, 2018 at 08:14 AM -- Server version: 10.1.31-MariaDB -- PHP Version: 5.6.35 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `aws-csi` -- -- -------------------------------------------------------- -- -- Table structure for table `access` -- CREATE TABLE `access` ( `accessID` int(11) NOT NULL, `accessRole` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `access` -- INSERT INTO `access` (`accessID`, `accessRole`) VALUES (1, 'Administrator'), (2, 'User (Elevated)'), (3, 'User'); -- -------------------------------------------------------- -- -- Table structure for table `accounts` -- CREATE TABLE `accounts` ( `accountID` int(11) NOT NULL, `accountUN` varchar(150) NOT NULL, `accountPW` varchar(300) NOT NULL, `accountAccess` tinyint(4) NOT NULL COMMENT '1-administrator; 2-elevated user; 3-user', `accountStatus` tinyint(5) NOT NULL COMMENT '1-active; 2-pending; 0-inactive', `userID` int(11) NOT NULL COMMENT 'Specifies who owns the account' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `accounts` -- INSERT INTO `accounts` (`accountID`, `accountUN`, `accountPW`, `accountAccess`, `accountStatus`, `userID`) VALUES (1, '<EMAIL>', '12345', 3, 1, 1), (2, '<EMAIL>', '$2y$10$FtCpvMlFiQyMvzEThycOoeZd0PBdXr/e8aErCupdF/rUoPwbAS5xi', 3, 2, 2), (3, '<EMAIL>', <PASSWORD>$10$unzGJA.WK.NPcxSB.CPYnOHPOxfJ6jQ0Jib4hIqclExW/DiJ1Setq', 3, 1, 3), (4, '<EMAIL>', '$2y$10$lmPiSB5lTY6epDEG1kQM6OuD1a.z6oGk1x5Y/I7dxYGW6UlAskEO.', 3, 1, 4), (5, '<EMAIL>', <PASSWORD>$10$tM2fqOHQ/BemNqvTLzaleO2iX.w9x.U7ZhxZgAp4HghB0YjeLI9Oi', 3, 1, 5), (6, '$2y$10$VmrvYkcpawgGgrf0AQBklu6XtOiIpzGHhZeFhGUImyTWIm5MN3Z8m', '$2y$10$yMnaeWMlwpV0m3tmW/V30.S3VONujFqSS7XmN.q9393yBHOs6vhcy', 3, 1, 6), (7, '<EMAIL>', '$2y$10$ktJr/gALDk1iN/znj593duLJTTwXclq1uiuACe3/RdiE.ZQTCAjn6', 3, 1, 7), (8, '$2y$10$wnuF9xxVItfzndaGxZ3kBu2malbmzl2Y3iagJXzC/3ubxxNdMXEye', '$2y$10$4pArefxAmzAtTGN6oYwMUObSyb4Rfldqi9OSEFF1.fIxN7toyctYC', 3, 1, 8), (9, '$2y$10$yNUAN4AVUY0iC0oiUPErMOyCOveNuvjeyfClblEocoLbCnR7SdOsS', '$2y$10$hgP6dVBvE6ywFkGpGkE/k.YhbLNvaEenudub1/Ic1thbCt.5qWh/G', 1, 1, 9), (10, '$2y$10$cYp/UA5Uvp9inoJIW/tZo.wx0SDKKX5KP.T7zSBiOHmNm3/3qioye', '$2y$10$g9T2KD.VDok.Uw58KEWEL.TSIaWj0jFu6c4uZoj8AxJmvcSv6ceha', 3, 0, 10), (11, '$2y$10$oB0Csioz9dxhSqtDvCpIP.4nLUXCYVbNrasg8V1svATLKJTGViXbm', '$2y$10$jrQ5WHRS4kLjoyX5kaGiQObiGfG7u96OAGSSBslC7YDgx6fWs8BD6', 3, 1, 11), (12, '$2y$10$gQ6b4uwBYm.Y84SQLWAtdeJEeHJDhSQKnIhzvpZxSVdJuhZy5LIPm', '$2y$10$VT04BvlZ6I282c1yxctPM.30OTGi/a9qPdhOX/oKIto2Z/XQyxIPC', 3, 1, 12), (13, '$2y$10$.GStvL2.Cg94NxLJOyJ3He3Kg7kLLKlvUqqG/jXxq20adlCV/xxB6', '$2y$10$Jr.wfHuZtDbgJvpfTaoVkO3MAQrbDfDaQg04S.3EcrOE7UCfXhG8S', 3, 1, 13), (14, '$2y$10$cLqhYkJTlnR1eOKzh355A.6.sF4pNUKZyeLRTW1SBaz07PkQN/R0a', '$2y$10$R8Z6O6RoKlJqRWZFHt1m7elA3giTuhpyI6It1onpo.wnQmyQBvLKa', 3, 1, 14), (15, '$2y$10$gU8b2u3HT1WuQHxC3hf61uyUJBePIBKT1SVpPM.Lzr0scsCmNCjka', '$2y$10$68Rsk8tcV1qperAtf6sv1.OwOkM6sMca1WKmS3yFKTDHFPfbqKpgC', 3, 1, 15), (16, '$2y$10$p0boFG74U8mFL64wys0m1.KK/INTPpEWwe4220gYc90Bc/ojApN.S', '$2y$10$IqxrYax1GDY1OpOieZmDy..QaYXHtkfUBglLJ8d0VwF815P0p.auC', 3, 1, 16), (17, '$2y$10$1tAMLxyr/MPpJUFmQZC9yOqt6Ip0b3kdlglUbYpUUpYI6sc8ct2lq', '$2y$10$xL/BZNMilYNu9dRfPW2lleSY8TkwLGjspo3ZKMMpmA7N6OUNmwEq.', 3, 1, 17), (18, '$2y$10$jYcPM<PASSWORD>', <PASSWORD>', 3, 1, 18), (19, '$<PASSWORD>', <PASSWORD>', 3, 1, 19); -- -------------------------------------------------------- -- -- Table structure for table `costsavings` -- CREATE TABLE `costsavings` ( `csID` int(11) NOT NULL, `csCause` varchar(1000) NOT NULL COMMENT 'Description for the root cause of the problem', `csSteps` varchar(1000) NOT NULL COMMENT 'Description for the steps taken in resolving the problem', `csDate` date NOT NULL, `csSavings` decimal(10,2) NOT NULL COMMENT 'The final total cost of the savings from the initial and final input (computed automatically)', `csInitial` decimal(10,2) NOT NULL COMMENT 'The initial cost input', `csFinal` decimal(10,2) NOT NULL COMMENT 'The final cost input after the steps taken ', `teamID` int(11) NOT NULL COMMENT 'FK that connects data from journeyteams', `techID` int(11) NOT NULL COMMENT 'FK that connects data from technologies', `envID` int(11) NOT NULL COMMENT 'FK that connects data from environments', `typeID` int(11) NOT NULL COMMENT 'FK that connects data from savingtypes', `projectID` int(11) DEFAULT NULL COMMENT 'FK that connects data from projects', `userID` int(11) NOT NULL COMMENT 'FK that connects the users table; determines ownership of the record' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `costsavings` -- INSERT INTO `costsavings` (`csID`, `csCause`, `csSteps`, `csDate`, `csSavings`, `csInitial`, `csFinal`, `teamID`, `techID`, `envID`, `typeID`, `projectID`, `userID`) VALUES (1, 'lorem', 'ipsum', '2018-07-03', '20.00', '120.00', '100.00', 5, 2, 3, 3, 0, 9), (2, 'test input 2', 'test input 2', '2018-07-03', '50.00', '250.00', '200.00', 5, 2, 1, 3, 0, 9), (3, 'test ', 'test', '2018-07-03', '80.00', '200.00', '120.00', 2, 1, 2, 2, 0, 9), (4, 'hello', 'world', '2018-06-29', '150.00', '1200.00', '1050.00', 4, 2, 1, 2, 0, 9), (5, 'test', 'test', '2018-06-26', '20.00', '100.00', '80.00', 4, 1, 2, 4, 0, 9), (192, 'lorem ipsum', 'lorem ipsum', '2018-01-01', '80.00', '200.00', '120.00', 1, 1, 1, 1, 0, 5), (193, 'lorem ipsum', 'lorem ipsum', '2018-01-04', '100.00', '200.00', '100.00', 4, 2, 2, 2, 0, 2), (194, 'lorem ipsum', 'lorem ipsum', '2018-01-07', '120.00', '200.00', '80.00', 4, 2, 1, 3, 0, 3), (195, 'lorem ipsum', 'lorem ipsum', '2018-01-08', '70.00', '200.00', '130.00', 1, 2, 1, 2, 0, 1), (196, 'lorem ipsum', 'lorem ipsum', '2018-01-12', '50.00', '170.00', '120.00', 3, 1, 2, 2, 0, 1), (197, 'lorem ipsum', 'lorem ipsum', '2018-01-13', '50.00', '200.00', '150.00', 2, 1, 3, 1, 0, 4), (198, 'lorem ipsum', 'lorem ipsum', '2018-01-13', '100.00', '220.00', '120.00', 2, 1, 1, 1, 0, 6), (199, 'lorem ipsum', 'lorem ipsum', '2018-01-14', '100.00', '300.00', '200.00', 2, 1, 1, 1, 0, 2), (200, 'lorem ipsum', 'lorem ipsum', '2018-01-16', '120.00', '200.00', '80.00', 4, 1, 2, 2, 0, 1), (201, 'lorem ipsum', 'lorem ipsum', '2018-01-18', '80.00', '200.00', '120.00', 3, 1, 2, 3, 0, 2), (202, 'lorem ipsum', 'lorem ipsum', '2018-01-20', '60.00', '200.00', '140.00', 1, 2, 3, 4, 0, 4), (203, 'lorem ipsum', 'lorem ipsum', '2018-01-21', '100.00', '300.00', '200.00', 4, 1, 3, 2, 0, 7), (204, 'lorem ipsum', 'lorem ipsum', '2018-01-21', '20.00', '100.00', '80.00', 1, 1, 1, 1, 0, 8), (205, 'lorem ipsum', 'lorem ipsum', '2018-01-21', '50.00', '100.00', '50.00', 5, 2, 2, 1, 0, 6), (206, 'lorem ipsum', 'lorem ipsum', '2018-01-22', '60.00', '200.00', '120.00', 1, 2, 1, 2, 0, 3), (207, 'lorem ipsum', 'lorem ipsum', '2018-01-26', '80.00', '200.00', '120.00', 3, 1, 1, 3, 0, 4), (208, 'lorem ipsum', 'lorem ipsum', '2018-01-27', '80.00', '200.00', '120.00', 2, 2, 1, 1, 0, 7), (209, 'lorem ipsum', 'lorem ipsum', '2018-01-27', '120.00', '400.00', '280.00', 4, 2, 2, 1, 0, 2), (210, 'lorem ipsum', 'lorem ipsum', '2018-02-03', '80.00', '200.00', '120.00', 1, 2, 2, 1, 0, 7), (211, 'lorem ipsum', 'lorem ipsum', '2018-02-05', '100.00', '200.00', '100.00', 4, 2, 1, 2, 0, 1), (212, 'lorem ipsum', 'lorem ipsum', '2018-02-07', '120.00', '200.00', '80.00', 4, 2, 1, 3, 0, 1), (213, 'lorem ipsum', 'lorem ipsum', '2018-02-11', '70.00', '200.00', '130.00', 2, 2, 2, 2, 0, 3), (214, 'lorem ipsum', 'lorem ipsum', '2018-02-12', '80.00', '200.00', '120.00', 3, 2, 2, 2, 0, 4), (215, 'lorem ipsum', 'lorem ipsum', '2018-02-12', '80.00', '200.00', '120.00', 2, 1, 1, 1, 0, 8), (216, 'lorem ipsum', 'lorem ipsum', '2018-02-13', '100.00', '220.00', '120.00', 2, 2, 1, 1, 0, 2), (217, 'lorem ipsum', 'lorem ipsum', '2018-02-14', '120.00', '300.00', '180.00', 2, 1, 3, 1, 0, 2), (218, 'lorem ipsum', 'lorem ipsum', '2018-02-16', '120.00', '200.00', '80.00', 4, 1, 2, 2, 0, 1), (219, 'lorem ipsum', 'lorem ipsum', '2018-02-18', '80.00', '200.00', '120.00', 3, 1, 2, 3, 0, 2), (220, 'lorem ipsum', 'lorem ipsum', '2018-02-19', '60.00', '200.00', '140.00', 2, 2, 3, 4, 0, 9), (221, 'lorem ipsum', 'lorem ipsum', '2018-02-22', '100.00', '300.00', '200.00', 4, 1, 2, 2, 0, 6), (222, 'lorem ipsum', 'lorem ipsum', '2018-02-22', '120.00', '200.00', '80.00', 2, 2, 3, 1, 0, 4), (223, 'lorem ipsum', 'lorem ipsum', '2018-02-23', '50.00', '100.00', '50.00', 5, 2, 2, 2, 0, 9), (224, 'lorem ipsum', 'lorem ipsum', '2018-02-24', '60.00', '200.00', '140.00', 2, 1, 1, 2, 0, 4), (225, 'lorem ipsum', 'lorem ipsum', '2018-02-25', '100.00', '210.00', '110.00', 3, 1, 1, 3, 0, 2), (226, 'lorem ipsum', 'lorem ipsum', '2018-02-26', '210.00', '160.00', '50.00', 2, 2, 1, 1, 0, 1), (227, 'lorem ipsum', 'lorem ipsum', '2018-02-26', '120.00', '400.00', '280.00', 4, 1, 1, 2, 0, 2), (228, 'lorem ipsum', 'lorem ipsum', '2018-03-02', '80.00', '200.00', '120.00', 2, 1, 2, 1, 0, 4), (229, 'lorem ipsum', 'lorem ipsum', '2018-03-03', '100.00', '200.00', '100.00', 4, 1, 1, 2, 0, 2), (230, 'lorem ipsum', 'lorem ipsum', '2018-03-03', '120.00', '200.00', '80.00', 4, 2, 2, 3, 0, 1), (231, 'lorem ipsum', 'lorem ipsum', '2018-03-04', '70.00', '200.00', '130.00', 2, 2, 1, 1, 0, 1), (232, 'lorem ipsum', 'lorem ipsum', '2018-03-05', '50.00', '200.00', '150.00', 3, 2, 2, 3, 0, 2), (233, 'lorem ipsum', 'lorem ipsum', '2018-03-07', '100.00', '200.00', '100.00', 2, 1, 2, 1, 0, 3), (234, 'lorem ipsum', 'lorem ipsum', '2018-03-11', '100.00', '220.00', '120.00', 2, 2, 2, 1, 0, 3), (235, 'lorem ipsum', 'lorem ipsum', '2018-03-12', '120.00', '300.00', '180.00', 2, 2, 3, 1, 0, 4), (236, 'lorem ipsum', 'lorem ipsum', '2018-03-13', '120.00', '200.00', '80.00', 4, 2, 2, 2, 0, 5), (237, 'lorem ipsum', 'lorem ipsum', '2018-03-16', '80.00', '200.00', '120.00', 2, 1, 2, 3, 0, 6), (238, 'lorem ipsum', 'lorem ipsum', '2018-03-17', '60.00', '200.00', '140.00', 1, 2, 3, 4, 0, 1), (239, 'lorem ipsum', 'lorem ipsum', '2018-03-18', '110.00', '300.00', '190.00', 4, 2, 2, 2, 0, 2), (240, 'lorem ipsum', 'lorem ipsum', '2018-03-20', '20.00', '200.00', '180.00', 2, 1, 3, 1, 0, 3), (241, 'lorem ipsum', 'lorem ipsum', '2018-03-21', '150.00', '200.00', '50.00', 5, 2, 2, 2, 0, 2), (242, 'lorem ipsum', 'lorem ipsum', '2018-03-21', '160.00', '200.00', '40.00', 2, 1, 1, 2, 0, 5), (243, 'lorem ipsum', 'lorem ipsum', '2018-03-22', '100.00', '210.00', '110.00', 1, 2, 2, 3, 0, 1), (244, 'lorem ipsum', 'lorem ipsum', '2018-03-24', '210.00', '160.00', '50.00', 2, 1, 1, 1, 0, 2), (245, 'lorem ipsum', 'lorem ipsum', '2018-03-25', '120.00', '200.00', '80.00', 4, 2, 1, 2, 0, 3), (246, 'lorem ipsum', 'lorem ipsum', '2018-03-26', '120.00', '400.00', '280.00', 2, 2, 1, 2, 0, 3), (247, 'lorem ipsum', 'lorem ipsum', '2018-03-27', '20.00', '100.00', '80.00', 4, 1, 1, 2, 0, 5), (248, 'lorem ipsum', 'lorem ipsum', '2018-04-15', '150.00', '300.00', '150.00', 1, 2, 2, 3, 0, 2), (249, 'lorem ipsum', 'lorem ipsum', '2018-04-17', '100.00', '200.00', '100.00', 1, 1, 2, 1, 0, 2), (250, 'lorem ipsum', 'lorem ipsum', '2018-04-21', '100.00', '220.00', '120.00', 2, 2, 2, 1, 0, 1), (251, 'lorem ipsum', 'lorem ipsum', '2018-04-22', '120.00', '300.00', '180.00', 2, 1, 2, 1, 0, 2), (252, 'lorem ipsum', 'lorem ipsum', '2018-04-23', '120.00', '200.00', '80.00', 4, 1, 2, 2, 0, 1), (253, 'lorem ipsum', 'lorem ipsum', '2018-04-26', '80.00', '200.00', '120.00', 2, 1, 2, 3, 0, 1), (254, 'lorem ipsum', 'lorem ipsum', '2018-04-27', '60.00', '200.00', '140.00', 1, 2, 3, 4, 0, 3), (255, 'lorem ipsum', 'lorem ipsum', '2018-04-28', '110.00', '300.00', '190.00', 4, 1, 1, 2, 0, 4), (256, 'lorem ipsum', 'lorem ipsum', '2018-04-28', '20.00', '200.00', '180.00', 2, 1, 1, 1, 0, 1), (257, 'lorem ipsum', 'lorem ipsum', '2018-05-01', '80.00', '200.00', '120.00', 1, 2, 2, 1, 0, 2), (258, 'lorem ipsum', 'lorem ipsum', '2018-05-02', '100.00', '200.00', '100.00', 4, 2, 1, 2, 0, 3), (259, 'lorem ipsum', 'lorem ipsum', '2018-05-05', '80.00', '200.00', '120.00', 4, 2, 1, 3, 0, 2), (260, 'lorem ipsum', 'lorem ipsum', '2018-05-06', '70.00', '200.00', '130.00', 2, 2, 2, 2, 0, 4), (261, 'lorem ipsum', 'lorem ipsum', '2018-05-07', '80.00', '200.00', '120.00', 3, 2, 2, 2, 0, 1), (262, 'lorem ipsum', 'lorem ipsum', '2018-05-08', '80.00', '200.00', '120.00', 2, 1, 3, 1, 0, 7), (263, 'lorem ipsum', 'lorem ipsum', '2018-05-11', '120.00', '220.00', '100.00', 2, 2, 1, 1, 0, 6), (264, 'lorem ipsum', 'lorem ipsum', '2018-05-11', '120.00', '300.00', '180.00', 2, 1, 3, 1, 0, 2), (265, 'lorem ipsum', 'lorem ipsum', '2018-05-16', '20.00', '200.00', '180.00', 4, 1, 2, 2, 0, 2), (266, 'lorem ipsum', 'lorem ipsum', '2018-05-17', '80.00', '200.00', '120.00', 3, 1, 2, 3, 4, 3), (267, 'lorem ipsum', 'lorem ipsum', '2018-05-18', '160.00', '200.00', '40.00', 2, 2, 3, 4, 0, 1), (268, 'lorem ipsum', 'lorem ipsum', '2018-05-19', '100.00', '200.00', '100.00', 4, 1, 2, 2, 0, 1), (269, 'lorem ipsum', 'lorem ipsum', '2018-05-22', '120.00', '200.00', '80.00', 2, 2, 3, 1, 0, 2), (270, 'lorem ipsum', 'lorem ipsum', '2018-05-22', '50.00', '100.00', '50.00', 5, 2, 2, 2, 0, 3), (271, 'lorem ipsum', 'lorem ipsum', '2018-05-23', '60.00', '200.00', '140.00', 2, 1, 1, 2, 0, 5), (272, 'lorem ipsum', 'lorem ipsum', '2018-05-24', '80.00', '100.00', '80.00', 3, 2, 1, 3, 4, 3), (273, 'lorem ipsum', 'lorem ipsum', '2018-05-27', '40.00', '160.00', '120.00', 2, 2, 1, 1, 0, 1), (274, 'lorem ipsum', 'lorem ipsum', '2018-05-27', '120.00', '400.00', '280.00', 4, 1, 1, 2, 0, 2), (275, 'lorem ipsum', 'lorem ipsum', '2018-06-05', '20.00', '200.00', '180.00', 2, 1, 2, 2, 0, 2), (276, 'lorem ipsum', 'lorem ipsum', '2018-06-08', '80.00', '200.00', '120.00', 3, 2, 2, 3, 1, 3), (277, 'lorem ipsum', 'lorem ipsum', '2018-06-08', '60.00', '100.00', '40.00', 2, 2, 2, 4, 0, 1), (278, 'lorem ipsum', 'lorem ipsum', '2018-06-13', '100.00', '200.00', '100.00', 2, 1, 2, 2, 0, 2), (279, 'lorem ipsum', 'lorem ipsum', '2018-06-14', '120.00', '200.00', '80.00', 2, 2, 3, 1, 0, 3), (280, 'lorem ipsum', 'lorem ipsum', '2018-06-14', '50.00', '100.00', '50.00', 1, 2, 2, 2, 0, 5), (281, 'lorem ipsum', 'lorem ipsum', '2018-06-16', '60.00', '200.00', '140.00', 2, 1, 1, 2, 0, 2), (282, 'lorem ipsum', 'lorem ipsum', '2018-06-21', '100.00', '200.00', '100.00', 3, 2, 1, 3, 4, 3), (283, 'lorem ipsum', 'lorem ipsum', '2018-06-25', '40.00', '260.00', '220.00', 2, 2, 1, 1, 0, 3), (284, 'lorem ipsum', 'lorem ipsum', '2018-06-26', '20.00', '100.00', '80.00', 4, 2, 1, 1, 0, 1), (285, 'lorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque viverra augue eu lobortis mattis. Cras vel mi faucibus, gravida est a, facilisis sem.', '2018-07-05', '20.00', '100.00', '80.00', 3, 1, 1, 3, 4, 9), (286, 'test edit of data', 'test edit of data', '2018-07-08', '70.00', '250.00', '180.00', 4, 1, 1, 4, 0, 9), (287, 'test add of data', 'test add of ', '2018-07-09', '60.00', '230.00', '170.00', 5, 2, 1, 3, 0, 9), (288, 'test input 2', 'test input 2', '2018-07-09', '20.00', '120.00', '100.00', 5, 2, 1, 1, 0, 9), (289, 'sample input with default values', 'sample input with default values', '2018-07-16', '130.00', '650.00', '520.00', 5, 2, 2, 4, 3, 9), (290, 'test input 2 with default values', 'test input 2 with default values', '2018-07-16', '50.00', '440.00', '390.00', 3, 2, 1, 4, 1, 9), (291, 'sample input from the index page', 'sample input from the index page', '2018-07-16', '40.00', '190.00', '150.00', 3, 1, 3, 3, 1, 14), (292, 'test input with 0 value final cost', 'test input with 0 value final cost', '2018-07-18', '120.00', '120.00', '0.00', 6, 2, 1, 2, 2, 9), (293, 'wwwwwwwwwwwwww', 'wwwwwwwwwwwwwww', '2018-07-30', '40.00', '200.00', '160.00', 3, 2, 1, 3, 4, 9), (294, 'qqqqqqqqq', 'qqqqwwwwwq', '2018-07-30', '35.00', '200.00', '165.00', 5, 2, 3, 1, 3, 9), (295, 'test input for project dropdown 2', 'test input for dropdown 2', '2018-07-30', '70.00', '250.00', '180.00', 6, 1, 3, 4, 1, 9), (296, 'test input - project with logs', 'test input - project with logs', '2018-07-30', '90.00', '300.00', '210.00', 1, 2, 1, 4, 5, 9), (297, 'test input - projects with logs', 'test input - projects with logs', '2018-07-30', '90.00', '300.00', '210.00', 1, 2, 1, 4, 5, 9), (298, 'pppppppppppppp', 'pppppppppppppp', '2018-07-30', '80.00', '100.00', '20.00', 3, 2, 1, 3, 3, 9), (299, 'test for proj input with logs', 'test for proj input with logs', '2018-07-30', '90.00', '300.00', '210.00', 1, 2, 1, 4, 3, 9), (300, 'test add for view page', 'test add for view page', '2018-07-30', '130.00', '800.00', '670.00', 2, 2, 1, 3, 1, 9), (301, 'test input 2 for view', 'test input 2 for view', '2018-07-30', '60.00', '200.00', '140.00', 6, 1, 2, 4, 5, 9), (302, 'test input 3 for view', 'test input 3 for view', '2018-07-30', '30.00', '200.00', '170.00', 4, 2, 1, 3, 4, 9), (303, '1234567890', '1234567890', '2018-08-01', '50.00', '500.00', '450.00', 1, 2, 2, 2, 6, 9), (304, 'qwwwwe', 'qqqqqqqqwwwwe', '2018-08-01', '50.00', '150.00', '100.00', 4, 2, 1, 3, 4, 14); -- -------------------------------------------------------- -- -- Table structure for table `environments` -- CREATE TABLE `environments` ( `envID` int(11) NOT NULL, `envName` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `environments` -- INSERT INTO `environments` (`envID`, `envName`) VALUES (1, 'Development'), (2, 'QA'), (3, 'Production'); -- -------------------------------------------------------- -- -- Table structure for table `journeyteams` -- CREATE TABLE `journeyteams` ( `teamID` int(11) NOT NULL, `teamName` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `journeyteams` -- INSERT INTO `journeyteams` (`teamID`, `teamName`) VALUES (1, 'CEP'), (2, 'DHC'), (3, 'Memories'), (4, 'Testing'), (5, 'My Team'), (6, 'New Team'); -- -------------------------------------------------------- -- -- Table structure for table `logs` -- CREATE TABLE `logs` ( `logID` int(11) NOT NULL, `logDate` datetime NOT NULL, `logUser` varchar(100) NOT NULL, `logEvent` varchar(300) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `logs` -- INSERT INTO `logs` (`logID`, `logDate`, `logUser`, `logEvent`) VALUES (1, '2018-07-09 09:41:16', '<NAME>', 'Logged in into the system.'), (2, '2018-07-09 09:43:40', '<NAME>', 'Logged out of the system.'), (3, '2018-07-09 09:43:54', '<NAME>', 'Logged in into the system.'), (4, '2018-07-09 10:10:40', '<NAME>', 'Updated the information of record #2'), (5, '2018-07-09 11:05:15', '<NAME>', 'Updated record #2 of environments from \'QA\' to \'Quality Assurance\''), (6, '2018-07-09 11:08:47', '<NAME>', 'Updated record #2 of environments from \'Quality Assurance\' to \'QA\''), (7, '2018-07-09 11:09:24', '<NAME>', 'Updated record #4 of journey teams from \'Testing\' to \'Testing 1\''), (8, '2018-07-09 11:09:42', '<NAME>', 'Updated record #4 of journey teams from \'Testing 1\' to \'Testing\''), (9, '2018-07-09 11:10:18', '<NAME>', 'Added a new journey team: New Team'), (10, '2018-07-09 11:14:54', '<NAME>', 'Updated record #4 of savings types from \'Optimization\' to \'Optimizations\''), (11, '2018-07-09 11:15:09', '<NAME>', 'Updated record #4 of savings types from \'Optimizations\' to \'Optimization\''), (12, '2018-07-09 11:19:21', '<NAME>', 'Added a new cost savings entry dated: 2018-07-08, with a total savings of $55'), (13, '2018-07-09 11:37:20', '<NAME>', 'Added a new cost savings entry dated 2018-07-09, with a total savings of $60'), (14, '2018-07-09 11:39:52', '<NAME>', 'Updated the information of record #286'), (15, '2018-07-09 11:56:43', '<NAME>', 'Updated the information of cost savings record #285'), (16, '2018-07-09 12:00:51', '<NAME>', 'Added a new cost savings entry dated 2018-07-09, with a total savings of $20'), (17, '2018-07-10 08:05:38', '<NAME>', 'Logged in into the system'), (18, '2018-07-10 08:35:12', '<NAME>', 'Updated the information of cost savings record #287'), (19, '2018-07-10 15:25:50', '<NAME>', 'Logged in into the system'), (20, '2018-07-11 06:50:18', '<NAME>', 'Logged in into the system'), (21, '2018-07-11 07:06:00', '<NAME>', 'Logged out of the system'), (22, '2018-07-11 07:09:11', '<NAME>', 'Logged in into the system'), (23, '2018-07-11 07:09:20', '<NAME>', 'Logged out of the system'), (24, '2018-07-11 07:09:20', ' ', 'Logged out of the system'), (25, '2018-07-11 07:09:28', '<NAME>', 'Logged in into the system'), (26, '2018-07-11 08:57:29', 'Asht<NAME>', 'Logged in into the system'), (27, '2018-07-11 13:53:35', 'Ashton Foreman', 'Logged out of the system'), (28, '2018-07-11 13:53:35', ' ', 'Logged out of the system'), (29, '2018-07-11 13:53:54', 'Ashton Foreman', 'Logged in into the system'), (30, '2018-07-11 13:54:13', 'Ashton Foreman', 'Logged out of the system'), (31, '2018-07-11 13:54:24', 'Ashton Foreman', 'Logged in into the system'), (32, '2018-07-11 13:54:30', 'Ashton Foreman', 'Logged out of the system'), (33, '2018-07-16 11:33:49', 'Ashton Foreman', 'Logged in into the system'), (34, '2018-07-16 15:08:16', '<NAME>', 'Updated their account information.'), (35, '2018-07-16 15:10:25', '<NAME>', 'Added a new cost savings entry dated 2018-07-16, with a total savings of $130'), (36, '2018-07-16 15:10:45', '<NAME>', 'Updated their account information.'), (37, '2018-07-16 15:11:36', '<NAME>', 'Added a new cost savings entry dated 2018-07-16, with a total savings of $50'), (38, '2018-07-16 15:21:09', 'Ashton Foreman', 'Added a new cost savings entry dated 2018-07-16, with a total savings of $40'), (39, '2018-07-16 15:22:25', 'As<NAME>', 'Updated their account information.'), (40, '2018-07-18 14:25:47', '<NAME>', 'Added a new cost savings entry dated 2018-07-18, with a total savings of $120'), (41, '2018-07-23 18:11:34', '<NAME>', 'Logged in into the system'), (42, '2018-07-25 07:58:30', 'Ashton Foreman', 'Logged in into the system'), (43, '2018-07-25 13:42:06', 'Ashton Foreman', 'Logged in into the system'), (44, '2018-07-25 14:59:05', '<NAME>', 'Changed the access level of Ashton Foreman from 3 to 2'), (45, '2018-07-26 09:37:56', '<NAME>', 'Archived Antonio Akyatpanaog\'s account (account ID #3)'), (46, '2018-07-26 09:59:02', '<NAME>', 'Archived Darrell Brady\'s account (account ID #16)'), (47, '2018-07-26 10:28:13', '<NAME>', ''), (48, '2018-07-26 10:32:39', '<NAME>', 'Archived Darrell Brady\'s account (account ID #16)'), (49, '2018-07-26 10:47:42', 'Ashton Foreman', 'Logged in into the system'), (50, '2018-07-26 11:01:22', '<NAME>', 'Logged out of the system'), (51, '2018-07-26 11:01:30', '<NAME>', 'Logged in into the system'), (52, '2018-07-26 11:09:58', '<NAME>', 'Changed the access level of Ashton Foreman from 2 to 3'), (53, '2018-07-26 11:14:19', 'Ashton Foreman', 'Logged out of the system'), (54, '2018-07-26 11:19:44', '<NAME>', 'Logged out of the system'), (55, '2018-07-26 11:19:51', '<NAME>', 'Logged in into the system'), (56, '2018-07-26 11:22:12', '<NAME>', 'Logged out of the system'), (57, '2018-07-26 11:22:18', '<NAME>', 'Logged in into the system'), (58, '2018-07-26 11:22:35', '<NAME>', ''), (59, '2018-07-26 11:22:44', '<NAME>', 'Logged out of the system'), (60, '2018-07-26 11:23:05', '<NAME>', 'Logged in into the system'), (61, '2018-07-26 11:24:40', '<NAME>', 'Archived Antonio Akyatpanaog\'s account (account ID #10)'), (62, '2018-07-26 11:24:53', '<NAME>', ''), (63, '2018-07-27 14:06:18', '<NAME>', 'Logged in into the system'), (64, '2018-07-30 09:55:50', '<NAME>', 'Added a new cost savings entry dated 2018-07-30, with a total savings of $40'), (65, '2018-07-30 13:31:39', '<NAME>', 'Added a new cost savings entry dated 2018-07-30, with a total savings of $35'), (66, '2018-07-30 13:35:04', '<NAME>', 'Updated their account information.'), (67, '2018-07-30 13:50:08', '<NAME>', 'Added a new cost savings entry dated 2018-07-30, with a total savings of $70'), (68, '2018-07-30 14:13:36', '<NAME>', 'Added a new cost savings entry for the project , with a total savings of $90'), (69, '2018-07-30 14:14:38', '<NAME>', 'Added a new cost savings entry for the project , with a total savings of $90'), (70, '2018-07-30 14:15:21', '<NAME>', 'Added a new cost savings entry for the project , with a total savings of $80'), (71, '2018-07-30 14:16:22', '<NAME>', 'Added a new cost savings entry for the project Project 3, with a total savings of $90'), (72, '2018-07-30 14:27:29', '<NAME>', 'Added a new cost savings entry for the project Project 1, with a total savings of $130'), (73, '2018-07-30 14:28:33', '<NAME>', 'Added a new cost savings entry for the project Project 5, with a total savings of $60'), (74, '2018-07-30 14:29:12', '<NAME>', 'Added a new cost savings entry for the project Project 4, with a total savings of $30'), (75, '2018-07-30 14:50:42', '<NAME>', 'Added a new project: Project ABC'), (76, '2018-07-30 14:52:07', '<NAME>', 'Added a new project: Project ABC'), (77, '2018-07-31 11:07:33', '<NAME>', 'Updated record #3 of projects from \'Project 3\' to \'Project 3 Test\''), (78, '2018-08-01 13:56:44', '<NAME>', 'Added a new project: Project 6'), (79, '2018-08-01 14:04:32', '<NAME>', 'Added a new cost savings entry for the project Project ABC, with a total savings of $50'), (80, '2018-08-01 14:05:40', '<NAME>', 'Logged out of the system'), (81, '2018-08-01 14:05:49', '<NAME>', 'Logged in into the system'), (82, '2018-08-01 14:06:29', '<NAME>', 'Added a new cost savings entry for the project Project 4, with a total savings of $50'), (83, '2018-08-01 14:06:48', '<NAME>', 'Logged out of the system'), (84, '2018-08-01 14:06:56', '<NAME>', 'Logged in into the system'), (85, '2018-08-01 14:08:32', '<NAME>', 'Updated record #1 of projects from \'Project 1\' to \'Project 1\''); -- -------------------------------------------------------- -- -- Table structure for table `projects` -- CREATE TABLE `projects` ( `projectID` int(11) NOT NULL, `projectName` varchar(100) NOT NULL, `projectDescription` varchar(300) NOT NULL, `projectStatus` tinyint(4) NOT NULL COMMENT '1-active; 2-something..; etc.' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `projects` -- INSERT INTO `projects` (`projectID`, `projectName`, `projectDescription`, `projectStatus`) VALUES (1, 'Project 1', 'Hello World 123', 1), (2, 'Project 2', 'hesoyam', 1), (3, 'Project 3 Test', 'Test update for project information', 1), (4, 'Project 4', '12345', 1), (5, 'Project 5', '54321', 1), (6, 'Project ABC', 'This is a test input using the add form', 1), (7, 'Project 6', 'Testing for the project status default on adding a new record', 1); -- -------------------------------------------------------- -- -- Table structure for table `savingtypes` -- CREATE TABLE `savingtypes` ( `typeID` int(11) NOT NULL, `typeName` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `savingtypes` -- INSERT INTO `savingtypes` (`typeID`, `typeName`) VALUES (1, 'Cleanup'), (2, 'Right Sizing'), (3, 'Reconfiguration'), (4, 'Optimization'); -- -------------------------------------------------------- -- -- Table structure for table `technologies` -- CREATE TABLE `technologies` ( `techID` int(11) NOT NULL, `techName` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `technologies` -- INSERT INTO `technologies` (`techID`, `techName`) VALUES (1, 'ELB'), (2, 'AWS'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `userID` int(11) NOT NULL, `userFN` varchar(100) NOT NULL, `userLN` varchar(100) NOT NULL, `envID` int(11) DEFAULT NULL, `teamID` int(11) DEFAULT NULL, `techID` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`userID`, `userFN`, `userLN`, `envID`, `teamID`, `techID`) VALUES (1, 'Mark', 'Castillo', NULL, NULL, NULL), (2, 'Mark', 'Castillo', NULL, NULL, NULL), (3, 'Antonio', 'Akyatpanaog', NULL, NULL, NULL), (4, '<NAME>', 'Castillo', NULL, NULL, NULL), (5, 'Screenshot', 'API', NULL, NULL, NULL), (6, 'Jane', 'Doe', NULL, NULL, NULL), (7, 'John', 'Doe', NULL, NULL, NULL), (8, 'Lorem', 'Ipsum', NULL, NULL, NULL), (9, 'Mark', 'Castillo', 1, 0, 2), (10, 'Antonio', 'Akyatpanaog', NULL, NULL, NULL), (11, 'Cameron', 'Leblanc', NULL, NULL, NULL), (12, 'Rebecca', 'Winters', NULL, NULL, NULL), (13, 'Maliha', 'Crowther', NULL, NULL, NULL), (14, 'Ashton', 'Foreman', 1, 4, 2), (15, 'Tahlia', 'Jeffery', NULL, NULL, NULL), (16, 'Darrell', 'Brady', NULL, NULL, NULL), (17, 'Devan', 'Moses', NULL, NULL, NULL), (18, 'Nela', 'Hopper', NULL, NULL, NULL), (19, 'Henry', 'Moose', NULL, NULL, NULL); -- -- Indexes for dumped tables -- -- -- Indexes for table `access` -- ALTER TABLE `access` ADD PRIMARY KEY (`accessID`); -- -- Indexes for table `accounts` -- ALTER TABLE `accounts` ADD PRIMARY KEY (`accountID`); -- -- Indexes for table `costsavings` -- ALTER TABLE `costsavings` ADD PRIMARY KEY (`csID`), ADD KEY `envID` (`envID`), ADD KEY `teamID` (`teamID`), ADD KEY `costsavings_ibfk_3` (`techID`), ADD KEY `costsavings_ibfk_4` (`typeID`), ADD KEY `costsavings_ibfk_5` (`userID`); -- -- Indexes for table `environments` -- ALTER TABLE `environments` ADD PRIMARY KEY (`envID`); -- -- Indexes for table `journeyteams` -- ALTER TABLE `journeyteams` ADD PRIMARY KEY (`teamID`); -- -- Indexes for table `logs` -- ALTER TABLE `logs` ADD PRIMARY KEY (`logID`); -- -- Indexes for table `projects` -- ALTER TABLE `projects` ADD PRIMARY KEY (`projectID`); -- -- Indexes for table `savingtypes` -- ALTER TABLE `savingtypes` ADD PRIMARY KEY (`typeID`); -- -- Indexes for table `technologies` -- ALTER TABLE `technologies` ADD PRIMARY KEY (`techID`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`userID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `access` -- ALTER TABLE `access` MODIFY `accessID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `accounts` -- ALTER TABLE `accounts` MODIFY `accountID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20; -- -- AUTO_INCREMENT for table `costsavings` -- ALTER TABLE `costsavings` MODIFY `csID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=305; -- -- AUTO_INCREMENT for table `environments` -- ALTER TABLE `environments` MODIFY `envID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `journeyteams` -- ALTER TABLE `journeyteams` MODIFY `teamID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `logs` -- ALTER TABLE `logs` MODIFY `logID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=86; -- -- AUTO_INCREMENT for table `projects` -- ALTER TABLE `projects` MODIFY `projectID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `savingtypes` -- ALTER TABLE `savingtypes` MODIFY `typeID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `technologies` -- ALTER TABLE `technologies` MODIFY `techID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `userID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20; -- -- Constraints for dumped tables -- -- -- Constraints for table `costsavings` -- ALTER TABLE `costsavings` ADD CONSTRAINT `costsavings_ibfk_1` FOREIGN KEY (`envID`) REFERENCES `environments` (`envID`) ON UPDATE NO ACTION, ADD CONSTRAINT `costsavings_ibfk_2` FOREIGN KEY (`teamID`) REFERENCES `journeyteams` (`teamID`) ON UPDATE NO ACTION, ADD CONSTRAINT `costsavings_ibfk_3` FOREIGN KEY (`techID`) REFERENCES `technologies` (`techID`) ON UPDATE NO ACTION, ADD CONSTRAINT `costsavings_ibfk_4` FOREIGN KEY (`typeID`) REFERENCES `savingtypes` (`typeID`) ON UPDATE NO ACTION, ADD CONSTRAINT `costsavings_ibfk_5` FOREIGN KEY (`userID`) REFERENCES `users` (`userID`) ON UPDATE NO ACTION; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php include('controllers/dashboard_controller.php'); ?> <div class="row" id="formDiv"> <div class="col-lg-12"> <h4 class="display-4"><?php echo $headerDisplay; ?></h4> <div class="card-deck"> <div class="card mb-3"> <div class="card-body text-center"> <div class="row"> <div class="col-lg-12"> <p>Cost Savings Total <br><small class="text-muted"><?php echo '(for ' . $cstotalDate . ')'; ?></small></p> <h3 class="card-title"> <i class="fa fa-fw fa-dollar-sign fa-sm"></i> <?php echo $sumSavings; ?> </h3> </div> </div> <br /> <div class="row"> <div class="col-lg-12"> <h5><?php echo getDiff($sumLast, $sumSavings); ?>% <?php echo getArrowIcon($sumLast, $sumSavings); ?></h5> <small class="text-muted">vs $ <?php echo $sumLast; ?> (prev.)</small> </div> </div> </div> </div> <div class="card mb-3"> <div class="card-body text-center"> <p>Largest Weekly Entry</p> <p class="card-text"> <h3> <i class="fa fa-fw fa-dollar-sign fa-sm"></i> <?php echo $lar_csSavings; ?> </h3> </p> <small class="text-muted"> Action performed by: <br><?php echo $lar_csActor; ?> <br><?php echo $lar_csDate; ?> </small> </div> </div> <div class="card mb-3" id="formButtons"> <div class="card-body"> <form method="POST" class="form-horizontal"> <label for="filterTeam"><small class="text-muted">Filter by Team</small></label> <div class="form-row"> <div class="col-lg-8"> <select class="form-control" name="filterTeam" id="filterTeam"> <option value="" <?php if(!isset($_GET['filter'])) {echo "selected='true'";} else { echo ""; } ?>>Show All</option> <?php echo $list_teams; ?> </select> </div> <div class="col-lg-4 text-center"> <button type="submit" class="btn btn-primary" name="btnFilter" id="btnFilter">Apply</button> </div> </div> </form> <hr /> <div class="text-center"> <div class="addthis_inline_share_toolbox"></div> <a href="<?php if(isset($_GET['filter'])) { echo $_SERVER['REQUEST_URI'] . '&viewonly=1'; } else { echo $_SERVER['REQUEST_URI'] . '?viewonly=1'; }; ?>" class="btn btn-outline-dark text-center" target="_blank"><i class="fa fa-fw fa-camera"></i> Take a Screenshot</a> </div> </div> </div> </div> </div> <div class="col-lg-12"> <div class="card mb-3"> <div class="card-header"> Total Savings per Month </div> <div class="card-body"> <canvas id="barChart" height="90"></canvas> </div> <div class="card-footer text-muted"> <small>For the year <?php echo date('Y'); ?></small> </div> </div> </div> <div class="col-lg-12"> <div class="card-deck"> <div class="card mb-3"> <div class="card-body"> <h5><?php echo $pieDisplay; ?></h5><br> <canvas id="pieTeam" width="100%"></canvas> </div> </div> <div class="card mb-3"> <div class="card-body"> <h5>Breakdown by Environment</h5><br> <canvas id="pieEnv" width="100%"></canvas> </div> </div> </div> </div> <div class="col-lg-12"> <div class="card-deck"> <div class="card mb-3"> <div class="card-body"> <h5>Breakdown by Technology</h5><br> <canvas id="pieTech" width="100%"></canvas> </div> </div> <div class="card mb-3"> <div class="card-body"> <h5>Breakdown by Savings Type</h5><br> <canvas id="pieType" width="100%"></canvas> </div> </div> </div> </div> <div class="col-lg-12"> <div class="card mb-3"> <div class="card-header"> <h5>Latest Initiatives <?php echo $tableDisplay; ?></h5> </div> <div class="card-body"> <div class="table table-responsive table-hover"> <table class="table-bordered" id="recentsTable" width="100%" cellspacing="0"> <thead> <tr> <th class="text-center">Date</th> <th class="text-center">Team</th> <th class="text-center">Technology</th> <th class="text-center">Environment</th> <th class="text-center">Type</th> <th class="text-center">Savings</th> </tr> </thead> <tbody> <?php echo $list_latest; ?> </tbody> </table> </div> </div> </div> </div> </div> <script type="text/javascript"> // JS for the bar chart var ctxL = document.getElementById("barChart").getContext('2d'); var myBarChart = new Chart(ctxL, { type: 'bar', data: { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], datasets: [ { label: "Savings Total ($)", backgroundColor: "rgba(52, 152, 219,0.8)", borderColor: "rgba(52, 152, 219,0.8)", pointBackgroundColor: "rgba(52, 152, 219,0)", data: <?php echo $data_bar; ?> } ] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] }, <?php echo $animation; ?> responsive: true } }); // JS for the pie chart (per team data) var ctxP = document.getElementById("pieTeam").getContext('2d'); var mypieTeam = new Chart(ctxP, { type: 'doughnut', data: { labels: <?php echo $teams_list; ?> datasets: [ { data: <?php echo $tsavings_list; ?> backgroundColor: ["#3498db", "#2ecc71", "#9b59b6", "#e67e22", "#1abc9c", "#e74c3c", "#f39c12", "#8e44ad", "#2c3e50", "#2980b9", "#7f8c8d", "#27ae60", "#34495e", "#c0392b", "#d35400"], hoverBackgroundColor: [] } ] }, options: { legend: { position: 'right' }, <?php echo $animation; ?> responsive: true } }); // JS for the pie chart (per environment data) var ctxP = document.getElementById("pieEnv").getContext('2d'); var myPieEnv = new Chart(ctxP, { type: 'doughnut', data: { labels: <?php echo $env_list; ?> datasets: [ { data: <?php echo $esavings_list; ?> backgroundColor: ["#3498db", "#2ecc71", "#9b59b6", "#e67e22", "#1abc9c", "#e74c3c", "#f39c12", "#8e44ad", "#2c3e50", "#2980b9", "#7f8c8d", "#27ae60", "#34495e", "#c0392b", "#d35400"], hoverBackgroundColor: [] } ] }, options: { legend: { position: 'right' }, <?php echo $animation; ?> responsive: true } }); // JS for the pie chart (per technology data) var ctxP = document.getElementById("pieTech").getContext('2d'); var myPieTech = new Chart(ctxP, { type: 'doughnut', data: { labels: <?php echo $tech_list; ?> datasets: [ { data: <?php echo $hsavings_list; ?> backgroundColor: ["#3498db", "#2ecc71", "#9b59b6", "#e67e22", "#1abc9c", "#e74c3c", "#f39c12", "#8e44ad", "#2c3e50", "#2980b9", "#7f8c8d", "#27ae60", "#34495e", "#c0392b", "#d35400"], hoverBackgroundColor: [] } ] }, options: { legend: { position: 'right' }, <?php echo $animation; ?> responsive: true } }); // JS for the pie chart (per cost savings type) var ctxP = document.getElementById("pieType").getContext('2d'); var myPieType = new Chart(ctxP, { type: 'doughnut', data: { labels: <?php echo $type_list; ?> datasets: [ { data: <?php echo $ysavings_list; ?> backgroundColor: ["#3498db", "#2ecc71", "#9b59b6", "#e67e22", "#1abc9c", "#e74c3c", "#f39c12", "#8e44ad", "#2c3e50", "#2980b9", "#7f8c8d", "#27ae60", "#34495e", "#c0392b", "#d35400"], hoverBackgroundColor: [] } ] }, options: { legend: { position: 'right' }, <?php echo $animation; ?> responsive: true } }); </script> <script type="text/javascript"> // JS for the data table (10 most recent entries) $(document).ready(function() { $('#recentsTable').DataTable( { "order": [[ 0, "desc" ]], "paging": false, "bFilter": false } ); } ); </script> <script type="text/javascript"> // popover for initiative summary -- currently unused $(document).ready(function(){ $('[data-toggle="popover"]').popover(); }); </script> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php include('controllers/login_controller.php'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Login</title> <!-- jQuery --> <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script> <script type="text/javascript" src="js/jquery.easing.min.js"></script> <!-- Bootstrap --> <link rel="stylesheet" type="text/css" href="lib/bootstrap/css/bootstrap.min.css"> <script type="text/javascript" src="lib/bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="lib/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Font Awesome --> <link rel="stylesheet" type="text/css" href="lib/fontawesome/fontawesome-all.min.css"> <!-- sb-admin template --> <link href="css/sb-admin.css" rel="stylesheet"> </head> <body class="bg-dark"> <div class="container"> <div class="card card-login mx-auto mt-5"> <div class="card-header">Login</div> <div class="card-body"> <?php echo $msgDisplay; ?> <form class="form-horizontal" method="POST"> <div class="form-group"> <label for="inpEmail">Email address</label> <input class="form-control" id="inpEmail" name="inpEmail" type="email" placeholder="Enter email" required="true"> </div> <div class="form-group"> <label for="inpPassword">Password</label> <input class="form-control" id="inpPassword" name="inpPassword" type="password" placeholder="<PASSWORD>" required="true"> </div> <button class="btn btn-primary btn-block" id="btnLogin" name="btnLogin">Login</button> <div class="text-center"> <a href="register.php" class="d-block small mt-3">Register an Account</a> <a href="forgot_password.php" class="d-block small">Forgot Password?</a> </div> </form> </div> </div> </div> </body> </html><file_sep><?php $pageTitle = "Search Results"; include_once 'controllers/includes/header.php'; # Initialize/set the default value for the page header $displayHeader = ""; # Check if a post value was passed if(empty($_POST)) { header('location: error.php'); } else { # Get the search keyword that was entered $searchKey = htmlspecialchars($_POST['inpSearch']); # The initial SQL statement for querying the data $stmt_search = "SELECT s.csID, s.csCause, s.csSteps, s.csDate, s.csSavings, s.csInitial, s.csFinal, m.teamName, h.techName, e.envName, y.typeName, u.userFN, u.userLN FROM costsavings s INNER JOIN journeyteams m ON s.teamID = m.teamID INNER JOIN technologies h ON s.techID = h.techID INNER JOIN environments e ON s.envID = e.envID INNER JOIN savingtypes y ON s.typeID = y.typeID INNER JOIN users u ON s.userID = u.userID "; $stmt_order = " ORDER BY s.csDate DESC"; # Check if the input is empty if(empty(trim($searchKey))) { # Header to display if no search key is specified $displayHeader = "Displaying All Records"; # If the key is blank/empty, display all the records $sql_search = $stmt_search . $stmt_order; $result_search = $con->query($sql_search) or die(mysqli_error($sql_search)); } else { # Header to display if there is a search key specified $displayHeader = 'Displaying results with "' . $searchKey . '"'; #else, filter columns with the key as parameter on the LIKE operator $sql_search = $con->prepare($stmt_search . "WHERE csCause LIKE CONCAT ('%', ?, '%') OR csSteps LIKE CONCAT ('%', ?, '%') OR u.userFN LIKE CONCAT ('%', ?, '%') OR u.userLN LIKE CONCAT ('%', ?, '%') OR csDate LIKE CONCAT ('%', ?, '%') OR csSavings LIKE CONCAT ('%', ?, '%') OR csInitial LIKE CONCAT ('%', ?, '%') OR csFinal LIKE CONCAT ('%', ?, '%') OR m.teamName LIKE CONCAT ('%', ?, '%') OR h.techName LIKE CONCAT ('%', ?, '%') OR e.envName LIKE CONCAT ('%', ?, '%') OR y.typeName LIKE CONCAT ('%', ?, '%') " . $stmt_order); $sql_search->bind_param("ssssssssssss", $searchKey, $searchKey, $searchKey, $searchKey, $searchKey, $searchKey, $searchKey, $searchKey, $searchKey, $searchKey, $searchKey, $searchKey); $sql_search->execute(); $result_search = $sql_search->get_result(); } # Get the results and display in a table $search_table = ""; while($row = mysqli_fetch_array($result_search)) { $csID = htmlspecialchars($row['csID']); $csCause = htmlspecialchars($row['csCause']); $csSteps = htmlspecialchars($row['csSteps']); $userName = htmlspecialchars($row['userFN']) . ' ' . htmlspecialchars($row['userLN']); $csDate = htmlspecialchars($row['csDate']); $displayDate = date('m/d/Y', strtotime($csDate)); $csSavings = htmlspecialchars($row['csSavings']); $csInitial = htmlspecialchars($row['csInitial']); $csFinal = htmlspecialchars($row['csFinal']); $teamName = htmlspecialchars($row['teamName']); $techName = htmlspecialchars($row['techName']); $envName = htmlspecialchars($row['envName']); $typeName = htmlspecialchars($row['typeName']); $search_table .= " <tr class='clickable-row' data-href='details.php?rid=$csID' style='cursor: pointer;'> <td>$displayDate</td> <td>$teamName</td> <td>$techName</td> <td>$envName</td> <td>$typeName</td> <td>$userName</td> <td> <span class='float-left'>$</span> <span class='float-right'>$csInitial</span> </td> <td>$csSteps</td> <td> <span class='float-left'>$</span> <span class='float-right'>$csFinal</span> </td> <td> <span class='float-left'>$</span> <span class='float-right'>$csSavings</span> </td> </tr>"; } } ?><file_sep><?php include 'controllers/manage_controller.php'; ?> <div class="row"> <div class="col-lg-12"> <div class="card mb-3"> <div class="card-header"> <h5>Manage Access</h5> </div> <div class="card-body"> <div class="table table-responsive table-hover"> <table id="usersTable" width="100%" cellspacing="0"> <thead> <tr> <th class="text-center">User Name</th> <th class="text-center">Access Level</th> <th class="text-center">Account Status</th> <th></th> </tr> </thead> <tbody> <?php echo $list_users; ?> </tbody> <tfoot> <tr> <th></th> <th></th> <th></th> <th></th> </tr> </tfoot> </table> </div> </div> </div> </div> </div> <script type="text/javascript"> $(document).ready(function() { $('#usersTable').DataTable( { "order": [[ 0, "asc" ]], pageResize: true, scrollY: '50vh', scrollX: '100%', scrollCollapse: true, paging: false, columnDefs: [{orderable: false, targets: [3]}], initComplete: function () { this.api().columns([1,2]).every( function () { var column = this; var title = $(this).text(); var select = $('<select class="form-control"><option value="">Show All</option></select>') .appendTo( $(column.footer()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option value="'+d+'">'+d+'</option>' ) } ); } ); } } ); } ); $(document).ready(function () { $('.dataTables_filter input[type="search"]'). attr('placeholder','Enter a keyword...'). css({'width':'300px','display':'inline-block'}); }); </script> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php include 'controllers/details_controller.php'; ?> <script type="text/javascript" src="js/html2canvas.min.js"></script> <div class="row" id="formDiv"> <div class="col-lg-12"> <?php echo $msgDisplay; ?> <h4 class="display-4">Details</h4> <form class="form-horizontal" method="POST"> <div class="row"> <div class="col-lg-6""> <div class="col-lg-12"> <div class="form-group row"> <label for="displayTeam" class="col-lg-4 col-form-label">Team</label> <div class="col-lg-8"> <input type="text" readonly class="form-control" id="displayTeam" name="displayTeam" value="<?php echo $teamName; ?>"> </div> </div> <div class="form-group row"> <label for="displayEnv" class="col-lg-4 col-form-label">Environment</label> <div class="col-lg-8"> <input type="text" readonly class="form-control" id="displayEnv" name="displayEnv" value="<?php echo $envName; ?>"> </div> </div> <div class="form-group row"> <label for="displayTech" class="col-lg-4 col-form-label">AWS/DevOps Technology</label> <div class="col-lg-8"> <input type="text" readonly class="form-control" id="displayTech" name="displayTech" value="<?php echo $techName; ?>"> </div> </div> <div class="form-group row"> <label for="displayType" class="col-lg-4 col-form-label">Cost Savings Type</label> <div class="col-lg-8"> <input type="text" readonly class="form-control" id="displayType" name="displayType" value="<?php echo $typeName; ?>"> </div> </div> </div> </div> <div class="col-lg-6""> <div class="col-lg-12"> <div class="form-group row"> <label for="displayDate" class="col-lg-4 col-form-label">Completion Date</label> <div class="col-lg-8"> <input type="text" readonly class="form-control" id="displayDate" name="displayDate" value="<?php echo $displayDate; ?>"> </div> </div> </div> <div class="col-lg-12"> <div class="form-group row"> <label for="displayActor" class="col-lg-4 col-form-label">Executed By</label> <div class="col-lg-8"> <input type="text" readonly class="form-control" id="displayActor" name="displayActor" value="<?php echo $userName; ?>"> </div> </div> </div> </div> </div> <hr /> <div class="row"> <div class="col-lg-6"> <div class="col-lg-12"> <div class="form-group"> <label for="displayCause" class="col-form-label">Root Cause/Problem to Solve</label> <div> <textarea <?php echo $readonly; ?> class="form-control" rows="10" id="inpCause" name="inpCause" style="resize: none;" required="true"><?php echo $csCause; ?></textarea> </div> </div> </div> <div class="col-lg-12"> <div class="form-group row"> <label for="displayInitial" class="col-lg-4 col-form-label">Initial Cost</label> <div class="col-lg-8"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input type="text" <?php echo $readonly; ?> class="form-control" id="inpInitial" name="inpInitial" value="<?php echo $csInitial; ?>" required="true"> </div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="col-lg-12"> <div class="form-group"> <label for="displaySteps" class="col-form-label">Solution/s Implemented</label> <div> <textarea <?php echo $readonly; ?> class="form-control" rows="10" id="inpSteps" name="inpSteps" style="resize: none;" required="true"><?php echo $csSteps; ?></textarea> </div> </div> </div> <div class="col-lg-12"> <div class="form-group row"> <label for="displayFinal" class="col-lg-4 col-form-label">Final Cost</label> <div class="col-lg-8"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input type="text" <?php echo $readonly; ?> class="form-control" id="inpFinal" name="inpFinal" value="<?php echo $csFinal; ?>" required="true"> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-6 offset-lg-6"> <div class="col-lg-12"> <div class="form-group row"> <label for="displaySavings" class="col-lg-4 col-form-label">Total Savings</label> <div class="col-lg-8"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input type="text" readonly class="form-control" id="displaySavings" name="displaySavings" value="<?php echo $csSavings; ?>"> </div> </div> </div> </div> </div> </div> <div class="row" id="formButtons"> <div class="col-lg-6"> <div class="form-group"> <a href="view.php" class="btn btn-secondary" name="btnBack"><i class="fa fa-fw fa-angle-left"></i>Back to List</a> </div> </div> <div class="col-lg-6"> <div class="col-lg-12" <?php echo $showButton; ?>> <div class="row"> <div class="col-lg-12"> <button class="btn btn-primary float-right" id="btnUpdate" name="btnUpdate">Save Changes</button> </div> </div> </div> <br <?php echo $showButton; ?>> <div class="col-lg-12"> <div class="row"> <!--<label for="buttonGroup" class="col-lg-4 col-form-label">Share</label>--> <div class="col-lg-7"> <div class="addthis_inline_share_toolbox"></div> </div> <div class="col-lg-5"> <a href="<?php echo $_SERVER['REQUEST_URI'] . '&viewonly=1'; ?>" class="btn btn-outline-dark float-right" target="_blank"><i class="fa fa-fw fa-camera fa-lg"></i> Take a Screenshot</a> </div> </div> </div> </div> </div> </form> </div> </div> <script type="text/javascript"> // Input masking for the money input $(function() { $('#inpInitial').maskMoney({allowZero: true}); }); $(function() { $('#inpFinal').maskMoney({allowZero: true}); }) </script> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php $pageTitle = "Update Record"; include 'includes/header.php'; # Validate the record being requested: # If the record id doesnt exist, show an error if(isset($_GET['rid'])) { $requestedID = $_GET['rid']; # Query: check that the ID exists $sql_validate = "SELECT csID FROM costsavings WHERE csID = $requestedID"; $result_validate = $con->query($sql_validate) or die(mysqli_error($con)); if(mysqli_num_rows($result_validate) == 0) { # Requested ID does not exist; redirect to the error page header('location: error.php'); } else { # Query: get the values for the fields with the requested ID $sql_values = "SELECT csID, csCause, csSteps, csActor, csDate, csSavings, csInitial, csFinal, teamID, techID, envID, typeID FROM costsavings WHERE csID = $requestedID"; $result_values = $con->query($sql_values) or die(mysqli_error($con)); while($row = mysqli_fetch_array($result_values)) { $csCause = $row['csCause']; $csSteps = $row['csSteps']; $csActor = $row['csActor']; $csDate = $row['csDate']; $csSavings = $row['csSavings']; $csInitial = $row['csInitial']; $csFinal = $row['csFinal']; $selTeam = $row['teamID']; $selTech = $row['techID']; $selEnv = $row['envID']; $selType = $row['typeID']; } # Change the display format for the date $displayDate = new DateTime(date('Y-m-d', strtotime($csDate))); # SQL query for the journey teams dropdown list $sql_teams = "SELECT teamID, teamName FROM journeyteams"; $result_teams = $con->query($sql_teams) or die(mysqli_error($con)); $list_teams = ""; while($rowt = mysqli_fetch_array($result_teams)) { $teamID = htmlspecialchars($rowt['teamID']); $teamName = htmlspecialchars($rowt['teamName']); $selectedTeam = $teamID == $selTeam ? "selected" : ""; $list_teams .= "<option value='$teamID' $selectedTeam>$teamName</option>"; } # SQL query for the devops technology dropdown list $sql_tech = "SELECT techID, techName FROM technologies"; $result_tech = $con->query($sql_tech) or die(mysqli_error($con)); $list_tech = ""; while($rowh = mysqli_fetch_array($result_tech)) { $techID = htmlspecialchars($rowh['techID']); $techName = htmlspecialchars($rowh['techName']); $selectedTech = $techID == $selTech ? "selected" : ""; $list_tech .= "<option value='$techID' $selectedTech>$techName</option>"; } # SQL query for the environments dropdown list $sql_env = "SELECT envID, envName FROM environments"; $result_env = $con->query($sql_env) or die(mysqli_error($con)); $list_env = ""; while($rowv = mysqli_fetch_array($result_env)) { $envID = htmlspecialchars($rowv['envID']); $envName = htmlspecialchars($rowv['envName']); $selectedEnv = $envID == $selEnv ? "selected" : ""; $list_env .= "<option value='$envID' $selectedEnv>$envName</option>"; } # SQL query for the cost savings type dropdown list $sql_type = "SELECT typeID, typeName FROM savingtypes"; $result_type = $con->query($sql_type) or die(mysqli_error($con)); $list_type = ""; while($rowy = mysqli_fetch_array($result_type)) { $typeID = htmlspecialchars($rowy['typeID']); $typeName = htmlspecialchars($rowy['typeName']); $selectedType = $typeID == $selType ? "selected" : ""; $list_type .= "<option value='$typeID' $selectedType>$typeName</option>"; } } } else { # The record being requested (via url) does not exist header('location: error.php'); } ?><file_sep><?php include_once str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/controllers/function.php'); include_once str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/controllers/config.php'); session_start(); if(isset($_SESSION['accID'])) { $msgDisplay = ""; # Change the format of the datetime input and set default to the date today $dateToday = new DateTime(date("Y-m-d")); # Bind the session ID to a variable $accID = $_SESSION['accID']; #Get the user ID using the session ID $userID = getUserID($con, $accID); # Get the default values for the dropdowns $sql_default = $con->prepare("SELECT envID, teamID, techID FROM users WHERE userID = ?"); $sql_default->bind_param("i", $userID); $sql_default->execute(); $result_default = $sql_default->get_result(); while ($row = mysqli_fetch_array($result_default)) { # Get the values... $def_envID = $row['envID']; $def_teamID = $row['teamID']; $def_techID = $row['techID']; } if(isset($_POST['btnAdd'])) { # Retrieve the input data from the form $inpTeam = mysqli_real_escape_string($con, $_POST['inpTeam']); $inpEnv = mysqli_real_escape_string($con, $_POST['inpEnv']); $inpTech = mysqli_real_escape_string($con, $_POST['inpTech']); $inpType = mysqli_real_escape_string($con, $_POST['inpType']); $inpProj = mysqli_real_escape_string($con, $_POST['inpProj']); # Rremove the commas from the money input $inpInitial = str_replace(",", "", mysqli_real_escape_string($con, $_POST['inpInitial'])); $inpFinal = str_replace(",", "", mysqli_real_escape_string($con, $_POST['inpFinal'])); $totSavings = $inpInitial - $inpFinal; $inpCause = mysqli_real_escape_string($con, $_POST['inpCause']); $inpSteps = mysqli_real_escape_string($con, $_POST['inpSteps']); #$inpName = mysqli_real_escape_string($con, $_POST['inpName']); -- will be automatically added via session ID $inpDate = mysqli_real_escape_string($con, $_POST['inpDate']); addRecord($con, $inpTeam, $inpEnv, $inpTech, $inpType, $inpInitial, $inpFinal, $totSavings, $inpCause, $inpSteps, $inpDate, $inpProj, $userID); $projName = getProjectName($con, $inpProj); $txtEvent = "Added a new cost savings entry for the project " . $projName . ", with a total savings of $" . $totSavings; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("Successfully added a new record!"); header('Refresh: 1'); } } else { header('location: login.php'); } ?><file_sep><?php $pageTitle = "Error"; include 'controllers/includes/header.php'; ?> <div class="vertical-center-offset"> <div class="container"> <h1 class="display-4 text-center">Something went wrong...</h1> <p class="lead text-center">The page you requested was not found or is unavailable.</p> </div> </div> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php $msgDisplay = ""; function test() { echo 'hello'; } # Used by the view.php and index.php's modal for adding a new record function addRecord($con, $inpTeam, $inpEnv, $inpTech, $inpType, $inpInitial, $inpFinal, $totSavings, $inpCause, $inpSteps, $inpDate, $inpProj, $userID) { $stmt_insert = $con->prepare("INSERT INTO costsavings (csCause, csSteps, csDate, csSavings, csInitial, csFinal, teamID, techID, envID, typeID, projectID, userID) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $stmt_insert->bind_param("sssdddiiiiii", $inpCause, $inpSteps, $inpDate, $totSavings, $inpInitial, $inpFinal, $inpTeam, $inpTech, $inpEnv, $inpType, $inpProj, $userID); $stmt_insert->execute() or die(mysqli_error($con)); $msgDisplay = successAlert("Successfully inserted a new record."); return $msgDisplay; } # Gets the access value from the database to determine the availability of administrator functions for the user function allowAccess($con, $accID) { $sql_access = $con->prepare("SELECT accountAccess FROM accounts WHERE accountID = ?"); $sql_access->bind_param("i", $accID); $sql_access->execute(); $result_access = $sql_access->get_result(); while($row = mysqli_fetch_array($result_access)) { $accountAccess = $row['accountAccess']; } return $accountAccess; } # Determines whether the page can be accessed by the user # Used in the Manage Data pages (add/edit teams, tech, savings types, environments) function accessPage($con, $accID) { $accountAccess = allowAccess($con, $accID); if($accountAccess == 1 || $accountAccess == 2) { } else { header('location: error.php'); } #return $accessPage; } # Used to compare password inputs for verification # Currently used in the access management page (user.php) function confirmPassword($con, $accID, $inpPassword) { # Get the password stored in the database $sql_pass = $con->prepare("SELECT accountPW FROM accounts WHERE accountID = ?"); $sql_pass->bind_param("i", $accID); $sql_pass->execute(); $result_pass = $sql_pass->get_result(); while($row = mysqli_fetch_array($result_pass)) { $accountPW = $row['accountPW']; } # Verify that the input and stored values are the same # password_verify(input, hash); returns bool return password_verify($inpPassword, $accountPW); } # Used to display an error alert box function errorAlert($msgText) { $msgError = "<div class='alert alert-danger alert-dismissible fade show'> <button type='button' class='close' data-dismiss='alert'>&times;</button> " . $msgText . " </div>"; return $msgError; } # Checks the input data by removing slashes and white spaces function inpcheck($inputData) { $inputData = removeslashes($inputData); $inputData = stripslashes($inputData); $inputData = trim($inputData); $inputData = htmlspecialchars($inputData); return $inputData; } # Gets the percent difference between savings values (used in the dashboard) function getDiff($sumLast, $sumSavings) { #formula to get the % difference for the current week vs. previous week $percDiff = ($sumLast == 0) ? '--' : number_format((float)(($sumSavings-$sumLast) / $sumLast)*100, 2, '.', ''); return $percDiff; } # Determines the arrow icon to display based on the increase or decrease of savings (previous vs current) function getArrowIcon($sumLast, $sumSavings) { $percDiff = getDiff($sumLast, $sumSavings); if($percDiff < 0) { $arrowIcon = "<span class='fa fa-fw fa-arrow-circle-down' style='color: red'></span>"; } else if($percDiff > 0) { $arrowIcon = "<span class='fa fa-fw fa-arrow-circle-up' style='color: green'></span>"; } else { $arrowIcon = "<span class='fa fa-fw fa-minus-circle' style='color: grey'></span>"; } return $arrowIcon; } function getProjectName($con, $inpProj) { # Get the project name for the audit text $sql_projName = $con->prepare("SELECT projectName FROM projects WHERE projectID = ?"); $sql_projName->bind_param("i", $inpProj); $sql_projName->execute(); $result_projName = $sql_projName->get_result(); while($row = mysqli_fetch_array($result_projName)) { $projName = $row['projectName']; } return $projName; } # function getUserID($con, $accID) { $sql_user = $con->prepare("SELECT userID FROM accounts WHERE accountID = ?"); $sql_user->bind_param("i", $accID); $sql_user->execute(); $result_user = $sql_user->get_result(); while($ru = mysqli_fetch_array($result_user)) { $userID = $ru['userID']; } return $userID; } # function getUserName($con, $accID) { $sql_name = $con->prepare("SELECT u.userFN, u.userLN FROM accounts a INNER JOIN users u ON a.userID = u.userID WHERE a.userID = ?"); $sql_name->bind_param("i", $accID); $sql_name->execute() or die(mysqli_error($con)); $result_name = $sql_name->get_result(); while($row = mysqli_fetch_array($result_name)) { $userFN = $row['userFN']; $userLN = $row['userLN']; } $userName = $userFN . ' ' . $userLN; return $userName; } # Get the list of access types and its default function listAccess($con, $def_access) { $sql_access = "SELECT accessID, accessRole FROM access"; $result_access = $con->query($sql_access) or die(mysqli_error($con)); $list_access = ""; while($row = mysqli_fetch_array($result_access)) { $accessID = $row['accessID']; $accessRole = htmlspecialchars($row['accessRole']); if($accessID == $def_access) { $selected = "selected='true'"; } else { $selected = ""; } $list_access .= "<option value='$accessID' $selected>$accessRole</option>"; } return $list_access; } # Gets the list of environments for the dropdown function listEnvironments($con, $def_envID) { # Default value for the environment dropdown $sql_env = "SELECT envID, envName FROM environments"; $result_env = $con->query($sql_env) or die(mysqli_error($con)); $list_env = ""; while($rowv = mysqli_fetch_array($result_env)) { $envID = htmlspecialchars($rowv['envID']); $envName = htmlspecialchars($rowv['envName']); if($envID == $def_envID) { $selected = "selected='true'"; } else { $selected = ""; } $list_env .= "<option value='$envID' $selected>$envName</option>"; } return $list_env; } function listProjects($con) { $sql_proj = "SELECT projectID, projectName FROM projects"; $result_proj = $con->query($sql_proj) or die(mysqli_error($con)); $list_proj = ""; while($row = mysqli_fetch_array($result_proj)) { $projectID = ($row['projectID']); $projectName = htmlspecialchars($row['projectName']); $list_proj .= "<option value='$projectID'>$projectName</option>"; } return $list_proj; } #Gets the list of status (roles) related to a user's account function listStatus($con, $def_status) { switch ($def_status) { case 0: $statusText = "Inactive/Archived"; break; case 1: $statusText = "Active"; break; case 2: $statusText = "Pending"; break; default: $statusText = "Undetermined"; break; } return $statusText; } # Gets the list of journey teams for the dropdown function listTeams($con, $def_teamID) { # Default value for the team dropdown $sql_teams = "SELECT teamID, teamName FROM journeyteams"; $result_teams = $con->query($sql_teams) or die(mysqli_error($con)); $list_teams = ""; while($rowt = mysqli_fetch_array($result_teams)) { $teamID = htmlspecialchars($rowt['teamID']); $teamName = htmlspecialchars($rowt['teamName']); if($teamID == $def_teamID) { $selected = "selected='true'"; } else { $selected = ""; } $list_teams .= "<option value='$teamID' $selected>$teamName</option>"; } return $list_teams; } # Gets the list of aws/devops technologies for the dropdown function listTech($con, $def_techID) { # Default value for the tech dropdown $sql_tech = "SELECT techID, techName FROM technologies"; $result_tech = $con->query($sql_tech) or die(mysqli_error($con)); $list_tech = ""; while($rowh = mysqli_fetch_array($result_tech)) { $techID = htmlspecialchars($rowh['techID']); $techName = htmlspecialchars($rowh['techName']); if($techID == $def_techID) { $selected = "selected='true'"; } else { $selected = ""; } $list_tech .= "<option value='$techID' $selected>$techName</option>"; } return $list_tech; } # Gets the list of savings types for the dropdown function listTypes($con) { $sql_type = "SELECT typeID, typeName FROM savingtypes"; $result_type = $con->query($sql_type) or die(mysqli_error($con)); $list_type = ""; while($rowy = mysqli_fetch_array($result_type)) { $typeID = htmlspecialchars($rowy['typeID']); $typeName = htmlspecialchars($rowy['typeName']); $list_type .= "<option value='$typeID'>$typeName</option>"; } return $list_type; } # Logs the event/action that was performed on a page as well as the actor of the event function logEvent($con, $accID, $txtEvent) { $userName = getUserName($con, $accID); $sql_log = $con->prepare("INSERT INTO logs (logDate, logUser, logEvent) VALUES (NOW(), ?, ?)"); $sql_log->bind_param("ss", $userName, $txtEvent); $sql_log->execute() or die(mysqli_error($con)); } # Removes slashes from input data function removeslashes($inpData) { $inpData = implode("", explode("\\", $inpData)); $inpData = implode("", explode("/", $inpData)); return $inpData; } /* taken from https://screenshotlayer.com/documentation note: only the free version is used. there is a limitation of 2 requests per minute and 100 requests per month ** currently unused ** */ function screenshotlayer($url, $args) { // set access key $access_key = "3e2fb89a508890b8ee36657091d275e7"; // set secret keyword (defined in account dashboard) $secret_keyword = "helloworld114"; // encode target URL $params['url'] = urlencode($url); $params += $args; // create the query string based on the options foreach($params as $key => $value) { $parts[] = "$key=$value"; } // compile query string $query = implode("&", $parts); // generate secret key from target URL and secret keyword $secret_key = md5($url . $secret_keyword); return "https://api.screenshotlayer.com/api/capture?access_key=$access_key&secret_key=$secret_key&$query"; } # Displays a success alert box function successAlert($msgText) { $msgSuccess = "<div class='alert alert-success alert-dismissible fade show'> <button type='button' class='close' data-dismiss='alert'>&times;</button> " . $msgText . " </div>"; return $msgSuccess; } # Displays a warning alert box function warningAlert($msgText) { $msgWarning = "<div class='alert alert-warning alert-dismissible fade show'> <button type='button' class='close' data-dismiss='alert'>&times;</button> " . $msgText . " </div>"; return $msgWarning; } ?><file_sep><?php include 'controllers/header_controller.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- For IE 9 and below. ICO should be 32x32 pixels in size --> <!--[if IE]><link rel="shortcut icon" href="images/icons/awslogo.png"><![endif]--> <!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> <link rel="apple-touch-icon-precomposed" href="images/icons/awslogo.png"> <!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. --> <link rel="icon" href="images/icons/awslogo.png"> <meta property="og:url" content="<?php echo $current_uri; ?>"> <meta property="og:type" content="website"> <!--<meta property="og:title" content="<?php #echo $metaTitle; ?>">--> <!--<meta property="og:description" content="<?php #echo $metaDescription; ?>">--> <!-- Replaced the title and description with static values for testing with the FB Sharing --> <meta property="og:title" content="AWS Cost Savings Knowledge Base"> <meta property="og:description" content="View analytical data from the cost savings entries."> <meta property="og:image" content="https://i.imgur.com/fgOWFZ4.png"> <meta name="description" content=""> <meta name="author" content=""> <title><?php echo $pageTitle; ?></title> <link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="lib/fontawesome/css/fontawesome-all.css" rel="stylesheet" type="text/css"> <link href="lib/datatables/dataTables.bootstrap4.css" rel="stylesheet"> <link href="css/sb-admin.css" rel="stylesheet"> <link href="lib/jasny-bootstrap/css/jasny-bootstrap.min.css" rel="stylesheet" type="text/css"> <style type="text/css"> .vertical-center { min-height: 100%; min-height: 100vh; display: flex; align-items: center; } .vertical-center-offset { min-height: 50%; min-height: 50vh; max-height: 50%; max-height: 50vh; display: flex; align-items: center; } /* Removes the caret after the dropdown */ .nav-link#userDropdown::after { display: none; } </style> </head> <body class="fixed-nav bg-dark" id="page-top"> <script> //Facebook SDK window.fbAsyncInit = function() { FB.init({ appId : '619686831726851', autoLogAppEvents : true, xfbml : true, version : 'v3.0' }); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <!-- Navigation bar --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav"> <a class="navbar-brand" href="">AWS Cost Savings Knowledge Base</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav navbar-sidenav" id="navAccordion"> <li class="nav-item" data-toggle="tooltip" data-placement="right" title="Home Page"> <a class="nav-link" href="index.php"> <i class="fas fa-fw fa-home"></i> <span class="nav-link-text text-center">Home</span> </a> </li> <li class="nav-item <?php echo $pageTitle === 'Dashboard' ? 'active' : ''; ?>" data-toggle="tooltip" data-placement="right" title="Dashboard"> <a class="nav-link" href="dashboard.php"> <i class="fas fa-fw fa-chart-pie"></i> <span class="nav-link-text text-center">Dashboard</span> </a> </li> <li class="nav-item <?php echo $pageTitle === 'Cost Savings Initiatives' ? 'active' : ''; ?>" data-toggle="tooltip" data-placement="right" title="Cost Savings"> <a class="nav-link" href="view.php"> <i class="fas fa-fw fa-piggy-bank"></i> <span class="nav-link-text">Cost Savings Initiatives</span> </a> </li> <li class="nav-item" data-toggle="tooltip" data-placement="right" title="Manage Data" <?php echo $accessLevel == 1 || $accessLevel == 2 ? '' : 'style="display: none;"'; ?>> <a class="nav-link nav-link-collapse collapsed" data-toggle="collapse" href="#collapseAddData" data-parent="#navAccordion"> <i class="fas fa-fw fa-folder-open"></i> <span class="nav-link-text">Manage Data</span> </a> <ul class="sidenav-second-level collapse" id="collapseAddData"> <li class="<?php echo $pageTitle === 'AWS/DevOps Technologies' ? 'active' : ''; ?>"><a href="add_tech.php">AWS/DevOps Technologies</a></li> <li class="<?php echo $pageTitle === 'Cost Savings Types' ? 'active' : ''; ?>"><a href="add_type.php">Cost Savings Types</a></li> <li class="<?php echo $pageTitle === 'Environments' ? 'active' : ''; ?>"><a href="add_env.php">Environments</a></li> <li class="<?php echo $pageTitle === 'Journey Teams' ? 'active' : ''; ?>"><a href="add_jt.php">Journey Teams</a></li> <li class="<?php echo $pageTitle === 'Projects' ? 'active' : ''; ?>"><a href="add_proj.php">Projects</a></li> </ul> </li> <li class="nav-item <?php echo $pageTitle === 'Manage Access' ? 'active' : ''; ?>" data-toggle="tooltip" data-placement="right" title="Manage Access" <?php echo $accessLevel == 1 ? '' : 'style="display: none;"'; ?>> <a class="nav-link" href="manage.php"> <i class="fas fa-fw fa-clipboard-list"></i> <span class="nav-link-text">Manage Access</span> </a> </li> <li class="nav-item <?php echo $pageTitle === 'Audit Logs' ? 'active' : ''; ?>" data-toggle="tooltip" data-placement="right" title="Audit Logs" <?php echo $accessLevel == 1 ? '' : 'style="display: none;"'; ?>> <a class="nav-link" href="logs.php"> <i class="fas fa-fw fa-book"></i> <span class="nav-link-text">Audit Logs</span> </a> </li> </ul> <ul class="navbar-nav sidenav-toggler"> <li class="nav-item"> <a class="nav-link text-center" id="sidenavToggler"> <i class="fa fa-fw fa-angle-left"></i> </a> </li> </ul> <ul class="navbar-nav ml-auto"> <!-- ** Screenshot button used to call screenshotlayer's API <form method="POST"> <li class="nav-item"> <a href="<?php #echo $imglink; ?>" class="nav-link btn btn-basic btn-block" target="_blank" title="Screenshot page"> <span><i class="fa fa-fw fa-camera fa-lg"></i></span> Save a Screenshot (X) </a> </li> </form>--> <!--<li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="" id="navbardrop" data-toggle="dropdown"> User </a> <div class="dropdown-menu"> <a class="dropdown-item" href="">Menu 1</a> <a class="dropdown-item" href="">Logout</a> </div> </li>--> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="" id="userDropdown" name="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-fw fa-user-circle fa-lg"></i> <?php echo $userFN . ' ' . $userLN; ?> <i class="fa fa-fw fa-angle-down"></i> </a> <div class="dropdown-menu menu-hover" aria-labelledby="userDropdown"> <a class="dropdown-item" href="account.php"><i class="fa fa-fw fa-user fa-sm"></i> My Account</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#logoutModal" data-toggle="modal" data-target="#logoutModal"><i class="fas fa-fw fa-sign-out-alt fa-sm"></i> Logout</a> </div> </li> <!--<li class="nav-item"> <a class="nav-link btn btn-basic btn-block" data-toggle="modal" data-target="#logoutModal" title="Logout"> <i class="fas fa-fw fa-sign-out-alt fa-lg"></i> Logout </a> </li>--> </ul> </div> </nav> <div class="content-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-12"> <!-- Bootstrap core JavaScript--> <script src="js/jquery-3.3.1.min.js"></script> <script src="lib/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="js/jquery.easing.min.js"></script> <!-- Chart.js JavaScript--> <script src="js/Chart.min.js"></script> <!-- Chart.js Datalabels plugin --> <script src="lib/chartjs-datalabels/chartjs-plugin-datalabels.js"></script> <!-- Data Tables js --> <script src="lib/datatables/jquery.dataTables.js"></script> <script src="lib/datatables/dataTables.bootstrap4.js"></script> <script src="lib/datatables/dataTables.pageResize.min.js"></script> <!-- sb-admin template js --> <script src="js/sb-admin.min.js"></script> <script src="js/sb-admin-datatables.min.js"></script> <script src="js/sb-admin-charts.min.js"></script> <!-- jasny boostrap --> <script src="lib/jasny-bootstrap/js/jasny-bootstrap.min.js"></script> <!-- input masking --> <script src="js/jquery.maskMoney.min.js"></script> <!-- AddThis Share Buttons js --> <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5b0220ddd0e5d139"></script> <!-- html2canvas js --> <script type="text/javascript" src="js/html2canvas.min.js"></script> <!-- custom scripts --> <script type="text/javascript"> // Clickable table rows jQuery(document).ready(function($) { $(".clickable-row").click(function() { window.location = $(this).data("href"); }); }); </script> <file_sep><?php include_once str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/controllers/function.php'); include_once str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/controllers/config.php'); ob_start(); session_start(); # Change the default timezone for the date/time functions date_default_timezone_set("Asia/Singapore"); # Parameters for the screenshotlayer API # Set optional parameters (leave blank if unused) $params['fullpage'] = '1'; $params['width'] = ''; $params['viewport'] = ''; $params['format'] = ''; $params['css_url'] = ''; $params['delay'] = ''; $params['ttl'] = ''; $params['force'] = '1'; $params['placeholder'] = ''; $params['user_agent'] = ''; $params['accept_lang'] = ''; $params['export'] = ''; $params['access'] = '<EMAIL>'; $params['pk'] = 'screenshotlayer'; # Get the current url of the page to pass into the og:image meta tag $current_uri = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; # Call Screenshotlayer's API (assigned to a function) $imglink = screenshotlayer($current_uri, $params); if(isset($_SESSION['accID'])) { # Bind the session ID to a variable $accID = $_SESSION['accID']; # SQL query for displaying the current user's name $sql_name = "SELECT userFN, userLN FROM users WHERE userID = $accID"; $result_name = $con->query($sql_name) or die(mysqli_error($con)); while($row = mysqli_fetch_array($result_name)) { $userFN = $row['userFN']; $userLN = $row['userLN']; } # Hide/show certain navbar buttons depending on the user's access level $accessLevel = allowAccess($con, $accID); } else if(isset($_GET['access'])) { # **Originally used for sceenshotlayer's API; currently unused # The session id is not set but login info can still be queried $ssaccess = $_GET['access']; $sql_su = "SELECT userID FROM accounts WHERE accountEmail = $ssaccess"; $result_su = $con->query($sql_su) or die(mysqli_error($con)); while($a_row = mysqli_fetch_array($result_su)) { $userID = $a_row['userID']; } $sql_ss = "SELECT userFN, userLN FROM users WHERE userID = $userID"; $result_ss = $con->query($sql_ss) or die(myslqli_error($con)); while($s_row = mysqli_fetch_array($result_ss)) { $userFN = $s_row['userFN']; $userLN = $s_row['userLN']; } } else { header('location: login.php'); } ?><file_sep><?php include_once 'function.php'; include_once 'config.php'; session_start(); # Get the current session ID $accID = $_SESSION['accID']; # Log the event $txtEvent = "Logged out of the system"; logEvent($con, $accID, $txtEvent); # Unset the session ID unset($_SESSION['accID']); header('location: ../login.php'); ?><file_sep>// For the data table filtering $(document).ready(function() { $('#savingsTable').DataTable( { "order": [[ 0, "desc" ]], pageResize: true, scrollY: '50vh', scrollX: '100%', scrollCollapse: true, paging: false, initComplete: function () { this.api().columns([1,2,3,4,5]).every( function () { var column = this; var title = $(this).text(); var select = $('<select class="form-control"><option value="">Show All</option></select>') .appendTo( $(column.footer()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option value="'+d+'">'+d+'</option>' ) } ); } ); } } ); } ); $(document).ready(function () { $('.dataTables_filter input[type="search"]'). attr('placeholder','Enter a keyword...'). css({'width':'300px','display':'inline-block'}); }); // Automatically display the total when the initial and final values are input function getTotal() { var initcost = document.getElementById('inpInitial').value; var finalcost = document.getElementById('inpFinal').value; initcost = initcost.replace(/\,/g,''); finalcost = finalcost.replace(/\,/g,''); var diffcost = initcost - finalcost; document.getElementById('sampledisp').value = diffcost.toFixed(2); } // Set the default value of the date input to today's date document.getElementById('inpDate').valueAsDate = new Date(); // Input masking for the money input $(function() { $('#inpInitial').maskMoney({allowZero: true}); }); $(function() { $('#inpFinal').maskMoney({allowZero: true}); })<file_sep><?php $pageTitle = "Projects"; include 'includes/header.php'; # Echoes a redirect line if the user does not have access to the page accessPage($con, $accID); # Query for displaying the records $sql_list = "SELECT projectID, projectName, projectDescription FROM projects"; $result_list = $con->query($sql_list) or die(mysqli_error($con)); $list_proj = ""; if(mysqli_num_rows($result_list) == 0) { #$list_env .= " # <tr> # <td class='text-center'>There are no records to display.</td> # </tr>"; } else { # Display the result in a table format while($row = mysqli_fetch_array($result_list)) { $projID = $row['projectID']; $projName = htmlspecialchars($row['projectName']); $projDescription = htmlspecialchars($row['projectDescription']); $list_proj .= " <tr> <td>$projName</td> <td>$projDescription</td> <td> <a href='edit_proj.php?id=$projID' class='btn btn-outline-link btn-sm float-right'> <span class='fa fa-edit fa-fw'></span> </a> </td> </tr>"; } } if(isset($_POST['btnAdd'])) { # Get the input from the form $inpName = inpcheck($_POST['inpName']); $inpDesc = htmlspecialchars($_POST['inpDesc']); # Validate that the input is not empty if(empty($inpName)) { $msgDisplay = errorAlert("Please make sure that your input is valid and try again."); } else { # convert the input value to uppercase for validation $tName = strtoupper($inpName); # Validate that the record being added doesnt already exist $sql_validate = "SELECT projectName FROM projects WHERE UPPER(projectName) = '$tName'"; $result_validate = $con->query($sql_validate) or die(mysqli_error($con)); if(mysqli_num_rows($result_validate) > 0) { $msgDisplay = errorAlert("The record you are trying to add already exists."); } else { # Insert the record with default status set to '1' for an 'Active' status $stmt_insert = $con->prepare("INSERT INTO projects (projectName, projectDescription, projectStatus) VALUES (?, ?, 1)"); $stmt_insert->bind_param("ss", $inpName, $inpDesc); $stmt_insert->execute(); $txtEvent = "Added a new project: " . $inpName; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("Successfully added a new record."); header('Refresh: 1'); } } } ?><file_sep><?php include 'controllers/edit_env_controller.php'; ?> <div class="row"> <div class="col-md-12"> <?php echo $msgDisplay; ?> <div class="card mb-3"> <div class="card-header"> Edit Environment Name </div> <form class="form-horizontal" method="POST"> <div class="card-body"> <div class="form-group"> <label for="inpName">Environment Name</label> <input class="form-control" type="text" name="inpName" id="inpName" maxlength="50" value="<?php echo $envName; ?>" required="true"> </div> </div> <div class="card-footer"> <button class="btn btn-primary float-right" id="btnSave" name="btnSave">Save Changes</button> <a href="add_env.php" class="btn btn-secondary"><i class="fa fa-angle-left fa-fw"></i> Back to List</a> </div> </form> </div> </div> </div> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php include 'controllers/add_env_controller.php'; ?> <div class="row"> <div class="col-md-12"> <?php echo $msgDisplay; ?> <div class="card mb-3"> <div class="card-header"> <h5>Environments <button class="btn btn-primary float-right" data-toggle="modal" data-target="#addEnvModal"> <span>Add an Environment</span> </button> </h5> </div> <div class="card-body"> <div class="table table-responsive table-hover"> <table class="table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Environment</th> </tr> </thead> <tbody> <?php echo $list_env; ?> </tbody> </table> </div> </div> </div> </div> </div> <!-- Modal for creating a new team --> <div class="modal fade" id="addEnvModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="addModalLabel">New Environment</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <form class="form-horizontal" method="POST"> <div class="modal-body"> <div class="form-group"> <label for="inpName">Environment Name</label> <input class="form-control" type="text" name="inpName" id="inpName" maxlength="50" required="true"> </div> </div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <button class="btn btn-primary" name="btnAdd" id="btnAdd">Add</button> </div> </form> </div> </div> </div> <?php include 'controllers/includes/footer.php'; ?><file_sep><?php $pageTitle = "Edit Team Name"; include_once 'includes/header.php'; # Echoes a redirect line if the user does not have access to the page accessPage($con, $accID); if(isset($_GET['id'])) { $requestID = $_GET['id']; # Validate that the requested input exists $sql_validate = "SELECT teamID FROM journeyteams WHERE teamID = $requestID"; $result_validate = $con->query($sql_validate) or die(mysqli_error($con)); if(mysqli_num_rows($result_validate) == 0) { # No records match header('location: error.php'); } else { # Display the current value $sql_display = "SELECT teamID, teamName FROM journeyteams WHERE teamID = $requestID"; $result_display = $con->query($sql_display) or die(mysqli_error($con)); while($rd = mysqli_fetch_array($result_display)) { $teamName = htmlspecialchars($rd['teamName']); } if(isset($_POST['btnSave'])) { # Get the input data from the form $inpName = $_POST['inpName']; # Execute the update query $sql_update = $con->prepare("UPDATE journeyteams SET teamName = ? WHERE teamID = ?"); $sql_update->bind_param("si", $inpName, $requestID); $sql_update->execute(); $txtEvent = "Updated record #". $requestID . " of journey teams from '" . $teamName . "' to '" . $inpName . "'"; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("Successfully udpated the record!"); header('refresh: 1; url=add_jt.php'); } } } else { header('location: error.php'); } ?><file_sep><?php $pageTitle = 'Journey Teams'; include_once 'includes/header.php'; # Echoes a redirect line if the user does not have access to the page accessPage($con, $accID); # Query for displaying the existing journey teams $sql_list = "SELECT teamID, teamName FROM journeyteams"; $result_list = $con->query($sql_list) or die(mysqli_error($con)); $list_teams = ""; if(mysqli_num_rows($result_list) == 0) { } else { # Display the records in a table format while($teams = mysqli_fetch_array($result_list)) { $teamID = $teams['teamID']; $teamName = htmlspecialchars($teams['teamName']); $list_teams .= " <tr> <td>$teamName <a href='edit_jt.php?id=$teamID' class='float-right'><span class='fa fa-edit fa-fw'></span></a></td> </tr>"; } } if(isset($_POST['btnAdd'])) { # Validate the input $inpName = inpcheck($_POST['inpName']); if(empty($inpName)) { $msgDisplay = errorAlert("Please make sure that your input is valid and try again."); } else { # Convert the input into upper string for validation $tName = strtoupper($inpName); # Validate that the input is not a duplicate $sql_validate = "SELECT teamName FROM journeyteams WHERE UPPER(teamName) = '$tName'"; $result_validate = $con->query($sql_validate) or die(mysqli_error($con)); if(mysqli_num_rows($result_validate) > 0) { $msgDisplay = errorAlert("The team you are adding already exists."); } else { $stmt_insert = $con->prepare("INSERT INTO journeyteams (teamName) VALUES (?)"); $stmt_insert->bind_param("s", $inpName); $stmt_insert->execute(); $txtEvent = "Added a new journey team: " . $inpName; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("Successfully added a new team."); header('Refresh: 1'); } } } ?><file_sep><?php include('config.php'); include('function.php'); if(isset($_POST['btnRegister'])) { # Get the input data from the form $inpFN = inpcheck($_POST['inpFN']); $inpLN = inpcheck($_POST['inpLN']); $inpEmail = inpcheck($_POST['inpEmail']); $inpPW = inpcheck($_POST['inpPW']); $inpConfirm = inpcheck($_POST['inpConfirm']); # Fields should have a valid input if(empty($inpFN) || empty($inpLN) || empty($inpEmail) || empty($inpPW)) { $msgDisplay = errorAlert("Please make sure that your inputs are valid and try again."); } else { # Validate that the pw and confirmpw fields match if(strcmp($inpPW, $inpConfirm) == 0) { # Validate if the email/account exists $sql_validate = "SELECT accountID FROM accounts WHERE accountUN = '$inpEmail'"; $result_validate = $con->query($sql_validate) or die(mysqli_error($con)); if(mysqli_num_rows($result_validate) == 0) { # The email does not exist yet; insert the record /* For reference, account status: 1 - active, 2 - pending, 3 - inactive/disabled */ # Insert the user's information into the table 'users' $stmt_user = $con->prepare("INSERT INTO users (userFN, userLN) VALUES (?, ?)"); $stmt_user->bind_param("ss", $inpFN, $inpLN); $stmt_user->execute(); # Get the id of the record that was just inserted $last_user = $con->insert_id; # Hash the password that was given. PASSWORD_DEFAULT uses bcrypt $hasdedun = password_hash($inpEmail, PASSWORD_DEFAULT); $hashedpw = password_hash($inpPW, PASSWORD_DEFAULT); # Insert the account/login info w/ the user's id into the table 'accounts' /* Account access levels: 1- Administrator 2- Elevated User 3- User (default access level for newly registered accounts) */ $stmt_account = $con->prepare("INSERT INTO accounts (accountUN, accountPW, accountAccess, accountStatus, userID) VALUES (?, ?, 3, 1, ?)"); $stmt_account->bind_param("sss", $hasdedun, $hashedpw, $last_user); $stmt_account->execute(); $msgDisplay = successAlert("<strong>Success!</strong> Your account was successfully created."); } else { # The email exists; display an error $msgDisplay = errorAlert("That email already exists. Sign in <a href='login.php'>here</a> if you already have an account."); } } else { $msgDisplay = errorAlert("Please make sure that both passwords match."); } } } ?><file_sep><?php #$logoutLink = str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/controllers/logout.php'); ?> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top" data-toggle="tooltip" data-placement="left" title="Back to Top" style="text-decoration: none"> <i class="fa fa-angle-up"></i> </a> <!-- Logout Modal--> <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="logoutModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="logoutModalLabel">Ready to Leave?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="<?php echo 'controllers/logout.php' ?>">Logout</a> </div> </div> </div> </div> </div> </body> </html><file_sep><?php $pageTitle = "Environments"; include 'includes/header.php'; # Echoes a redirect line if the user does not have access to the page accessPage($con, $accID); # Query for displaying the records $sql_list = "SELECT envID, envName FROM environments"; $result_list = $con->query($sql_list) or die(mysqli_error($con)); $list_env = ""; if(mysqli_num_rows($result_list) == 0) { #$list_env .= " # <tr> # <td class='text-center'>There are no records to display.</td> # </tr>"; } else { # Display the result in a table format while($row = mysqli_fetch_array($result_list)) { $envID = $row['envID']; $envName = htmlspecialchars($row['envName']); $list_env .= " <tr> <td>$envName <a href='edit_env.php?id=$envID' class='btn btn-outline-link btn-sm float-right'> <span class='fa fa-edit fa-fw'></span> </a> </td> </tr>"; } } if(isset($_POST['btnAdd'])) { # Get the input from the form $inpName = inpcheck($_POST['inpName']); # Validate that the input is not empty if(empty($inpName)) { $msgDisplay = errorAlert("Please make sure that your input is valid and try again."); } else { # convert the input value to uppercase for validation $tName = strtoupper($inpName); # Validate that the record being added doesnt already exist $sql_validate = "SELECT envName FROM environments WHERE UPPER(envName) = '$tName'"; $result_validate = $con->query($sql_validate) or die(mysqli_error($con)); if(mysqli_num_rows($result_validate) > 0) { $msgDisplay = errorAlert("The record you are trying to add already exists."); } else { $stmt_insert = $con->prepare("INSERT INTO environments (envName) VALUES (?)"); $stmt_insert->bind_param("s", $inpName); $stmt_insert->execute(); $txtEvent = "Added a new environment: " . $inpName; logEvent($con, $accID, $txtEvent); $msgDisplay = successAlert("Successfully added a new record."); header('Refresh: 1'); } } } ?><file_sep><?php include_once str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/controllers/function.php'); include_once str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/controllers/config.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- For IE 9 and below. ICO should be 32x32 pixels in size --> <!--[if IE]><link rel="shortcut icon" href="images/icons/awslogo.png"><![endif]--> <!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> <link rel="apple-touch-icon-precomposed" href="images/icons/awslogo.png"> <!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. --> <link rel="icon" href="images/icons/awslogo.png"> <meta name="description" content=""> <meta name="author" content=""> <title><?php echo $pageTitle; ?></title> <link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="lib/fontawesome/css/fontawesome-all.css" rel="stylesheet" type="text/css"> <link href="lib/datatables/dataTables.bootstrap4.css" rel="stylesheet"> <link href="css/sb-admin.css" rel="stylesheet"> <link href="lib/jasny-bootstrap/css/jasny-bootstrap.min.css" rel="stylesheet" type="text/css"> <script type="text/javascript"> function takeScreenshot() { // Calls the html2canvas API to generate a screenshot // Hide buttons (screenshot button and the back button) var bu = document.getElementById('formButtons'); if (bu.style.display === 'none') { bu.style.display = 'block'; } else { bu.style.display = 'none'; } // Take screenshot // (html2canvas generates an image by recreating the elements of the html body) html2canvas(document.body).then(function(canvas) { document.body.appendChild(canvas); }); // Hide form div (so only the screenshot will remain visible on the page) setTimeout(function() { var x = document.getElementById('formDiv'); if (x.style.display === 'none') { x.style.display = 'block'; } else { x.style.display = 'none'; }; }, 500); } </script> <style type="text/css"> .vertical-center { min-height: 100%; min-height: 100vh; display: flex; align-items: center; } .vertical-center-offset { min-height: 50%; min-height: 50vh; max-height: 50%; max-height: 50vh; display: flex; align-items: center; } </style> </head> <body id='page-top' onload="takeScreenshot()"> <div class="container-fluid"> <div class="row"> <div class="col-12"> <!-- Bootstrap core JavaScript--> <script src="js/jquery-3.3.1.min.js"></script> <script src="lib/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="js/jquery.easing.min.js"></script> <!-- Chart.js JavaScript--> <script src="js/Chart.min.js"></script> <!-- Chart.js Datalabels plugin --> <script src="lib/chartjs-datalabels/chartjs-plugin-datalabels.js"></script> <!-- Data Tables js --> <script src="lib/datatables/jquery.dataTables.js"></script> <script src="lib/datatables/dataTables.bootstrap4.js"></script> <script src="lib/datatables/dataTables.pageResize.min.js"></script> <!-- sb-admin template js --> <script src="js/sb-admin.min.js"></script> <script src="js/sb-admin-datatables.min.js"></script> <script src="js/sb-admin-charts.min.js"></script> <!-- jasny boostrap --> <script src="lib/jasny-bootstrap/js/jasny-bootstrap.min.js"></script> <!-- input masking --> <script src="js/jquery.maskMoney.min.js"></script> <!-- AddThis Share Buttons js --> <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-<PASSWORD>"></script> <!-- html2canvas js --> <script type="text/javascript" src="js/html2canvas.min.js"></script>
edd39053ee72310eec17665ccee7a0485b2cf055
[ "JavaScript", "SQL", "Text", "PHP" ]
41
PHP
markiancastillo/aws-csi
81869b4b6273d7a584e556fcb8fe78c25e0c8d4c
ba8ebbce0c37784bd384a41895e9be6847a0f86d
refs/heads/master
<repo_name>deivid7007/deivid7007.github.io<file_sep>/README.md # deivid7007.github.io<file_sep>/JS/distributor.js var rejime, canvas, context, radius,dragging, startX, startY, endX, endY, moyseStatus, draggingClear; $(document).ready(function () { canvas = document.getElementById('canvas'); context = canvas.getContext("2d"); radius = 10; dragging = false; canvas.width = window.innerWidth; canvas.height = window.innerHeight; context.lineWidth = radius*2; ColorPallete(); Radius(10); context.fillStyle = 'white'; context.fillRect(0,0,window.innerWidth,window.innerHeight); $("img").click(function () { rejime = $(this).attr("id"); moyseStatus = 0; dragging = false; Distribute(); }); $("#clear").click(function () { context.clearRect(0,0, canvas.width, canvas.height); }) }); function Distribute() { switch(rejime) { case "pen":Pen();break; case "line": moyseStatus = 1; Line(); break; case "sircle": moyseStatus = 1; Circle(); break; case "rect": moyseStatus = 1; Rectangle(); break; case "square": moyseStatus = 1; Rectangle(); break; case "guma":Guma() ;break; } } function Pen(){ var drawPen = function(e) { if (dragging && rejime === "pen") { context.lineTo(e.clientX, e.clientY); context.stroke(); context.beginPath(); // draw point context.arc(e.clientX, e.clientY, radius, 0, Math.PI*2); context.fill(); context.beginPath(); context.moveTo(e.clientX, e.clientY); } } var engagePen = function (e) { dragging = true; drawPen; } var disengagePen = function () { dragging = false; context.beginPath() } canvas.addEventListener('mousedown', engagePen); canvas.addEventListener('mousemove', drawPen); canvas.addEventListener('mouseup', disengagePen); } function Line() { function Draw(e) { if (rejime === "line") { context.moveTo(startX, startY); context.lineTo(endX, endY); context.stroke(); context.arc(e.clientX, e.clientY, radius, 0, Math.PI*2); context.fill(); context.beginPath(); } } var engageLine = function(e) { startX = e.clientX; startY = e.clientY; } var disengageLine = function(e) { endX = e.clientX; endY = e.clientY; Draw(e); } canvas.addEventListener('mousedown', engageLine); canvas.addEventListener('mouseup', disengageLine); } function Circle() { function Draw(e) { if (rejime === "sircle") { radiusCircle = (endX - startX) / 2; context.beginPath(); context.arc(startX, startY, radiusCircle, 0, Math.PI*2); context.stroke(); } } var engageLine = function(e) { startX = e.clientX; startY = e.clientY; } var disengageLine = function(e) { endX = e.clientX; endY = e.clientY; Draw(e); } canvas.addEventListener('mousedown', engageLine); canvas.addEventListener('mouseup', disengageLine); } function Rectangle() { function Draw(e) { var x,y; if (rejime === "rect") { x = (endX - startX); y = (endY - startY); } else if (rejime === "square") { x = y = endX - startX; } context.beginPath(); context.rect(startX, startY, x, y); context.stroke(); } var engageLine = function(e) { startX = e.clientX; startY = e.clientY; } var disengageLine = function(e) { endX = e.clientX; endY = e.clientY; if (rejime === "rect" || rejime === "square" ) { Draw(e); } } canvas.addEventListener('mousedown',engageLine); canvas.addEventListener('mouseup', disengageLine); } function Guma() { var drawClear = function(e) { if (draggingClear && rejime === "guma") { context.lineTo(e.clientX, e.clientY); context.stroke(); context.beginPath(); // draw point context.arc(e.clientX, e.clientY, radius, 0, Math.PI*2); context.fill(); context.beginPath(); context.moveTo(e.clientX, e.clientY); } } var engageClear = function (e) { draggingClear = true; drawClear; } var disengageClear = function () { draggingClear = false; context.beginPath() } canvas.addEventListener('mousedown', engageClear); canvas.addEventListener('mousemove', drawClear); canvas.addEventListener('mouseup', disengageClear); } function Radius(n) { // custom pen var setRadius = function (newRadius) { if (newRadius < minR) { newRadius = minR; } else if(newRadius > maxR){ newRadius = maxR; } radius = newRadius; context.lineWidth = radius*2; defR.innerHTML = radius; } var minR = 0.5, maxR = 100, defaultRadius = n, interval = 5, defR = document.getElementById('defR'), backR = document.getElementById('backR'), nextR = document.getElementById('nextR'); backR.addEventListener('click', function () { setRadius(radius - interval); }); nextR.addEventListener('click', function () { setRadius(radius + interval); }); } function ColorPallete() { var colors = ['black', 'brown','grey','white','red','orange','yellow','green','blue','indigo','violet']; var swtches = document.getElementsByClassName('switch'); for (var i = 0, n=colors.length; i < n ; i++) { var swatch = document.createElement('div'); swatch.className ='switch'; swatch.style.backgroundColor = colors[i]; swatch.addEventListener('click', setSwatch); document.getElementById('colors').appendChild(swatch); } function setColor(color) { context.fillStyle = color; context.strokeStyle = color; var active = document.getElementsByClassName('active')[0]; if (active) { active.className = 'switch'; } } function setSwatch(e) { var swatch = e.target; setColor(swatch.style.backgroundColor); swatch.className += ' active'; } setSwatch({target: document.getElementsByClassName('switch')[0] }); $("#guma").click(function () { setColor('white'); }); }
d0f9c10c4fdedf12d89b48d59468cfe68b1c8a5a
[ "Markdown", "JavaScript" ]
2
Markdown
deivid7007/deivid7007.github.io
638cb9db09057eea0445f144da4e9c750f8d4f7d
da5ac5c9358fc9c48db47ecf36fff0bd07c4f019
refs/heads/master
<file_sep>import React from 'react'; import './search-bar.component.css'; const Searchbar = ({placeholder, handleChange}) => { return ( <input className="search" type="text" placeholder={placeholder} onChange={handleChange}/> ) } export default Searchbar;
81a75a890cdcb99ff0f9d590ea162a92a083ff06
[ "JavaScript" ]
1
JavaScript
hardik98/Monster-mania
c197c9802ef7cb8d8574efbc1b37465935c5cafe
08e5a78b9092b6fc4bac954e7b70c53e018e1262
refs/heads/master
<repo_name>jt3k/painless-alarm-clock<file_sep>/lib/segments.js // full // |-----------------| // 0 9 // 0 A- B -C 9 // case 0 A < C && B < C && B > A // 0 B -C A- 9 // case 1 A > C && B < C // 0 -C A- B 9 // case 2 A > C && B > A // | | | | | // 0 3 6 8 9 // ------------------- // exceptions: // -C B A- // error 0 A > C && B < A && B > C // B A-----C // error 1 A < C && B < A // A-----C B // error 2 A < C && B > C // [case 0] // (AC) = (0С) - (0A) = (C) - (A) // (AB) = (0B) - (0A) = (B) - (A) // [case 1] // (AC) = (A9) + (0C) = (full - A) + C // (AB) = (A9) + (0B) = (full - A) + B // [case 2] // (AC) = (A9) + (0C) = (full - A) + C // (AB) = (0A) + (0C) = (B) - (A) function _calculateSegmentsLength(A, B, C, full = 60 * 60 * 24) { // exceptions const isException = A > C && B < A && B > C || A < C && B < A || A < C && B > C; if (isException) { return false; } let AC = 0; let AB = 0; // [case 0] if (A < C && B < C && B > A) { // console.log('[case 0]'); AC = C - A; AB = B - A; } // [case 1] if (A > C && B < C) { // console.log('[case 1]'); AC = (full - A) + C; AB = (full - A) + B; } // [case 2] if (A > C && B > A) { // console.log('[case 2]'); AC = (full - A) + C; AB = B - A; } return [AC, AB]; } function calculateSegmentsLengthRatio(A, B, C) { const isExteption = A === B || C === B; if (isExteption) { return false; } const lengths = _calculateSegmentsLength(A, B, C); if (!lengths) { return false; } // calculate ratio const [AC, AB] = lengths; return AB / AC; } module.exports = { calculateSegmentsLengthRatio }; <file_sep>/lib/h.js // [A--%--B C] // AB = first-segment function getFirstSegmentRatio(start, end, between) { return 100 / (end - start) * (between - start); } let id = 0; module.exports = { idGen: () => `id_${++id}`, getFirstSegmentRatio }; <file_sep>/README.md # painless-alarm-clock [![Build Status](https://travis-ci.org/jt3k/painless-alarm-clock.svg?branch=master)](https://travis-ci.org/jt3k/painless-alarm-clock) > Alarm clock with fade-in function > *It's currently not in a usable state.* ![illustration](./illustration.svg) ## Install ``` $ npm install --save painless-alarm-clock ``` ## Usage ```js const painlessAlarmClock = require('painless-alarm-clock'); painlessAlarmClock('unicorns'); //=> 'unicorns & rainbows' ``` ## API ### painlessAlarmClock(input, [options]) #### input Type: `string` Lorem ipsum. #### options ##### foo Type: `boolean`<br> Default: `false` Lorem ipsum. ## CLI ``` $ npm install --global painless-alarm-clock ``` ``` $ painless-alarm-clock --help Usage painless-alarm-clock [input] Options --foo Lorem ipsum. [Default: false] Examples $ painless-alarm-clock unicorns & rainbows $ painless-alarm-clock ponies ponies & rainbows ``` ## License MIT © [<NAME>](https://github.com/jt3k) <file_sep>/core.js const vol = require('vol'); const BezierEasing = require('bezier-easing'); const { bus, calculateSegmentsLengthRatio, convertTimeToSecondsSinceMidnignt } = require('./lib'); const { startEndlesPlaying, stopEndlessPlaying, sayTime } = require('./player'); const easing = new BezierEasing(1.0, 1.0, 1.0, 0.3); let curVolumeLevel = 0; let lastTimeSay = 0; const volSayCorrection = 1; bus.on('UPDATE', ({alarmStatus}) => { const isAlarm = alarmStatus !== false; if (isAlarm) { startEndlesPlaying(); } else { stopEndlessPlaying(); } console.log('isAlarm', isAlarm); const volumeLevel = Number(easing(alarmStatus).toFixed(3)) * volSayCorrection; if (alarmStatus !== false && curVolumeLevel !== volumeLevel) { console.log({ volumeLevel: volumeLevel.toFixed(4), alarmStatus: alarmStatus.toFixed(4) }); vol.set(volumeLevel, () => {}); curVolumeLevel = volumeLevel; // ///////////////////////////////////// // in half phase say time each 8 min // // ///////////////////////////////////// const sayRate = 8 * 60 * 1000; // 8 min const isTimeToSayTime = alarmStatus >= 0.5; // one say per 8 min const allowedToSay = (Date.now() - lastTimeSay) > sayRate; if (allowedToSay && isTimeToSayTime) { // setTimeout(); lastTimeSay = Date.now(); sayTime(); } } }); function painlessAlarmClock(START, END) { setInterval(() => { const NOW = (new Date()).toLocaleTimeString(); const startInSec = convertTimeToSecondsSinceMidnignt(START); const nowInSec = convertTimeToSecondsSinceMidnignt(NOW); const endInSec = convertTimeToSecondsSinceMidnignt(END); const alarmStatus = calculateSegmentsLengthRatio(startInSec, nowInSec, endInSec); bus.emit('UPDATE', { alarmStatus }); }, 1000); } module.exports = painlessAlarmClock; <file_sep>/lib/segments.test.js import test from 'ava'; import segments from './segments'; test('should calculate ratio of time segments', t => { t.is(segments.calculateSegmentsLengthRatio(0, 99, 100), 0.99); t.is(segments.calculateSegmentsLengthRatio(21600, 28800, 7200), 0.1); t.is(segments.calculateSegmentsLengthRatio(86400, 0, 43200), 0); let times = 100; while (--times) { t.is(segments.calculateSegmentsLengthRatio(0, times, 100), times / 100); // console.log('times / 100', times / 100); } // exceptions t.is(segments.calculateSegmentsLengthRatio(0, 0, 100), false); t.is(segments.calculateSegmentsLengthRatio(0, 100, 100), false); t.is(segments.calculateSegmentsLengthRatio(0, 101, 100), false); t.is(segments.calculateSegmentsLengthRatio(0, -101, 100), false); }); <file_sep>/lib/time.js function convertTimeToSecondsSinceMidnignt(time) { const [h, m, s] = time.split(':'); return ((Number(h) + Number(m) / 60) * 60 * 60) + Number(s); } function _padZeroAtLeft(num) { return String(num).padStart(2, '0'); } function fixTimeStringFormat(string) { return string.split(':').map(_padZeroAtLeft).join(':'); } module.exports = { convertTimeToSecondsSinceMidnignt, fixTimeStringFormat }; <file_sep>/lib/bus.js const EventEmitter = require('events'); class MyBus extends EventEmitter {} module.exports = new MyBus(); <file_sep>/cli.js #!/usr/bin/env node 'use strict'; const meow = require('meow'); const painlessAlarmClock = require('./'); const cli = meow([ 'Usage', ' $ painless-alarm-clock <START_TIME> <END_TIME>', '', 'Example', ' $ painless-alarm-clock 05:00:00 10:00:00' ]); const NOW = new Date(); const RAW_START_TIME = new Date(Number(NOW) + 3000).toLocaleTimeString(); const RAW_END_TIME = new Date(Number(NOW) + 30000).toLocaleTimeString(); console.log(painlessAlarmClock(cli.input[0] || RAW_START_TIME, cli.input[1] || RAW_END_TIME)); <file_sep>/player.js const say = require('say'); const lib = require('./lib'); const { procM: { spawn, kill, killall }, bus } = lib; function play(playlist) { const args = [ '-playlist', // 'cliqhop32.pls', playlist, '-quiet' ]; return spawn('mplayer', args); } let plzStopPlaying = false; let curStatus = 'stoped'; function startEndlesPlaying() { if (curStatus !== 'stoped') { return; } let proc = play('http://somafm.com/beatblender32.pls'); bus.emit('PLAYER', 'pending'); proc.stdout.on('data', data => { data = data.toString(); // console.log('stdout: ' + data); if (/\[coreaudio\]/.test(data)) { bus.emit('PLAYER', 'playing'); } }); proc.stderr.on('data', err => { err = err.toString(); // console.log('stderr: ' + err); if (/\[performance issue\]/.test(err)) { bus.emit('PLAYER', 'stoped'); } }); proc.on('close', code => { console.log(`CLOSING CODE: ${code}`); bus.emit('PLAYER', 'stoped'); sayTime(); if (plzStopPlaying) { plzStopPlaying = false; return; } proc = startEndlesPlaying(); }); return proc; } function stopEndlessPlaying() { plzStopPlaying = true; killall(); } bus.on('PLAYER', status => { console.log('status', status); curStatus = status; }); // startEndlesPlaying(); // play('http://somafm.com/cliqhop32.pls'); // play('http://somafm.com/groovesalad32.pls'); const stdin = process.stdin; stdin.setRawMode(true); stdin.resume(); stdin.setEncoding('utf-8'); function sayTime() { say.stop(); const timeString = (new Date()).toLocaleTimeString().replace(/\d+$/, ''); say.speak(timeString, 'Milena', 0.25); } stdin.on('data', key => { // say time if (key === 't') { sayTime(); } if (key === '\u0003' || key === '\u001b' || key === 'q') { // kill all child processes killall(); // close program kill(process.pid); } }); module.exports = { startEndlesPlaying, stopEndlessPlaying, sayTime }; // module.exports = function (str, opts) { // if (typeof str !== 'string') { // throw new TypeError('Expected a string'); // } // opts = opts || {}; // return str + ' & ' + (opts.postfix || 'rainbows'); // }; <file_sep>/lib/index.js module.exports = { bus: require('./bus.js'), procM: require('./process-manager.js'), ...require('./time.js'), ...require('./segments.js') };
503da88b0f74d32fed806ff1415956c7fa517947
[ "JavaScript", "Markdown" ]
10
JavaScript
jt3k/painless-alarm-clock
1c254f22275b684738063833c260d9118a8dc1c7
643fb1154d07fd1c1e807b13526b2ac6daede03b
refs/heads/master
<file_sep>package com.julia.demo2.Entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Frame { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private int roll1; private int roll2; private boolean roll1Done; private boolean roll2Done; public Frame() {} public Frame(int roll1, int roll2) { this.roll1 = roll1; this.roll2 = roll2; this.roll1Done = true; this.roll2Done = true; } public Frame(int roll1, int roll2, boolean roll1Done, boolean roll2Done) { this.roll1 = roll1; this.roll2 = roll2; this.roll1Done = roll1Done; this.roll2Done = roll2Done; } public int getId() { return id; } public int getRoll1() { return roll1; } public void setRoll1(int roll1) { this.roll1 = roll1; } public int getRoll2() { return roll2; } public void setRoll2(int roll2) { this.roll2 = roll2; } public boolean isRoll1Done() { return roll1Done; } public void setRoll1Done(boolean roll1Done) { this.roll1Done = roll1Done; } public boolean isRoll2Done() { return roll2Done; } public void setRoll2Done(boolean roll2Done) { this.roll2Done = roll2Done; } } <file_sep>package com.julia.demo2; import com.julia.demo2.Dao.FrameRepository; import com.julia.demo2.Entity.Frame; import com.julia.demo2.Entity.LastFrame; import com.julia.demo2.Service.GameService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.*; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.boot.test.web.client.TestRestTemplate; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Main.class ) @AutoConfigureMockMvc public class IntegrationTests { @Autowired MockMvc mockMvc; @Autowired FrameRepository repo; @Autowired GameService gameService; private static final int maxNumberOfFrames = 10; @Before public void init() { repo.save( new Frame( 1, 1 ) ); repo.save( new Frame( 1, 1 ) ); repo.save( new Frame( 1, 1 ) ); repo.save( new Frame( 1, 1 ) ); repo.save( new Frame( 1, 1 ) ); repo.save( new Frame( 1, 1 ) ); repo.save( new Frame( 1, 1 ) ); repo.save( new Frame( 1, 1 ) ); repo.save( new Frame( 1, 1 ) ); repo.save( new LastFrame(1,1,0, true, true, false) ); } private void previewFrames() throws Exception { MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.get("/game/") .accept(MediaType.APPLICATION_JSON) ).andReturn(); System.out.println("------------------ previewFrames ------------------"); System.out.println("response content = " + mvcResult.getResponse().getContentAsString()); } private int getScore() throws Exception { MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.get("/game/score/") .accept(MediaType.APPLICATION_JSON) ).andReturn(); return Integer.parseInt(mvcResult.getResponse().getContentAsString()); } @Test public void scoreNotAvailableBeforeGameHasFinished() throws Exception { Error e = null; try{ LastFrame lastFrame = (LastFrame) repo.findById(maxNumberOfFrames).orElse(null); lastFrame.setRoll3Done(false); lastFrame.setRoll2(0); lastFrame.setRoll2Done(false); previewFrames(); } catch (Exception ex) { System.out.println(ex.getMessage()); assertEquals( ex.getMessage(), gameService.GAME_NOT_FINISHED ); } } @Test public void scoreWithStrikeBonusAndSpareBonusInLastRound() { try{ Frame frame = repo.findById(1).orElseGet(null); frame.setRoll1(10); LastFrame lastFrame = (LastFrame) repo.findById(maxNumberOfFrames).orElseGet(null); lastFrame.setRoll1(5); lastFrame.setRoll2(5); lastFrame.setRoll3(5); lastFrame.setRoll3Done(true); repo.save(frame); repo.save(lastFrame); previewFrames(); int score = getScore(); assertEquals(44, score); // 37 normal points + 2 strike bonus + 5 spare bonus } catch (Exception e) { System.out.println("error message = " + e.getMessage()); } } } <file_sep>Bowling game kata The game consists of 10 frames. In each frame the player has two opportunities to knock down 10 pins. The score for the frame is the total number of pins knocked down, plus bonuses for strikes and spares. A spare is when the player knocks down all 10 pins in two tries. The bonus for that frame is the number of pins knocked down by the next roll. So in frame 3 above, the score is 10 (the total number knocked down) plus a bonus of 5 (the number of pins knocked down on the next roll.) A strike is when the player knocks down all 10 pins on his first try. The bonus for that frame is the value of the next two balls rolled. In the tenth frame a player who rolls a spare or strike is allowed to roll the extraballs to complete the frame. However no more than three balls can be rolled in tenth frame. 1. Write a class named “Game” that has two methods a. roll(pins : int) is called each time the player rolls a ball. The argument is the number of pins knocked down. b. score() : int is called only at the very end of the game. It returns the total score for that game. Expose roll and score methods as HTTP resources using newest Spring MVC and Spring Boot. . think about the structure and naming of the resource a. write end-to-end test using @SpringBootTest Persist game state between rolls in database . Use H2 in-memory database a. Use Hibernate as JPA implementation (you can try Spring Data JPA) <file_sep>package com.julia.demo2.Service; import java.util.Collection; import com.julia.demo2.Dao.FrameRepository; import com.julia.demo2.Entity.Frame; import com.julia.demo2.Entity.LastFrame; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class GameService { @Autowired private FrameRepository repo; private static final int maxNumberOfFrames = 10; public static final String END_OF_GAME = "End of game. Can't roll any more! " + "Get score first, and than start a new game."; public static final String GAME_NOT_FINISHED = "Game is not finished yet. " + "Score is available only after all rolls are done."; public Collection<Frame> getAllFrames() { return repo.findAll(); } public void roll(int pins) { if( isGameFinished() ) throw new Error("End of game. Can't roll any more! " + "Get score first, and than start a new game."); if( pins < 0 || pins > 10 ) throw new Error("Number of pins is from the range <0; 10>"); Frame frame = null; for(int i = 1; i <= maxNumberOfFrames; i++) { if(!repo.existsById(i)) { // frame does not exist if(i != maxNumberOfFrames) { frame = new Frame(0,0,false, false); } else if (i == maxNumberOfFrames) { frame = new LastFrame(0,0,0,false,false,false); } repo.save(frame); } else { // frame with id = i already exists in db if(i == maxNumberOfFrames) { frame = repo.findById(maxNumberOfFrames).orElse(null); //findOne(); } else { frame = repo.findById(i).orElse(null); } } if(frame.isRoll1Done()==false) { frame.setRoll1(pins); frame.setRoll1Done(true); break; } if(frame.isRoll2Done()==false) { frame.setRoll2(pins); frame.setRoll2Done(true); break; } if(frame.getId() == maxNumberOfFrames) { ((LastFrame) frame).setRoll3(pins); ((LastFrame) frame).setRoll3Done(true); } } if(frame.getId() == maxNumberOfFrames) { repo.save((LastFrame)frame); } else { repo.save(frame); } } private boolean isGameFinished() { if (repo.existsById(maxNumberOfFrames)) { LastFrame lastFrame = (LastFrame) repo.findById(maxNumberOfFrames).orElse(null); if (lastFrame.getRoll1() == 10 && lastFrame.isRoll2Done() && lastFrame.isRoll3Done() // strike || lastFrame.isRoll2Done() && lastFrame.getRoll1() + lastFrame.getRoll2() == 10 && lastFrame.isRoll3Done() // spare || lastFrame.isRoll1Done() && lastFrame.isRoll2Done() && lastFrame.getRoll1() + lastFrame.getRoll2() < 10) { return true; } } return false; } /* * gives total number of points at the END of the game * */ public int score() { if( !isGameFinished() ) throw new Error(GAME_NOT_FINISHED); Collection<Frame> allFrames = getAllFrames(); int score = 0, previousRoll1 = 0, previousRoll2 = 0; for( Frame frame : allFrames ) { int roll1 = frame.getRoll1(), roll2 = frame.getRoll2(); score += roll1 + roll2; if(previousRoll1 == 10) score += previousRoll2 + roll1; // strike bonus if (previousRoll1 + previousRoll2 == 10 && frame.isRoll2Done()) score += roll1; // spare bonus if( frame instanceof LastFrame) { if(roll1 == 10) score += roll2 + ((LastFrame) frame ).getRoll3(); // strike bonus if(roll1 + roll2 == 10 && frame.isRoll2Done()) score += ((LastFrame) frame ).getRoll3(); // spare bonus } previousRoll1 = roll1; previousRoll2 = roll2; } return score; } } <file_sep>package com.julia.demo2.Controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Collection; import com.julia.demo2.Entity.Frame; import com.julia.demo2.Service.GameService; @RestController @RequestMapping("/game") public class GameController { @Autowired private GameService gameService; // http://localhost:8080/game/ @RequestMapping(value = "/", method = RequestMethod.GET) public Collection<Frame> getAllFrames() { return gameService.getAllFrames(); } // http://localhost:8080/game/score/ @RequestMapping(value = "/score", method = RequestMethod.GET) public int score() { return gameService.score(); } // http://localhost:8080/game/roll/ @RequestMapping(value = "/roll", method = RequestMethod.PUT) public void roll(@RequestBody String pins) { try { gameService.roll(Integer.parseInt(pins)); } catch(Exception e) { e.getMessage(); } } } <file_sep>package com.julia.demo2.Dao; import com.julia.demo2.Entity.Frame; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface FrameRepository extends JpaRepository<Frame, Integer> { }
6586fe1319ba379a29caf0db9cd0643d71d37dc2
[ "Java", "Text" ]
6
Java
julkamaje/1app
ddc0f9bb4b14c2183c697484b6583461482db0f4
00700fe9264f56376a2de4bd7ad9b6fb50dbe857
refs/heads/master
<file_sep># School project: interfaceTest Use interface to link different classes together through common behavior. <file_sep>public class Prism extends Rectangle implements Volumeable{ private double height; public Prism(double length, double width, double height, String name){ super(length,width,name); this.height = height; } public double getHeight(){ return height; } public double getVolume(){ return getLength() * getWidth() * getHeight(); } public String toString(){ return "Prism " + getName() + " with length of " + getLength() + ", width of " + getWidth() + " and height of " + getWidth(); } }
f0f864866e59287afc77c996b5dd1fdf7d600ab6
[ "Markdown", "Java" ]
2
Markdown
OOYUKIOO/interfaceTest
f116740236461ce54ab9dce4ee69522860ea82bd
72bffcf0fb5c307dd008d8ca3d01b7016eff7ddf
refs/heads/main
<repo_name>somuncudayi/open_cv_face_mesh_detection.<file_sep>/main.py import cv2 import mediapipe as mp import time mp_face_mesh = mp.solutions.face_mesh mp_drawing = mp.solutions.drawing_utils drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1) cap=cv2.VideoCapture(0) with mp_face_mesh.FaceMesh( min_detection_confidence=0.5, min_tracking_confidence=0.5 ) as face_mesh: while cap.isOpened(): success, image = cap.read() start = time.time() image = cv2.cvtColor(cv2.flip(image, 1),cv2.COLOR_BGR2RGB) image.flags.writeable = False results = face_mesh.process(image) image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) if results.multi_face_landmarks: for face_landmarks in results.multi_face_landmarks: mp_drawing.draw_landmarks(image, landmark_list=face_landmarks,connections=mp_face_mesh.FACE_CONNECTIONS,landmark_drawing_spec=drawing_spec, connection_drawing_spec=drawing_spec) end = time.time() totaltime = end - start try: fps=1.0/totaltime except ZeroDivisionError: print(fps) cv2.putText(image,f'FPS:{int(fps)}',(20,70),cv2.FONT_HERSHEY_SIMPLEX,1.5,(255,0,0),2) cv2.imshow('MediaPipe FaceMesh', image) if cv2.waitKey(5) & 0xFF == 27: break cap.release() <file_sep>/README.md # open_cv_face_mesh_detection. This project utilizes opencv and python to create a facemesh. The project was built on pycharm platform. This project utilizes media pipe facemesh API and has a confidence threshold of 0.5. Due to media pipe it runs smoothly on workstations without GPU the code creates mesh on the face and calculates and displays upto 100+ FPS(frames per second).
989933f3c643c5f168fd1dccaff7b21efe86254c
[ "Markdown", "Python" ]
2
Python
somuncudayi/open_cv_face_mesh_detection.
daeb6fb68580f68c0bd244071060a2d4ee51db2c
cc53095ca721a64ee738a9558018ad6e5d6b292f
refs/heads/master
<repo_name>avmalyutin/json-merge-example<file_sep>/js/json-manipulate.controller.js /* global angular */ (function () { "use strict"; angular.module("jsonManipApp").controller("jsonManipCtrl", ["$log", function ($log) { var vm = this; vm.formatJSON = function () { var isJson = isJsonString(vm.source); if (isJson === false) { alert("JSON is wrong"); return; } var sourceParsedJson = JSON.parse(vm.source); var destinationParsedJson = {}; Object.keys(sourceParsedJson).forEach(function (key) { destinationParsedJson[key] = key; }); vm.destination = JSON.stringify(destinationParsedJson, null, 4); alert("Ready!"); }; vm.clearFields = function () { vm.source = undefined; vm.destination = undefined; }; function isJsonString(str) { try { JSON.parse(str); } catch (e) { return false; } return true; } }]); })(); <file_sep>/Gruntfile.js /* global module */ module.exports = function (grunt) { grunt.loadNpmTasks('grunt-merge-json'); grunt.loadNpmTasks('grunt-concat-json'); // Project configuration. grunt.initConfig({ 'merge-json': { // en: { // src: ["i18n/**/*-en.json", "!i18n/merged/locale-de.json"], // dest: "i18n/merged/locale-en.json" // }, // de: { // src: ["i18n/**/*-de.json", "!i18n/merged/locale-de.json"], // dest: "i18n/merged/locale-de.json" // } "i18n": { files: { "i18n/locale-en.json": ["i18n/**/*-en.json", "!i18n/locale-de.json"], "i18n/locale-de.json": ["i18n/**/*-de.json", "!i18n/locale-de.json"] } } }, 'concat-json': { en: { src: ["i18n/**/*-en.json", "!i18n/merged/locale-de.json"], dest: "i18n/merged/locale-en.json" }, de: { src: ["i18n/**/*-de.json", "!i18n/merged/locale-de.json"], dest: "i18n/merged/locale-de.json" } } }); grunt.registerTask('default', []); grunt.registerTask('merge-i18n', ['merge-json']); grunt.registerTask('merge-i18n-2', ['concat-json']); };
e040f407db557c145f5b9d4029c75ca0ea74d82f
[ "JavaScript" ]
2
JavaScript
avmalyutin/json-merge-example
90a3be053a42c59775dc2272bfa21850936aaa27
acb691e224a307b983fc4f7ff286a79e0212338c
refs/heads/master
<file_sep>package com.example.training.helloandroid; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; /** * Created by brahima on 20/05/15. */ public class DetailActivity extends Activity { public static final String TAG = DetailActivity.class.getSimpleName(); public static final int PICK_CONTACT_REQUEST = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detail_activity); LinearLayout firstBlock = (LinearLayout)findViewById(R.id.firstBlock); firstBlock.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG,"First Block is clicked"); } }); Intent intent = getIntent(); String message = intent.getStringExtra("message"); Toast.makeText(this, "Message : ["+message+"]", Toast.LENGTH_LONG).show(); Log.d(TAG, message); } public void visitAndroid(View v){ /*Uri android = Uri.parse("http://android.com"); Intent intent = new Intent(Intent.ACTION_VIEW,android); PackageManager pm = getPackageManager(); List activities = pm.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY); boolean isSafeIntent = (activities.size() > 0); if(isSafeIntent){ startActivity(intent); }*/ pickContact(); } public void displayNotification(View v){ Log.d(TAG,"displayNotification"); Intent intentService = new Intent(this,MyIntentService.class); intentService.setAction(MyIntentService.ACTION_NOTIF); intentService.putExtra(MyIntentService.EXTRA_PARAM1,"Ma superbe notification"); startService(intentService); } /*public void downloadData(View v) { Log.d(TAG,"displayNotification"); Intent service = new Intent(this,MyIntentService.class); startService(service); }*/ private void pickContact() { Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts")); pickContactIntent.setType(ContactsContract.CommonDataKinds.Email.CONTENT_TYPE); // Show user only contacts w/ emails //pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == PICK_CONTACT_REQUEST){ if(resultCode == RESULT_OK) { Log.d(TAG,"Result OK"); Log.d(TAG,data.toString()); }else if(resultCode == RESULT_CANCELED){ Log.d(TAG,"Cancelled"); if(data != null){ Log.d(TAG,data.toString()); } } } } @Override protected void onStart() { super.onStart(); // Initialiser ou Réinitialiser (récupération du gps) Log.d(TAG,"onStart()"); } @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "onRestart()"); } @Override protected void onResume() { super.onResume(); // Appeler à chaque fois que l'activité redevient visible Log.d(TAG, "onResume()"); } @Override protected void onPause() { super.onPause(); // Traitement cours (libérer webcam ou autre ...) Log.d(TAG, "onPause()"); } @Override protected void onStop() { super.onStop(); // Traitement plus long tel que pousser des données en bdd ... Log.d(TAG, "onStop()"); } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy()"); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); Log.d(TAG, "onRestoreInstanceState()"); if(savedInstanceState != null){ Log.d(TAG,savedInstanceState.toString()); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Log.d(TAG, "onSaveInstanceState()"); } }
a6b6034f8069158c9409c5ab992a93bda863f189
[ "Java" ]
1
Java
edenmob/android_training
8fe1a142ca79ca26a104d9a65c034636228b9560
d535f4aac8baa1419fceb269a0c1eac823105f68
refs/heads/master
<file_sep>class Event < ActiveRecord::Base belongs_to :tournament has_many :answers has_many :bets has_many :users, :through => :bets attr_accessible :description, :name, :tournament_id, :expiration_date, :correct_answer, :blocked def tournament_name tournament.name end def has_correct_answer? return correct_answer != nil end def correct_answer_name Answer.find(correct_answer).name end end <file_sep>class Tournament < ActiveRecord::Base belongs_to :category has_many :events has_many :bets, :through => :events attr_accessible :category_id, :description, :name def category_name category.name end def current_rank Event.transaction do Bet.transaction do rank = Hash.new {0} sum = 0 bets.each do |bet| if bet.answer_id == bet.correct_answer_id sum = sum+1 rank[bet.user] = rank[bet.user]+1 else rank[bet.user] = rank[bet.user] end end return rank.sort_by {|_key, value| -value} end end end end <file_sep>class Category < ActiveRecord::Base has_many :tournaments attr_accessible :description, :name end <file_sep>class Bet < ActiveRecord::Base belongs_to :user belongs_to :event attr_accessible :bet_date, :event_id, :user_id, :answer_id def answer_name Answer.find(answer_id).name end def user_name user.username end def event_name event.name end def tournament event.tournament end def tournament_name tournament.name end def correct_answer_id event.correct_answer end end <file_sep>class Role < ActiveRecord::Base # has_many :user_roles # has_many :roles, :through => :user_roles has_and_belongs_to_many :users attr_accessible :name end <file_sep>class User < ActiveRecord::Base # has_many :user_roles # has_many :roles, :through => :user_roles has_and_belongs_to_many :roles has_many :bets has_many :events, :through => :bets # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :role_ids def has_role?(role) return !!self.roles.find_by_name(role.to_s.camelize) end def answered?(event_id) return !!self.bets.find_by_event_id(event_id) end def answer (event_id) if answered? event_id b = bets.find_by_event_id(event_id) return b.answer_name else return '' end end end <file_sep>class Answer < ActiveRecord::Base belongs_to :event attr_accessible :event_id, :name def tournament_name event.tournament.name end def event_name event.name end end <file_sep>class AddExpirationDateAnd < ActiveRecord::Migration def up add_column :events, :expiration_date, :datetime add_column :events, :correct_answer, :integer end def down remove_column :events, :expiration_date remove_column :events, :correct_answer end end
5825117dcc7fbac591a44b0d585b0a6f2632aeeb
[ "Ruby" ]
8
Ruby
aszczepanski/betting-system
096de9aeef27d6c15c9f1a2e9272fae45b9aff63
19e38df955c0dd0f3e8d3b0cb07a141718925892
refs/heads/master
<repo_name>holmeslinux/jwm-artwork<file_sep>/README.md # jwm-artwork Artwork of the Manjaro JWM Community Edition <file_sep>/PKGBUILD # Maintainer: holmeslinux <<EMAIL>> pkgname=jwm-artwork pkgver=20160311 pkgrel=1 pkgdesc="artwork for jwm" arch=('any') license=('GPL3') url="https://github.com/holmeslinux/$pkgname" _snapshot=88b680538aeaa5d835860e1fb92d1ec890a19098 source=("$pkgname-$pkgver-$pkgrel.tar.gz::$url/archive/$_snapshot.tar.gz") md5sums=('839be3199e87e34d98739130dbcd66ee') prepare() { # fix file permissions chmod -x $srcdir/$pkgname-$_snapshot/buttons/jwm/* } package() { cd $srcdir/$pkgname-$_snapshot install -dm755 $pkgdir/usr/share/themes cp -r {buttons,GrayOrange} $pkgdir/usr/share/themes }
eca2baed0bb8a7a3c2f62f335bf2a216752e5536
[ "Markdown", "Shell" ]
2
Markdown
holmeslinux/jwm-artwork
8fd02bf5c0cfed917ff608113887c3e00caa1ec7
4d82280ae170ccfda75c6314ce2844a2d1316d6b
refs/heads/master
<file_sep>var resultado; var num1 = 0; var num2 = 0; function revealSuma() { cuadrosDeTexto = '<label>Primer número: </label>' + '<input type="text" id="n1Suma">'; cuadrosDeTexto += '<label> Segundo número: </label>' + '<input type="text" id="n2Suma">'; cuadrosDeTexto += '<button onclick="calcularSumaAPI()"> Calcular suma con API </button>'; cuadrosDeTexto += '<br>' + '<label id="resultadoSuma">' + '<em> El resultado de la suma aparecerá aquí... </em>' + '</label>'; document.getElementById("suma").innerHTML = cuadrosDeTexto; } function calcularSumaAPI() { var myNum1 = $('#n1Suma').val(); var myNum2 = $('#n2Suma').val(); var url = "http://localhost:8085/suma?num1=" + myNum1 + "&num2=" + myNum2; console.log(url); $.getJSON(url, function(json) { console.log(json); $('#resultadoSuma').html( '<h2>' + json.myResultado + '</h2>'); } ); } function revealResta() { cuadrosDeTexto = '<label>Primer número: </label>' + '<input type="text" id="n1Resta">'; cuadrosDeTexto += '<label> Segundo número: </label>' + '<input type="text" id="n2Resta">'; cuadrosDeTexto += '<button onclick="calcularRestaAPI()"> Calcular resta con API </button>'; cuadrosDeTexto += '<br>' + '<label id="resultadoResta">' + '<em> El resultado de la resta aparecerá aquí... </em>' + '</label>'; document.getElementById("resta").innerHTML = cuadrosDeTexto; } function calcularRestaAPI() { var myNum1 = $('#n1Resta').val(); var myNum2 = $('#n2Resta').val(); var url = "http://localhost:8085/resta?num1=" + myNum1 + "&num2=" + myNum2; console.log(url); $.getJSON(url, function(json) { console.log(json); $('#resultadoResta').html( '<h2>' + json.myResultado + '</h2>'); } ); } function revealMulti() { cuadrosDeTexto = '<label>Primer número: </label>' + '<input type="text" id="n1Multi">'; cuadrosDeTexto += '<label> Segundo número: </label>' + '<input type="text" id="n2Multi">'; cuadrosDeTexto += '<button onclick="calcularMultiAPI()"> Calcular multiplicación con API </button>'; cuadrosDeTexto += '<br>' + '<label id="resultadoMulti">' + '<em> El resultado de la multiplicación aparecerá aquí... </em>' + '</label>'; document.getElementById("multi").innerHTML = cuadrosDeTexto; } function calcularMultiAPI() { var myNum1 = $('#n1Multi').val(); var myNum2 = $('#n2Multi').val(); var url = "http://localhost:8085/multi?num1=" + myNum1 + "&num2=" + myNum2; console.log(url); $.getJSON(url, function(json) { console.log(json); $('#resultadoMulti').html( '<h2>' + json.myResultado + '</h2>'); } ); } function revealDivi() { cuadrosDeTexto = '<label>Primer número: </label>' + '<input type="text" id="n1Divi">'; cuadrosDeTexto += '<label> Segundo número: </label>' + '<input type="text" id="n2Divi">'; cuadrosDeTexto += '<button onclick="calcularDiviAPI()"> Calcular división con API </button>'; cuadrosDeTexto += '<br>' + '<label id="resultadoDivi">' + '<em> El resultado de la división aparecerá aquí... </em>' + '</label>'; document.getElementById("divi").innerHTML = cuadrosDeTexto; } function calcularDiviAPI() { var myNum1 = $('#n1Divi').val(); var myNum2 = $('#n2Divi').val(); var url = "http://localhost:8085/divi?num1=" + myNum1 + "&num2=" + myNum2; console.log(url); $.getJSON(url, function(json) { console.log(json); $('#resultadoDivi').html( '<h2>' + json.myResultado + '</h2>'); } ); } function revealRaiz() { cuadrosDeTexto = '<label>Número: </label>' + '<input type="text" id="nRaiz">'; cuadrosDeTexto += '<button onclick="calcularRaizAPI()"> Calcular raíz con API </button>'; cuadrosDeTexto += '<br>' + '<label id="resultadoRaiz">' + '<em> El resultado de la raíz cuadrada aparecerá aquí... </em>' + '</label>'; document.getElementById("raiz").innerHTML = cuadrosDeTexto; } function calcularRaizAPI() { var myNum = $('#nRaiz').val(); var url = "http://localhost:8085/raiz?num=" + myNum; console.log(url); $.getJSON(url, function(json) { console.log(json); $('#resultadoRaiz').html( '<h2>' + json.myResultado + '</h2>'); } ); } function revealCuadrado() { cuadrosDeTexto = '<label>Número: </label>' + '<input type="text" id="nCuadrado">'; cuadrosDeTexto += '<button onclick="calcularCuadradoAPI()"> Calcular exponente al cuadrado con API </button>'; cuadrosDeTexto += '<br>' + '<label id="resultadoCuadrado">' + '<em> El resultado del cuadrado aparecerá aquí... </em>' + '</label>'; document.getElementById("cuadrado").innerHTML = cuadrosDeTexto; } function calcularCuadradoAPI() { var myNum = $('#nCuadrado').val(); var url = "http://localhost:8085/cuadrado?num=" + myNum; console.log(url); $.getJSON(url, function(json) { console.log(json); $('#resultadoCuadrado').html( '<h2>' + json.myResultado + '</h2>'); } ); }
d50a4e9376fb43750736f838037f29ceed1d56c2
[ "JavaScript" ]
1
JavaScript
AaronCG01/Calculadora-Simple
51410fb4343dee6bd89b13d699b27e5222797509
46e933231c2c3349c2ec9e775a7e72e1847286a6
refs/heads/master
<repo_name>imhelle/yii2-xhprof-lib<file_sep>/lib/tests/xhprof_024.phpt --TEST-- XHProf: Transaction name detecion in layering mode --FILE-- <?php function get_query_template($name) { } // Test 1: Detection with layers xhprof_layers_enable( array('strlen' => 'db'), 'get_query_template' ); get_query_template("home"); echo "Wordpress 1: " . xhprof_transaction_name() . "\n"; $data = xhprof_disable(); // Test 2: Repetition to catch global state errors xhprof_layers_enable( array('strlen' => 'db'), 'get_query_template' ); get_query_template("page"); echo "Wordpress 2: " . xhprof_transaction_name() . "\n"; $data = xhprof_disable(); // Test 3: Without any layers defined xhprof_layers_enable(array(), 'get_query_template'); get_query_template("post"); echo "Wordpress 3: " . xhprof_transaction_name() . "\n"; $data = xhprof_disable(); --EXPECTF-- Wordpress 1: home Wordpress 2: page Wordpress 3: post <file_sep>/DebugPanelAsset.php <?php namespace imhelle\xhprof; use yii\web\AssetBundle; /** * Class DebugPanelAsset * Debug panel asset * * @author <NAME> <<EMAIL>> * @date 16.11.2017 */ class DebugPanelAsset extends AssetBundle { public $sourcePath = '@vendor/imhelle/yii2-xhprof-lib'; public $css = [ 'assets/xhprof.css' ]; public $js = [ 'assets/xhprof.js' ]; } <file_sep>/lib/tests/xhprof_019.phpt --TEST-- XHPRof: xhprof_layers_enable() Author: beberlei --FILE-- <?php include_once dirname(__FILE__).'/common.php'; function foo($x) { return file_get_contents(__FILE__); } function bar($x) { return strlen($x); } echo "With layers:\n"; xhprof_layers_enable(array('file_get_contents' => 'io', 'strlen' => 'db', 'main()' => 'main()')); foo("bar"); bar("baz"); $data = xhprof_disable(); print_canonical($data); echo "\nWithout layers:\n"; xhprof_layers_enable(NULL); ?> --EXPECTF-- With layers: db : ct= 1; wt=*; io : ct= 1; wt=*; main() : ct= 1; wt=*; Without layers: Notice: xhprof_layers_enable() requires first argument to be array in %s/xhprof_019.php on line %d
8442b7b68f975e146c348b2fd065cc23d9787eae
[ "PHP" ]
3
PHP
imhelle/yii2-xhprof-lib
2f9706e0239e1732b3065c2715dcfba170fbca5b
5e2cb8b91b31b4fb0983dad14dfdfa47135b4fe4
refs/heads/master
<repo_name>Jiusen/AD<file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/dao/AdUnitDao.java package com.imooc.ad.dao; import com.imooc.ad.entity.AdUnit; import org.springframework.stereotype.Repository; import java.util.List; /** * @author <NAME> * @date 2021/2/1 21:04 */ @Repository public interface AdUnitDao { /** * 得到单条记录 * @param id 推广单元id * @return */ AdUnit findById(Long id); /** * 得到单条记录 * @param planId 计划id * @param unitName 单元名字 * @return */ AdUnit findByPlanIdAndUnitName(Long planId, String unitName); /** * 多条记录 * @param unitStatus 单元状态 * @return */ List<AdUnit> findAllByUnitStatus(Integer unitStatus); /** * 得到多条记录 * @param ids 推广单元id * @return */ List<AdUnit> findAllById(List<Long> ids); /** * 添加推广单元 * @param adUnit * @return */ Long save(AdUnit adUnit); } <file_sep>/imooc-ad-service/ad-search/src/main/java/com/imooc/ad/search/ISearch.java package com.imooc.ad.search; import com.imooc.ad.search.vo.SearchRequest; import com.imooc.ad.search.vo.SearchResponse; /** * 搜索服务接口 */ public interface ISearch { /** * 搜索服务 * @param request 请求数据 * @return 返回应答 */ SearchResponse fetchAds(SearchRequest request); } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/dao/CreativeDao.java package com.imooc.ad.dao; import com.imooc.ad.entity.Creative; import org.springframework.stereotype.Repository; import java.util.List; /** * @author <NAME> * @date 2021/2/1 21:07 */ @Repository public interface CreativeDao { /** * 多条添加 -创意单元 * @param creative * @return */ Long save(Creative creative); /** * 得到所有记录 * @param creativeIds 创意 ids * @return */ List<Creative> findAllById(List<Long> creativeIds); /** * 得到所有记录 * @return */ List<Creative> findAll(); } <file_sep>/imooc-ad-service/ad-search/src/main/java/com/imooc/ad/client/SponsorClientHystrix.java package com.imooc.ad.client; import com.imooc.ad.client.vo.AdPlan; import com.imooc.ad.client.vo.AdPlanGetRequest; import com.imooc.ad.vo.CommonResponse; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.util.List; /** * @author <NAME> * @date 2021/2/7 17:40 */ @Service public class SponsorClientHystrix implements SponsorClient{ @Override //服务降级 (业务类与降级分离开来) public CommonResponse<List<AdPlan>> getAdPlans(AdPlanGetRequest request) { return new CommonResponse<>(-1, "eureka-client-ad-sponsor error"); } } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/SponsorApplication.java package com.imooc.ad; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; /** * @author <NAME> * @date 2021/2/1 16:34 * 主启动 */ @EnableEurekaClient @EnableCircuitBreaker @EnableFeignClients @SpringBootApplication @MapperScan("com.imooc.ad.dao") public class SponsorApplication { public static void main(String[] args) { SpringApplication.run(SponsorApplication.class, args); } } <file_sep>/imooc-ad-service/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>imooc-ad</artifactId> <groupId>com.imooc.ad</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>imooc-ad-service</artifactId> <version>1.0-SNAPSHOT</version> <properties> <spring-cloud.version>Finchley.RELEASE</spring-cloud.version> <mysql.version>5.1.47</mysql.version> <druid.version>1.1.16</druid.version> <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version> </properties> <modules> <module>ad-common</module> <module>ad-sponsor</module> <module>test</module> <module>ad-search</module> </modules> <packaging>pom</packaging> <dependencies> <!-- MySQL 驱动, 注意, 这个需要与 MySQL 版本对应 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- druid数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.spring.boot.version}</version> </dependency> </dependencies> </project><file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/dao/AdUserDao.java package com.imooc.ad.dao; import com.imooc.ad.entity.AdUser; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; /** * @author <NAME> * @date 2021/2/1 20:49 */ @Repository public interface AdUserDao { /** * 通过用户名字得到用户记录 * @param username * @return */ AdUser findByUserName(String username); AdUser findByIde(Long id); Long save(AdUser adUser); } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> </parent> <groupId>com.imooc.ad</groupId> <artifactId>imooc-ad</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>ad-eureka</module> <module>ad-gateway</module> <module>imooc-ad-service</module> </modules> <name>imooc-ad-spring-cloud</name> <description>Project For Imooc Ad SpringCloud</description> <!--子模块继承之后,提供作用:锁定版本 + 子modlue不用写groupId和version --> <!-- 统一管理jar包版本 --> <properties> <spring-cloud.version>Finchley.RELEASE</spring-cloud.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version> <log4j.version>1.2.17</log4j.version> <lombok.version>1.16.18</lombok.version> <mysql.version>5.1.47</mysql.version> <druid.version>1.1.16</druid.version> <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version> </properties> <!--子模块继承之后,提供作用:锁定版本 + 子modlue不用写groupId和version --> <dependencyManagement> <dependencies> <!-- &lt;!&ndash; spring boot 2.2.2 &ndash;&gt;--> <!-- <dependency>--> <!-- <groupId>org.springframework.boot</groupId>--> <!-- <artifactId>spring-boot-dependencies</artifactId>--> <!-- <version>2.2.2.RELEASE</version>--> <!-- <type>pom</type>--> <!-- <scope>import</scope>--> <!-- </dependency>--> <!-- spring cloud Hoxton.SR1 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <!-- spring cloud alibaba 2.1.0.RELEASE --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.1.0.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.spring.boot.version}</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <!-- <repositories>--> <!-- <repository>--> <!-- <id>spring-milestones</id>--> <!-- <name>Spring Milestones</name>--> <!-- <url>https://repo.spring.io/milestone</url>--> <!-- <snapshots>--> <!-- <enabled>false</enabled>--> <!-- </snapshots>--> <!-- </repository>--> <!-- </repositories>--> <!-- <build>--> <!-- <plugins>--> <!-- <plugin>--> <!-- <groupId>org.springframework.boot</groupId>--> <!-- <artifactId>spring-boot-maven-plugin</artifactId>--> <!-- <configuration>--> <!-- <fork>true</fork>--> <!-- <addResources>true</addResources>--> <!-- </configuration>--> <!-- </plugin>--> <!-- </plugins> &lt;!&ndash;将mapper文件打包进去&ndash;&gt;--> <!-- <resources> <resource> &lt;!&ndash;指定根目录 到源文件夹 一般如下&ndash;&gt;--> <!-- <directory>src/main/java</directory>--> <!-- <includes> <include>**/*.yml</include>--> <!-- <include>**/*.yaml</include>--> <!-- <include>**/*.xml</include>--> <!-- <include>**/*.properties</include>--> <!-- </includes>--> <!-- <filtering>false</filtering>--> <!-- </resource> <resource>--> <!-- &lt;!&ndash;指定根目录 到源文件夹 一般如下&ndash;&gt;--> <!-- <directory>src/main/resources</directory>--> <!-- <includes> <include>**/*.yml</include>--> <!-- <include>**/*.yaml</include>--> <!-- <include>**/*.xml</include>--> <!-- <include>**/*.properties</include>--> <!-- </includes> <filtering>false</filtering>--> <!-- </resource>--> <!-- </resources>--> <!-- </build>--> </project><file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/entity/unit_condition/AdUnitIt.java package com.imooc.ad.entity.unit_condition; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author <NAME> * @date 2021/2/1 18:48 * 推广单元-兴趣 */ @Data @AllArgsConstructor @NoArgsConstructor public class AdUnitIt { /** * 推广单元兴趣唯一 id */ private Long id; /** * 推广单元 id */ private Long unitId; /** * 兴趣标签 */ private String itTag; public AdUnitIt(Long unitId, String itTag) { this.unitId = unitId; this.itTag = itTag; } } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/dao/unit_condition/AdUnitItDao.java package com.imooc.ad.dao.unit_condition; import com.imooc.ad.entity.unit_condition.AdUnitIt; import com.imooc.ad.entity.unit_condition.AdUnitKeyword; import org.springframework.stereotype.Repository; import java.util.List; /** * @author <NAME> * @date 2021/2/1 21:11 */ @Repository public interface AdUnitItDao { /** * 批量插入数据 * @param unitIts * @return */ List<Long> saveAll(List<AdUnitIt> unitIts); /** * 得到所有记录 * @return */ List<AdUnitIt> findAll(); } <file_sep>/imooc-ad-service/ad-search/src/main/java/com/imooc/ad/client/SponsorClient.java package com.imooc.ad.client; import com.imooc.ad.client.vo.AdPlan; import com.imooc.ad.client.vo.AdPlanGetRequest; import com.imooc.ad.vo.CommonResponse; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; /** * @author <NAME> * @date 2021/2/7 17:30 */ @FeignClient(value = "eureka-client-ad-sponsor", fallback = SponsorClientHystrix.class) public interface SponsorClient { @PostMapping(value = "/ad-sponsor/get/adPlan") CommonResponse<List<AdPlan>> getAdPlans(@RequestBody AdPlanGetRequest request); } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/service/impl/IAdUnitServiceImpl.java package com.imooc.ad.service.impl; import com.imooc.ad.constant.Constants; import com.imooc.ad.dao.AdPlanDao; import com.imooc.ad.dao.AdUnitDao; import com.imooc.ad.dao.CreativeDao; import com.imooc.ad.dao.unit_condition.AdUnitDistrictDao; import com.imooc.ad.dao.unit_condition.AdUnitItDao; import com.imooc.ad.dao.unit_condition.AdUnitKeywordDao; import com.imooc.ad.dao.unit_condition.CreativeUnitDao; import com.imooc.ad.entity.AdPlan; import com.imooc.ad.entity.AdUnit; import com.imooc.ad.entity.unit_condition.AdUnitDistrict; import com.imooc.ad.entity.unit_condition.AdUnitIt; import com.imooc.ad.entity.unit_condition.AdUnitKeyword; import com.imooc.ad.entity.unit_condition.CreativeUnit; import com.imooc.ad.exception.AdException; import com.imooc.ad.service.IAdUnitService; import com.imooc.ad.vo.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; /** * @author <NAME> * @date 2021/2/3 1:19 */ @Service public class IAdUnitServiceImpl implements IAdUnitService { @Autowired private AdPlanDao adPlanDao; @Autowired private AdUnitDao adUnitDao; @Autowired private AdUnitKeywordDao adUnitKeywordDao; @Autowired private AdUnitItDao adUnitItDao; @Autowired private AdUnitDistrictDao adUnitDistrictDao; @Autowired private CreativeDao creativeDao; @Autowired private CreativeUnitDao creativeUnitDao; @Override public AdUnitResponse createUnit(AdUnitRequest request) throws AdException { if (!request.createValidate()) { throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR); } AdPlan adPlan = adPlanDao.findById(request.getPlanId()); if (adPlan == null) { throw new AdException(Constants.ErrorMsg.CAN_NOT_FIND_RECORD); } AdUnit oldAdUnit = adUnitDao.findByPlanIdAndUnitName( request.getPlanId(), request.getUnitName() ); if (oldAdUnit != null) { throw new AdException(Constants.ErrorMsg.SAME_NAME_UNIT_ERROR); } Long newAdUnitId = adUnitDao.save( new AdUnit(request.getPlanId(), request.getUnitName(), request.getPositionType(), request.getBudget()) ); AdUnit newAdUnit = adUnitDao.findById(newAdUnitId); return new AdUnitResponse(newAdUnit.getId(), newAdUnit.getUnitName()); } @Override public AdUnitKeywordResponse createUnitKeyword(AdUnitKeywordRequest request) throws AdException { List<Long> unitIds = request.getUnitKeywords().stream() //双冒号的用法,就是把方法当做参数传到stream内部,使stream的每个元素都传入到该方法里面执行一下。 .map(AdUnitKeywordRequest.UnitKeyword::getUnitId) //Object::function 代表这个对象的方法 .collect(Collectors.toList()); if (!isRelatedUnitExist(unitIds)) { throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR); } List<Long> ids = Collections.emptyList(); List<AdUnitKeyword> unitKeywords = new ArrayList<>(); //遍历添加(单元id、关键词) if (!CollectionUtils.isEmpty(request.getUnitKeywords())) { request.getUnitKeywords().forEach(i -> unitKeywords.add( new AdUnitKeyword(i.getUnitId(), i.getKeyword()) )); //批量插入 adUnitKeywordDao.saveAll(unitKeywords); //得到批量插入后数据的 ids ids = unitKeywords.stream() .map(AdUnitKeyword::getId) .collect(Collectors.toList()); } return new AdUnitKeywordResponse(ids); } @Override public AdUnitItResponse createUnitIt(AdUnitItRequest request) throws AdException { List<Long> unitIds = request.getUnitIts().stream() //双冒号的用法,就是把方法当做参数传到stream内部,使stream的每个元素都传入到该方法里面执行一下。 .map(AdUnitItRequest.UnitIt::getUnitId) //Object::function 代表这个对象的方法 .collect(Collectors.toList()); if (!isRelatedUnitExist(unitIds)) { throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR); } List<Long> ids = Collections.emptyList(); List<AdUnitIt> unitIts = new ArrayList<>(); //遍历添加(单元id、关键词) if (!CollectionUtils.isEmpty(request.getUnitIts())) { request.getUnitIts().forEach(i -> unitIts.add( new AdUnitIt(i.getUnitId(), i.getItTag()) )); //批量插入 adUnitItDao.saveAll(unitIts); //得到批量插入后数据的 ids ids = unitIts.stream() .map(AdUnitIt::getId) .collect(Collectors.toList()); } return new AdUnitItResponse(ids); } @Override public AdUnitDistrictResponse createUnitDistrict(AdUnitDistrictRequest request) throws AdException { List<Long> unitIds = request.getUnitDistricts().stream() //双冒号的用法,就是把方法当做参数传到stream内部,使stream的每个元素都传入到该方法里面执行一下。 .map(AdUnitDistrictRequest.UnitDistrict::getUnitId) //Object::function 代表这个对象的方法 .collect(Collectors.toList()); if (!isRelatedUnitExist(unitIds)) { throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR); } List<Long> ids = Collections.emptyList(); List<AdUnitDistrict> unitDistricts = new ArrayList<>(); //遍历添加(单元id、关键词) if (!CollectionUtils.isEmpty(request.getUnitDistricts())) { request.getUnitDistricts().forEach(i -> unitDistricts.add( new AdUnitDistrict(i.getUnitId(), i.getProvince(), i.getCity()) )); //批量插入 adUnitDistrictDao.saveAll(unitDistricts); //得到批量插入后数据的 ids ids = unitDistricts.stream() .map(AdUnitDistrict::getId) .collect(Collectors.toList()); } return new AdUnitDistrictResponse(ids); } @Override public CreativeUnitResponse createCreativeUnit(CreativeUnitRequest request) throws AdException { //java8 语法 :得到所有记录的 单元id List<Long> unitIds = request.getUnitItems().stream().map(CreativeUnitRequest.CreativeUnitItem::getUnitId).collect(Collectors.toList()); //关联的创意id List<Long> creativeIds = request.getUnitItems().stream().map(CreativeUnitRequest.CreativeUnitItem::getCreativeId).collect(Collectors.toList()); if (!(isRelatedUnitExist(unitIds) && isRelatedUnitExist(creativeIds))) { throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR); } List<CreativeUnit> creativeUnits = new ArrayList<>(); request.getUnitItems().forEach(i -> creativeUnits.add( new CreativeUnit(i.getCreativeId(), i.getUnitId()) )); //批量插入后对应的 ids List<Long> ids = creativeUnitDao.saveAll(creativeUnits); return new CreativeUnitResponse(ids); } //单元 ids是否存在 private boolean isRelatedUnitExist(List<Long> unitIds) { if (CollectionUtils.isEmpty(unitIds)) { return false; } return adUnitDao.findAllById(unitIds).size() == new HashSet<>(unitIds).size(); } //创意 ids是否存在 private boolean isRelatedCreativeExist(List<Long> creativeIds) { if (CollectionUtils.isEmpty(creativeIds)) { return false; } //是否有重复的 ids return creativeDao.findAllById(creativeIds).size() == new HashSet<>(creativeIds).size(); } } <file_sep>/imooc-ad-service/ad-search/src/main/java/com/imooc/ad/mysql/dto/Template.java package com.imooc.ad.mysql.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; /** * @author <NAME> * @date 2021/2/9 19:15 * 模板 json 数据 */ @Data @AllArgsConstructor @NoArgsConstructor public class Template { /** * 数据库 */ private String database; /** * 所有表 */ private List<JsonTable> tableList; } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/entity/unit_condition/AdUnitKeyword.java package com.imooc.ad.entity.unit_condition; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author <NAME> * @date 2021/2/1 18:43 * 推广单元-关键词 */ @Data @AllArgsConstructor @NoArgsConstructor public class AdUnitKeyword { /** * 推广单元关键词 唯一id */ private Long id; /** * 推广单元 id */ private Long unitId; /** * 关键词 */ private String keyword; public AdUnitKeyword(Long unitId, String keyword) { this.unitId = unitId; this.keyword = keyword; } } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/dao/AdPlanDao.java package com.imooc.ad.dao; import com.imooc.ad.entity.AdPlan; import org.springframework.stereotype.Repository; import java.util.List; /** * @author <NAME> * @date 2021/2/1 20:55 */ @Repository public interface AdPlanDao { /** * 查询单条记录 * @param id 计划id * @return */ AdPlan findById(Long id); /** * 查询单条记录 * @param id 计划id * @param userId 用户id * @return */ AdPlan findByIdAndUserId(Long id, Long userId); /** * 查询多条记录 * @param ids 计划ids * @param userId 用户id * @return */ List<AdPlan> findAllByIdInAndUserId(List<Long> ids, Long userId); /** * 查询单条记录 * @param userId 用户id * @param planName 计划名称 * @return */ AdPlan findByIdAndPlanName(Long userId, String planName); /** * 查询多条记录 * @param status 状态 * @return */ List<AdPlan> findAllByPlanStatus(Integer status); /** * 插入数据 * @param adPlan * @return */ Long save(AdPlan adPlan); } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/entity/Creative.java package com.imooc.ad.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @author <NAME> * @date 2021/2/1 19:00 * 创意表(提供给用户看的) */ @Data @AllArgsConstructor @NoArgsConstructor public class Creative { /** * 创意表唯一id */ private Long id; /** * 创意名称 */ private String name; /** * 物料类型(图片, 视频) */ private Integer type; /** * 物料子类型(图片: bmp, jpg 等等) */ private Integer materialType; /** * 高度 */ private Integer height; /** * 宽度 */ private Integer width; /** * 物料大小, 单位是 KB */ private Long size; /** * 持续时长, 只有视频才不为 0 */ private Integer duration; /** * 审核状态 */ private Integer auditStatus; /** * 标记当前记录所属用户 */ private Long userId; /** * 物料地址 */ private String url; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; } <file_sep>/imooc-ad-service/ad-search/src/main/java/com/imooc/ad/index/adunit/AdUnitConstants.java package com.imooc.ad.index.adunit; /** * @author <NAME> * @date 2021/2/14 2:38 * 广告出现的时间 */ public class AdUnitConstants { public static class POSITION_TYPE { public static final int KAIPING = 1; //开屏 public static final int TIEPIAN = 2; //贴片 public static final int TIEPIAN_MIDDLE = 4; //贴片中... public static final int TIEPIAN_PAUSE = 8; public static final int TIEPIAN_POST = 16; } } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/entity/AdPlan.java package com.imooc.ad.entity; import com.imooc.ad.constant.CommonStatus; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @author <NAME> * @date 2021/2/1 18:16 * 推广计划 */ @Data @AllArgsConstructor @NoArgsConstructor public class AdPlan { /** * 计划唯一id */ private Long id; /** * 绑定的用户id */ private Long userId; /** * 计划标题 */ private String planName; /** * 计划状态 开/关 */ private Integer planStatus; /** * 计划起始日期 */ private Date startDate; /** * 计划终止日期 */ private Date endDate; /** * 计划创建时间 */ private Date createTime; /** * 计划更新时间 */ private Date updateTime; public AdPlan(Long userId, String planName, Date startDate, Date endDate) { this.userId = userId; this.planName = planName; this.planStatus = CommonStatus.VALID.getStatus(); this.startDate = startDate; this.endDate = endDate; this.createTime = new Date(); this.updateTime = this.createTime; } } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/dao/unit_condition/CreativeUnitDao.java package com.imooc.ad.dao.unit_condition; import com.imooc.ad.entity.unit_condition.CreativeUnit; import org.springframework.stereotype.Repository; import java.util.List; /** * @author <NAME> * @date 2021/2/1 21:12 */ @Repository public interface CreativeUnitDao { /** * 批量保存 * @param creativeUnits * @return */ List<Long> saveAll(List<CreativeUnit> creativeUnits); /** * 得到所有数据记录 * @return */ List<CreativeUnit> findAll(); } <file_sep>/imooc-ad-service/ad-sponsor/src/main/java/com/imooc/ad/entity/AdUnit.java package com.imooc.ad.entity; import com.imooc.ad.constant.CommonStatus; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @author <NAME> * @date 2021/2/1 18:27 * 推广单元 */ @Data @AllArgsConstructor @NoArgsConstructor public class AdUnit { /** * 推广单元唯一id */ private Long id; /** * 推广单元绑定的推广计划id */ private Long planId; /** * 推广单元名称 */ private String unitName; /** * 推广单元状态 */ private Integer unitStatus; /** * 广告位类型(开屏、贴片、中贴、暂停贴,后贴...) */ private Integer positionType; /** * 预算 */ private Long budget; /** * 创建日期 */ private Date createTime; /** * 更新日期 */ private Date updateTime; public AdUnit(Long planId, String unitName, Integer positionType, Long budget) { this.planId = planId; this.unitName = unitName; this.unitStatus = CommonStatus.VALID.getStatus(); this.positionType = positionType; this.budget = budget; this.createTime = new Date(); this.updateTime = this.createTime; } } <file_sep>/imooc-ad-service/ad-search/src/main/java/com/imooc/ad/index/IndexFileLoader.java package com.imooc.ad.index; import com.alibaba.fastjson.JSON; import com.imooc.ad.dump.DConstant; import com.imooc.ad.dump.table.*; import com.imooc.ad.handler.AdLevelDataHandler; import com.imooc.ad.mysql.constant.OpType; import org.springframework.context.annotation.DependsOn; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; /** * @author <NAME> * @date 2021/2/8 20:34 * 全量索引的加载 */ @Component @DependsOn("dataTable") //控制bean加载顺序 public class IndexFileLoader { /** * 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。 * Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法) * 初始化,加载文件中的数据 */ @PostConstruct public void init() { //得到文件中每一行 --- 每一条数据 List<String> adPlanStrings = loadDumpData(String.format("%s%s", DConstant.DATA_ROOT_DIR, DConstant.AD_PLAN)); //解析每一条数据,随后执行添加方法,添加到对应类的map中 adPlanStrings.forEach(p -> AdLevelDataHandler.handleLevel2(JSON.parseObject(p, AdPlanTable.class), OpType.ADD)); adPlanStrings.forEach(p -> AdLevelDataHandler.handleLevel2(JSON.parseObject(p, AdPlanTable.class), OpType.ADD)); List<String> adCreativeStrings = loadDumpData(String.format("%s%s", DConstant.DATA_ROOT_DIR, DConstant.AD_CREATIVE)); adCreativeStrings.forEach(c -> AdLevelDataHandler.handleLevel2(JSON.parseObject(c, AdCreativeTable.class), OpType.ADD)); List<String> adUnitStrings = loadDumpData(String.format("%s%s", DConstant.DATA_ROOT_DIR, DConstant.AD_UNIT)); adUnitStrings.forEach(u -> AdLevelDataHandler.handleLevel3(JSON.parseObject(u, AdUnitTable.class), OpType.ADD)); List<String> adCreativeUnitStrings = loadDumpData(String.format("%s%s", DConstant.DATA_ROOT_DIR, DConstant.AD_CREATIVE_UNIT)); adCreativeUnitStrings.forEach(cu -> AdLevelDataHandler.handleLevel3(JSON.parseObject(cu, AdCreativeUnitTable.class), OpType.ADD)); List<String> adUnitDistrictStrings = loadDumpData(String.format("%s%s", DConstant.DATA_ROOT_DIR, DConstant.AD_UNIT_DISTRICT)); adUnitDistrictStrings.forEach(d -> AdLevelDataHandler.handleLevel4(JSON.parseObject(d, AdUnitDistrictTable.class), OpType.ADD)); List<String> adUnitItStrings = loadDumpData(String.format("%s%s", DConstant.DATA_ROOT_DIR, DConstant.AD_UNIT_IT)); adUnitItStrings.forEach(i -> AdLevelDataHandler.handleLevel4(JSON.parseObject(i, AdUnitItTable.class), OpType.ADD)); List<String> adUnitKeywordStrings = loadDumpData(String.format("%s%s", DConstant.DATA_ROOT_DIR, DConstant.AD_UNIT_KEYWORD)); adUnitKeywordStrings.forEach(k -> AdLevelDataHandler.handleLevel4(JSON.parseObject(k, AdUnitKeywordTable.class), OpType.ADD)); } /** * 读取文件中的数据 * @param fileName * @return */ private List<String> loadDumpData(String fileName) { try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))){ return br.lines().collect(Collectors.toList()); //得到所有行数的 数据 } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } }
636977147a64f6825a7faa45822e32efde85cef2
[ "Java", "Maven POM" ]
21
Java
Jiusen/AD
7f3fe81b08bc08121f98e6e58a0e0ba37aa5d535
3608392dfe9851dc9bdbdb27c2fc4fce1547f465
refs/heads/master
<file_sep>#include <stdio.h> #include<stdlib.h> struct donors { char Name[300]; char Age[300]; char Address[500]; char EmailId[100]; char mobile[1000]; char bloodGroup[100]; char Gender[100]; }; int main() { struct donors *ptr; int i, noOfRecords; printf("Enter number of Donors who want to donate blood: "); scanf("%d", &noOfRecords); // Allocates the memory for noOfRecords structures with pointer ptr pointing to the base address. ptr = (struct donors*) malloc (noOfRecords * sizeof(struct donors)); for(i = 0; i < noOfRecords; ++i) { printf("Enter valid name of Donor: \n"); scanf("%s", &(ptr+i)->Name); printf("Enter valid Age of Donor: \n"); scanf("%s", &(ptr+i)->Age); printf("Enter valid Address of Donor: \n"); scanf("%s", &(ptr+i)->Address); printf("Enter valid EmailId of Donor: \n"); scanf("%s", &(ptr+i)->EmailId); printf("Enter valid mobile of Donor: \n"); scanf("%s", &(ptr+i)->mobile); printf("Enter valid bloodGroup of Donor: \n"); scanf("%s", &(ptr+i)->bloodGroup); printf("Enter valid Gender of Donor: \n"); scanf("%s", &(ptr+i)->Gender); } printf("\n\n\nDisplaying Information of Donors:\n\n\n"); for(i = 0; i < noOfRecords ; ++i) { printf("Name of donor is:%s\n", (ptr+i)->Name); printf("Age of donor is:%s\n", (ptr+i)->Age); printf("Address of donor is:%s\n", (ptr+i)->Address); printf("EmailId of donor is:%s\n", (ptr+i)->EmailId); printf("mobile of donor is:%s\n", (ptr+i)->mobile); printf("bloodGroup of donor is:%s\n", (ptr+i)->bloodGroup); printf("Gender of donor is:%s\n", (ptr+i)->Gender); } return 0; }
78b64d48e2f4c418cf43eb2278afb6540716f83e
[ "C" ]
1
C
Neeraj121296/sumit
785608255ff58f968f29bf2bee51605793215cd8
e260d9291470d171bddcde7784859aa806f26ff3
refs/heads/master
<file_sep>// // MapKitViewController.swift.swift // MAMapKit // // Created by <NAME> on 31/07/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import MapKit import CoreLocation class MapKitViewController: UIViewController { //MARK: - IBOutlets @IBOutlet weak var mapView: MAMapKit! @IBOutlet weak var menuButton: UIButton! //MARK: - Variables let islamabad = CLLocationCoordinate2DMake(33.7080, 73.0497) let islamabad2 = CLLocationCoordinate2DMake(33.7132, 73.0497) var annotationView : MKAnnotationView = MKAnnotationView() let locationManager: CLLocationManager = { let manager = CLLocationManager() manager.requestWhenInUseAuthorization() return manager }() //MARK: - UIView Life Cycle Methods override func viewDidLoad() { super.viewDidLoad() setupUIViewController() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: - Setup Metjods func setupUIViewController() { mapView.setMap(view: view) } //MARK: - Helper Methods // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } //MARK: - IBActions @IBAction func menuButtonTapped(_ sender: Any) { let alert = UIAlertController(title: nil, message: Messages.SelectOption, preferredStyle: .actionSheet) //--------------------------------------------- Current Location --------------------------------------------- alert.addAction(UIAlertAction(title: Title.CurrentLocation, style: .default , handler:{ (UIAlertAction) in self.mapView.currentLocation() })) //--------------------------------------------- May Type --------------------------------------------- alert.addAction(UIAlertAction(title: Title.MapType, style: .default , handler:{ (UIAlertAction) in self.present(self.mapView.mapTerrin(), animated: true, completion: nil) })) //--------------------------------------------- Set Pin --------------------------------------------- alert.addAction(UIAlertAction(title: Title.SetPin, style: .default , handler:{ (UIAlertAction) in self.mapView.setPinOnMap(view: self.view, title: "Islamabad", locationName: "Pakistan", coordinate: self.islamabad) self.mapView.setPinWithImageOnMap(view: self.view, title: "Islamabad", locationName: "Pakistan", coordinate: self.islamabad2) })) //--------------------------------------------- Draw Circle --------------------------------------------- alert.addAction(UIAlertAction(title: Title.DrawCircle, style: .default , handler:{ (UIAlertAction) in self.mapView.drawCircle(coordinate: self.islamabad, radius: 200) self.mapView.drawCircle(coordinate: self.islamabad2, radius: 200) })) //--------------------------------------------- Dismiss --------------------------------------------- alert.addAction(UIAlertAction(title: Title.Dismiss, style: .cancel, handler:{ (UIAlertAction) in })) self.present(alert, animated: true, completion: { }) } } <file_sep>// // MAMapKit.swift // MAMaps // // Created by <NAME> on 04/07/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import MapKit class MAMapKit: MKMapView { //MARK: - Variables var annotationView : MKAnnotationView = MKAnnotationView() let locationManager: CLLocationManager = { let manager = CLLocationManager() manager.requestWhenInUseAuthorization() return manager }() //MARK: - Init Methods override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self } //MARK: - Map Setup func setMap(view: UIView) { showsUserLocation = true showsCompass = true showsScale = true setupUserTrackingButtonAndScaleView(view: view) } //MARK: - User Location Button func setupUserTrackingButtonAndScaleView(view: UIView) { if #available(iOS 11.0, *) { let button = MKUserTrackingButton(mapView: self) button.layer.backgroundColor = UIColor(white: 1, alpha: 0.8).cgColor button.layer.cornerRadius = 5 button.translatesAutoresizingMaskIntoConstraints = false view.addSubview(button) NSLayoutConstraint.activate([button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -40), button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)]) } else { } } //MARK: - Current Location Method func currentLocation() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest if #available(iOS 11.0, *) { locationManager.showsBackgroundLocationIndicator = true } else { // Fallback on earlier versions } locationManager.startUpdatingLocation() } //MARK: - Map Terrin Type func mapTerrin() -> UIAlertController { let alert = UIAlertController(title: nil, message: Messages.SelectOption, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: Title.Hybrid, style: .default , handler:{ (UIAlertAction) in self.mapType = .hybrid })) alert.addAction(UIAlertAction(title: Title.HybridFlyover, style: .default , handler:{ (UIAlertAction) in self.mapType = .hybridFlyover })) alert.addAction(UIAlertAction(title: Title.MutedStandard, style: .default , handler:{ (UIAlertAction) in if #available(iOS 11.0, *) { self.mapType = .mutedStandard } else { // Fallback on earlier versions } })) alert.addAction(UIAlertAction(title: Title.Satellite, style: .default, handler:{ (UIAlertAction) in self.mapType = .satellite })) alert.addAction(UIAlertAction(title: Title.SatelliteFlyover, style: .default, handler:{ (UIAlertAction) in self.mapType = .satelliteFlyover })) alert.addAction(UIAlertAction(title: Title.Standard, style: .default, handler:{ (UIAlertAction) in self.mapType = .standard })) alert.addAction(UIAlertAction(title: Title.Dismiss, style: .cancel, handler:{ (UIAlertAction) in })) return alert } //MARK: - Seting Pin func setCurrentLocationPinOnMap(view: UIView, title: String, locationName: String, coordinate: CLLocationCoordinate2D) { let pin1 = CurrentMapPin(title: title, locationName: locationName, coordinate: coordinate) let coordinateRegion = MKCoordinateRegionMakeWithDistance(pin1.coordinate, 800, 800) setRegion(coordinateRegion, animated: true) addAnnotations([pin1]) } func setPinOnMap(view: UIView, title: String, locationName: String, coordinate: CLLocationCoordinate2D) { let pin1 = MapPin(title: title, locationName: locationName, coordinate: coordinate) let coordinateRegion = MKCoordinateRegionMakeWithDistance(pin1.coordinate, 800, 800) setRegion(coordinateRegion, animated: true) addAnnotations([pin1]) } func setPinWithImageOnMap(view: UIView, title: String, locationName: String, coordinate: CLLocationCoordinate2D) { let pin1 = ImageMapPin(title: title, locationName: locationName, coordinate: coordinate) let coordinateRegion = MKCoordinateRegionMakeWithDistance(pin1.coordinate, 800, 800) setRegion(coordinateRegion, animated: true) addAnnotations([pin1]) } //MARK: - Draw Circle func drawCircle(coordinate: CLLocationCoordinate2D, radius: CLLocationDistance) { let circle = MKCircle(center: coordinate, radius: radius) add(circle) } } //MARK: - MKMapView Delegate Methods extension MAMapKit: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let Identifier = "Pin" annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: Identifier) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: Identifier) annotationView.canShowCallout = true if #available(iOS 11.0, *) { annotationView.clusteringIdentifier = "PinCluster" } else { // Fallback on earlier versions } if annotation is MKUserLocation { return nil } else if annotation is ImageMapPin { annotationView.image = #imageLiteral(resourceName: "pin") return annotationView } else { return nil } } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { annotationView.canShowCallout = false } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if let circleOverlay = overlay as? MKCircle { let circleRenderer = MKCircleRenderer(overlay: circleOverlay) circleRenderer.fillColor = UIColor.black circleRenderer.alpha = 0.5 circleRenderer.strokeColor = .red circleRenderer.lineWidth = 3 return circleRenderer }else { return MKPolylineRenderer() } } } //MARK: - CLLocationManager Delegate extension MAMapKit: CLLocationManagerDelegate { // Get Current Location func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last! as CLLocation let currentLocation = location.coordinate let coordinateRegion = MKCoordinateRegionMakeWithDistance(currentLocation, 800, 800) setRegion(coordinateRegion, animated: true) // locationManager.stopUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error.localizedDescription) } } <file_sep># MAMapKit ![Platform](https://img.shields.io/badge/Platform-iOS-orange.svg) ![Languages](https://img.shields.io/badge/Language-Swift-orange.svg) # Overview ### Functionalities - [Current Location](#current-location) - [Map Types](#map-types) - Hybrid - Hybrid Flyover - Muted Standard - Satellite - Satellite Flyover - Standard - [Pin On Map](#pin-on-map) - [Default](#default) - [With custom image/Annotation](#with-custom-image) - [Draw Circle on given location](#draw-circle-on-given-location) ### Current Location ```swift self.mapView.currentLocation() ``` ### Map Types ```swift self.present(self.mapView.mapTerrin(), animated: true, completion: nil) ``` ### Pin On Map Default ```swift self.mapView.setPinOnMap(view: self.view, title: "Islamabad", locationName: "Pakistan", coordinate: self.islamabad) ``` With Custom Image ```swift self.mapView.setPinWithImageOnMap(view: self.view, title: "Islamabad", locationName: "Pakistan", coordinate: self.location) ``` ### Draw Circle on given location ```swift self.mapView.drawCircle(coordinate: self.islamabad, radius: 200) ```
bdc2de63cb9a819a6beb1ddbc725c0bb66a00b7f
[ "Swift", "Markdown" ]
3
Swift
Muneebaliarshad/MAMapKit
8bd01178da421e94c7ce40c479e29c3100195633
f27b14b4aa019d5399deb3bdc8b04ef832054ce7
refs/heads/master
<file_sep>app.factory('vizService', function ($rootScope, $log, $timeout, $document, userDefaults) { "use strict"; var service = {}; var _loadedScripts = {}; service.startViz = function (vizSrc, imgData) { if (!_loadedScripts[vizSrc]) { $log.info("Loading " + vizSrc); var script = $document[0].createElement("script"); script.src = vizSrc; $document[0].head.appendChild(script); script.onload = function () { _loadedScripts[vizSrc] = true; try { runScene(imgData, $rootScope, userDefaults); } catch (error) { $log.error(error); $rootScope.$broadcast('VIZ_DONE'); } }; script.onerror = function() { $log.error("Viz file " + vizSrc + " failed to load."); $rootScope.$broadcast('VIZ_DONE'); }; } else { $log.info("Script " + vizSrc + " already loaded, running scene"); try { runScene(imgData, $rootScope, userDefaults); } catch (error) { $log.error("Error running viz:" + error); $log.error("Error running viz may be because viz code does not have a proper runScene() method."); $rootScope.$broadcast('VIZ_DONE'); } } }; return service; }); <file_sep>app.config(function ($routeProvider) { $routeProvider .when('/image/:seqNum', { templateUrl: 'app/components/ImageView/imageview.partial.html', controller: 'imageViewController' }) .when('/video/:seqNum', { templateUrl: 'app/components/VideoView/videoview.partial.html', controller: 'videoViewController' }) .when('/viz/:seqNum', { templateUrl: 'app/components/VizView/vizview.partial.html', controller: 'vizViewController' }) .when('/eviz/:seqNum', { templateUrl: 'app/components/EmbeddedVizView/embeddedvizview.partial.html', controller: 'embeddedVizViewController' }) .when('/loading', { templateUrl: 'app/components/LoadingView/loadingview.partial.html', controller: 'loadViewController' }) .when('/config', { templateUrl: 'app/components/ConfigView/configview.partial.html', controller: 'configViewController' }) .otherwise('/'); }); <file_sep>app.controller("embeddedVizViewController", function ( $scope, $log, playlistService, $timeout) { $scope.$on('VIZ_DONE', function() { playlistService.completed(); }); var item = playlistService.getCurrent(); $scope.vizSrc = item.src; $scope.vizMsg = ''; $scope.embedError = false; fs.stat(item.src, function(err){ var vizName = item.src.replace('cache/viz/', '').replace('/index.html', ''); if (err) { $scope.vizMsg = "Error loading index.html for the visualizer " + vizName + ". Make sure your visualizer has a file named index.html in its root directory."; $scope.embedError = true; } }); fs.readJson(item.src.replace('index.html', 'info.json'), function(err, object) { if (err) { $log.error("Visualizer does not contain 'info.json' in its root. Using default time of 30s."); } else { item.duration = object.duration; } $timeout(playlistService.completed, parseInt(item.duration) * 1000); }) }); <file_sep>/********************************* File: nwviz.module Function: Base App Copyright: AppDelegates LLC Date: 3/10/15 Author: atorres **********************************/ var app = angular.module('nwVizApp', [ 'ngRoute', 'ngSanitize', 'ngAnimate', 'ui.event', 'userdefaults.service', 'ngActiv8orLite']) app.run(function ($rootScope, $location, $log, playlistService, $timeout, actv8API, cacheService, userDefaults) { var a8Origin, cmsAddr, venueId; $rootScope.configs = undefined; $rootScope.errorMsg = ""; $rootScope.fatalError = false; $rootScope.loadingMsg = 'Getting configuration'; $timeout(function () { $location.path('loading') }); fs.readJson("locals/config.json", function (err, object) { if (err) { $log.info("No local config.json file found. Using default config.json."); fs.readJson("config.json", function (err, object) { if (err) { $log.error("No config.json file was found"); $rootScope.errorMsg = "No config.json file was found. Please add one!"; $rootScope.$broadcast('FATAL_ERROR'); } else { try { object.a8uname.x; object.a8pwd.x; object.cmsuname.x; object.cmspwd.x; object.defaultCmsAddr.x; object.defaultVenueId.x; object.defaultA8Ip.x; $rootScope.configs = object; $rootScope.$broadcast('CONFIGS_LOADED'); } catch (err) { $log.error("config.json is malformed"); $rootScope.errorMsg = "The config.json file is missing necessary fields."; $rootScope.$broadcast('FATAL_ERROR'); } } }); } else { try { object.a8uname.x; object.a8pwd.x; object.cmsuname.x; object.cmspwd.x; object.defaultCmsAddr.x; object.defaultVenueId.x; object.defaultA8Ip.x; $rootScope.configs = object; $rootScope.$broadcast('CONFIGS_LOADED'); } catch (err) { $log.error("config.json is malformed"); $rootScope.errorMsg = "The config.json file is missing necessary fields."; $rootScope.$broadcast('FATAL_ERROR'); } } }); // Done as a listener so it is easily called from other controllers $rootScope.$on('CONFIGS_LOADED', function () { var a8Ip = userDefaults.getStringForKey("a8Ip", $rootScope.configs.defaultA8Ip); venueId = userDefaults.getStringForKey("venueId", $rootScope.configs.defaultVenueId); cmsAddr = userDefaults.getStringForKey("cmsAddr", $rootScope.configs.defaultCmsAddr); a8Origin = 'http://' + a8Ip + ':1337'; userDefaults.setStringForKey('a8Ip', a8Ip); userDefaults.setStringForKey('cmsAddr', cmsAddr); userDefaults.setStringForKey('venueId', venueId); $rootScope.loadingMsg = 'Logging in to Activ8or'; // Note: cannot use file:// with node webkit actv8API.setSiteOrigin(a8Origin); // More concise, the way the cool kids roll actv8API.authorize($rootScope.configs.a8uname, $rootScope.configs.a8pwd).then(cacheService.clear); }); $rootScope.$on('NOT_AUTHORIZED', function () { $rootScope.loadingMsg = 'Error logging in to Activ8or. Make sure your credentials are correct and you have Activ8or running on ' + a8Origin + '. Press ESC to change the Activ8or IP address. Continuing app...'; $timeout(cacheService.clear, 5000); }); $rootScope.$on('CACHE_EMPTY', function () { $rootScope.loadingMsg = 'Cache successfully emptied.'; playlistService.init(cmsAddr); }); $rootScope.$on('CACHE_NOT_EMPTY', function () { $rootScope.errorMsg = 'Error emptying cache.'; $rootScope.$broadcast('FATAL_ERROR'); }); $rootScope.$on('FATAL_ERROR', function () { $rootScope.fatalError = true; }) }); <file_sep>app.controller("videoViewController", function ( $scope, $log, $timeout, playlistService ) { var item = playlistService.getCurrent(); $scope.currentItem = item; $scope.vidSrc = item.src; $scope.videoDone = function() { playlistService.completed(); } } ); <file_sep>app.factory('playlistService', function ($rootScope, $location, $timeout, $log, $http, cacheService, $q, userDefaults) { "use strict"; var service = {}; var _index = 0; var path; var playlistExt = 'viz-playlist-rest'; var tokenExt = 'services/session/token'; var loginExt = 'api/v1/user/login.json'; var mediaExt = 'api/v1/node/'; var mediaFilesExt = 'sites/default/files/'; var _nodes; var _i; var _stop = false; var ERR_MSG_TIME = 3000; // amount of time to show error messages service.playlist = []; service.playlistValid = false; function getToken() { return $http.get(path + tokenExt) .then(function(data) { $log.info("Got token"); $http.defaults.headers.common["X-CSRF-Token"] = data.data; return true; }) } service.login = function() { //MAK, discovered getting the token should not be necessary, but need to test //getToken() // .then(function() { return $q(function(resolve, reject) { superagent .post(path + loginExt) .send({username: $rootScope.configs.cmsuname, password: $rootScope.configs.cmspwd}) //.set('X-CSRF-Token', $http.defaults.headers.common["X-CSRF-Token"]) .set('Accept', 'application/json') .end(function (err, res) { if(err) { reject('Error logging in to the content management system. ' + 'Make sure credentials and CMS address are correct and you have an internet connection. Press ESC to configure CMS address.'); } else { resolve({data: res}); } }); }); // }, function(error) { // reject('Error logging in to the content management system. Make sure credentials are correct. Press ESC to configure CMS address.'); // }); }; service.init = function (endpoint) { var nodes, tmp; var venueId, playlistJSON; path = endpoint; $rootScope.loadingMsg = "Logging in to CMS"; service.login() .then(function () { $http.get(path + playlistExt) .then(function (data) { // get desired playlist by venue id // TODO: Playlists are listed without unique ids on commtix, so how do we choose which one? venueId = parseInt(userDefaults.getStringForKey("venueId", $rootScope.configs.defaultVenueId)); if (!venueId && venueId != 0) { $log.error("Error: invalid venue id " + venueId); $rootScope.errorMsg = "Invalid venue ID. Venue ID must be a number. " + "Press ESC to reconfigure."; $rootScope.$broadcast("FATAL_ERROR"); return; } try { playlistJSON = data.data.nodes[venueId].node; } catch(err) { $log.error("Error: Playlist at index venueId does not exist."); $rootScope.errorMsg = "No playlist exists for venue ID " + venueId + ". Press ESC to enter a different venue ID."; $rootScope.$broadcast("FATAL_ERROR"); return; } // get media item node ids for the playlist try { tmp = playlistJSON['Media Items']; } catch(err) { $log.error("Error: Playlist JSON is malformed. " + err); $rootScope.errorMsg = "Playlist JSON at " + path + playlistExt + " is malformed."; $rootScope.$broadcast("FATAL_ERROR"); return; } if (typeof tmp !== 'string') { $log.error("Error: Playlist JSON is malformed. "); $rootScope.errorMsg = "Playlist JSON at " + path + playlistExt + " is malformed."; $rootScope.$broadcast("FATAL_ERROR"); return; } nodes = tmp.split(" "); _nodes = nodes; _i = 0; $rootScope.loadingMsg = "Processing playlist"; service.processPlaylist(); }, function() { $rootScope.errorMsg = "Could not load playlist. Make sure you have a playlist up on " + endpoint; $rootScope.$broadcast("FATAL_ERROR"); }) }, function(error) { $log.error(error); $rootScope.errorMsg = error; $rootScope.$broadcast('FATAL_ERROR'); }) }; service.processPlaylist = function() { var i = _i; var n; if (i < _nodes.length) { n = i + 1; $rootScope.loadingMsg = 'Loading item ' + n + ' out of ' + _nodes.length; service.getMediaData(parseInt(_nodes[i])); } if (i == _nodes.length) { if (service.playlist.length > 0) { service.playlistValid = true; _index = 0; $rootScope.$broadcast('PLAYLIST_LOADED'); } else { service.playlistValid = false; $log.error('Media for playlist did not load properly.'); $rootScope.errorMsg = 'Media for playlist did not load properly. Either the playlist is empty ' + 'or there was an issue getting the individual media items. Check '+ path + ' to make sure you have a valid playlist loaded.'; $rootScope.$broadcast('FATAL_ERROR'); } } _i++; }; service.getMediaData = function(nodeNum) { var current = { src: undefined, type: undefined, duration: 30, supported: true }; var src, dest, filetype, filename; $http.get(path + mediaExt + nodeNum + '.json') .then(function(data) { try { current.type = data.data.type; } catch(err) { $log.error("Error: JSON for node " + nodeNum + " is malformed. Processing next item. " + err); $rootScope.loadingMsg = 'The JSON file at ' + path + mediaExt + nodeNum + '.json is malformed. Processing next item...'; $timeout(service.processPlaylist, ERR_MSG_TIME); return; } switch (current.type) { case 'visualizer_image': try { src = path + mediaFilesExt + data.data['field_viz_image'].und[0].uri.replace('public://', ''); dest = 'cache/images/' + data.data['field_viz_image'].und[0].filename; current.duration = data.data['field_duration'].und[0].value ? data.data['field_duration'].und[0].value : 5; } catch(err) { $log.error("Error: JSON for node " + nodeNum + " is malformed. Processing next item... "); $rootScope.loadingMsg = 'The JSON file at ' + path + mediaExt + nodeNum + '.json is malformed. Processing next item...'; $timeout(service.processPlaylist, ERR_MSG_TIME); return; } current.src = dest; cacheService.getFileAndPipe(src, dest) .then( function(success) { $log.info(success); service.playlist.push(current); service.processPlaylist(); }, function(error) { $log.error(error); current.supported = false; $rootScope.loadingMsg = 'Image file at ' + src + ' could not be found.' +' Make sure the file is uploaded and included in the playlist properly. Processing next item...'; $timeout(service.processPlaylist, ERR_MSG_TIME); }); break; case 'visualizer_video': try { src = path + mediaFilesExt + data.data['field_video'].und[0].uri.replace('public://', ''); dest = 'cache/videos/' + data.data['field_video'].und[0].filename; filetype = data.data['field_video'].und[0].filemime; } catch(err) { $log.error("Error: JSON for node " + nodeNum + " is malformed. Processing next item. "); $rootScope.loadingMsg = 'The JSON file at ' + path + mediaExt + nodeNum + '.json is malformed. Processing next item...'; $timeout(service.processPlaylist, ERR_MSG_TIME); return; } if (filetype == 'video/mp4') { $rootScope.loadingMsg = 'The video ' + data.data['field_video'].und[0].filename + ' is an mp4 file and is not supported. Processing next item...'; $log.error($rootScope.loadingMsg); $timeout(service.processPlaylist, ERR_MSG_TIME); return; } current.src = dest; cacheService.getFileAndPipe(src, dest) .then( function(success) { $log.info(success); service.playlist.push(current); service.processPlaylist(); }, function(error) { $log.error(error); current.supported = false; $rootScope.loadingMsg = 'Video file at ' + src + ' could not be found. Make sure the file is uploaded and included in the playlist properly.'; $timeout(service.processPlaylist, ERR_MSG_TIME); }); break; case 'visualizer_js': try { src = path + mediaFilesExt + data.data['field_js_file'].und[0].uri.replace('public://', ''); filetype = data.data['field_js_file'].und[0].filemime; filename = data.data['field_js_file'].und[0].filename; } catch(err) { $log.error("Error: JSON for node " + nodeNum + " is malformed. Processing next item. "); $rootScope.loadingMsg = 'The JSON file at ' + path + mediaExt + nodeNum + '.json is malformed. Processing next item.'; $timeout(service.processPlaylist, ERR_MSG_TIME); return; } if (typeof filename !== 'string') { $log.error("Error: JSON for node " + nodeNum + " is malformed. Processing next item. "); $rootScope.loadingMsg = 'The JSON file at ' + path + mediaExt + nodeNum + '.json is malformed. Processing next item.'; $timeout(service.processPlaylist, ERR_MSG_TIME); return; } if (filetype == 'application/x-tar'){ current.type = 'visualizer_pkg'; dest = 'cache/viz'; current.src = dest + '/' + filename.replace('.tar', '') + '/index.html'; cacheService.extractTarAndPipe(src, dest) .then( function(success) { $log.info(success); service.playlist.push(current); service.processPlaylist(); }, function(error) { $log.error(error); current.supported = false; if (error == 'GET_ERROR') { $rootScope.loadingMsg = 'Visualizer file at ' + src + ' could not be found. Make sure the file is uploaded and included in the playlist properly.'; } else { $rootScope.loadingMsg = 'Error extracting file ' + src + '.'; } $timeout(service.processPlaylist, ERR_MSG_TIME); }); } else if (filetype == 'application/x-gtar'){ current.type = 'visualizer_pkg'; dest = 'cache/viz'; current.src = dest + '/' + filename.replace('.tgz', '') + '/index.html'; cacheService.gunzipAndExtract(src, dest) .then( function(success) { $log.info(success); service.playlist.push(current); service.processPlaylist(); }, function(error) { $log.error(error); current.supported = false; if (error == 'GET_ERROR') { $rootScope.loadingMsg = 'Visualizer file at ' + src + ' could not be found. Make sure the file is uploaded and included in the playlist properly.'; } else { $rootScope.loadingMsg = 'Error extracting file ' + src + '.'; } $timeout(service.processPlaylist, ERR_MSG_TIME); }); } else { $log.error("Error: Filetype " + filetype + " for node " + nodeNum + " is not supported. Processing next item..."); $rootScope.loadingMsg = 'Unsupported filetype ' + filetype + ' detected. Processing next item...'; $timeout(service.processPlaylist, ERR_MSG_TIME); return; } break; default: current.supported = false; $log.error("Unsupported type (" + current.type + ") detected in playlist."); $rootScope.loadingMsg = "Unsupported type (" + current.type + ") detected in playlist." + " Processing next item..."; $timeout(service.processPlaylist, ERR_MSG_TIME); break; } }, function() { $rootScope.loadingMsg = "Error getting media at " + path + mediaExt + nodeNum + '.json.' + ' Processing next item.'; $log.error('Error getting media information from: ' + path + mediaExt + nodeNum + '.json.' + '\nProcessing next media item.'); $timeout(service.processPlaylist, ERR_MSG_TIME); }) }; service.getLength = function () { return service.playlist.length; }; service.getIndex = function () { return _index; }; service.getCurrent = function () { return service.playlist[_index]; }; service.next = function () { _index++; if (_index === service.playlist.length) { _index = 0; $rootScope.$broadcast('WRAP_PLAYLIST'); } return _index; }; service.sequence = function () { var nextItem = service.getCurrent(); if(_stop) { $log.info("Playlist stopped"); return; } $log.info("Getting ready to play: " + nextItem.src); switch (nextItem.type) { case 'visualizer_image': $timeout(function () { $location.path('image/' + _index) }); break; case 'visualizer_video': $timeout(function () { $location.path('video/' + _index) }); break; case 'visualizer_js': $timeout(function () { $location.path('viz/' + _index) }); break; case 'visualizer_pkg': $timeout(function () { $location.path('eviz/' + _index) }); break; default: //This shouldn't crash in production throw new Error("Malformed JSON. Unrecognized type: " + nextItem.type); } }; service.completed = function () { service.next(); service.sequence(); }; service.stop = function() { _stop = true; }; service.resume = function() { _stop = false; }; return service; }); <file_sep>app.controller("loadViewController", function ($scope, $log, $window) { $scope.restart = function() { $window.location.reload(); }; }); <file_sep># nwviz NW.js visualizer ## To get it up and running - Put in Activ8or credentials in **config.json**: ```json "a8uname": "username", "a8pwd": "<PASSWORD>" ``` - Put in CMS credentials in **config.json**: ```json "cmsuname": "username", "cmspwd": "<PASSWORD>" ``` - Put default CMS address, venue ID, and Activ8or IP in **config.json**: ```json "defaultCmsAddr": "https://commtix.appdelegates.net/ct/", "defaultVenueId": "0", "defaultA8Ip": "127.0.0.1" ``` - To run the app from the terminal, type in the path to the nwjs executable and then the path to the nwviz app: ``` /Applications/nwjs.app/Contents/MacOS/nwjs /path/to/nwviz ``` - To distribute on a Mac as a single executable, run `zip -r ../app.nw *` to create your **app.nw** right outside the project directory, and then replace the **app.nw** in your NWJS application (located at `/path/to/nwjs.app/Contents/Resources/app.nw`) with your **app.nw**. - To change the app's icon, modify `nwjs.app/Contents/Resources/nw.icns`. - To add information about the app, modify `nwjs.app/Contents/Info.plist`. ## Additional notes - Press ESC at any point to view and change the A8 IP address, the CMS address, and the venue ID. - For JS visualizers to work properly: - They must have an index.html file in their root directory. - If they login to Activ8or to get data, they must first use the UserDefaultsService to get "a8Ip", put the address in NW-compatible format, and set Activ8or's site origin: ```javascript var a8Ip = userDefaults.getStringForKey("a8Ip", "127.0.0.1"); var a8Origin = 'http://' + a8Ip + ':1337'; actv8API.setSiteOrigin(a8Origin); ``` - JS visualizers should additionally have an info.json file in their root directory with a duration (in sec) for how long to display the visualizer. The app will default to displaying a visualizer for 30 seconds. - The streaming unzip process is weird and not very reliable, so .tgz compressed files for the JS visualizers should be used instead. - NW.js does not support mp4 files, so convert videos to VP8 to use with this app (.webm, .mkv, .mov). ## Issues - Right now, the JS visualizers are displayed for a certain amount of time (specified in their info.json file). For some visualizers, it might make more sense to have them display based on some other metric. To do this, there must be some sort of communication between the embedded viz and the app so the app can listen for when the viz signals it is done. - Playlists on Commtix do not have a unique identifier, so choosing a playlist with the given venue ID is not working how it probably should be. - When the JS visualizers don't work (a8 login is wrong, a8 site origin is wrong, lost internet connection, etc.) they don't show anything. I think this is something that has to be handled in the JS visualizers and not the app, though. <file_sep>/** * * Functionality that is shared across entire app should be in here or a service. * * New > 1.2 Version * */ app.controller("rootController", function ($scope, $log, playlistService, $timeout, $location) { $scope.$on("PLAYLIST_LOADED", function () { $log.info("Playlist loaded"); playlistService.sequence(); }); $scope.onKeyDown = function($event) { var keyCode = window.event ? $event.keyCode : $event.which; // if ESC key is pressed if (keyCode === 27) { playlistService.stop(); $timeout(function () { $location.path('config') }); } } }); <file_sep>app.controller("configViewController", function ($rootScope, $scope, $log, $timeout, $window, userDefaults) { $scope.vizSettings = { a8Ip: undefined, cmsAddr: undefined, venueId: undefined }; $scope.vizSettings.a8Ip = userDefaults.getStringForKey("a8Ip", $rootScope.configs.defaultA8Ip); $scope.vizSettings.cmsAddr = userDefaults.getStringForKey("cmsAddr", $rootScope.configs.defaultCmsAddr); $scope.vizSettings.venueId = userDefaults.getStringForKey("venueId", $rootScope.configs.defaultVenueId); $scope.venueIdRegex = /^\d+$/; $scope.ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; $scope.ready = true; $scope.$watch("vizSettings.a8Ip", function(nval) { if (!nval) return; userDefaults.setStringForKey("a8Ip", nval); }); $scope.$watch("vizSettings.cmsAddr", function(nval) { if (!nval) return; nval += nval.slice(-1) == '/' ? "" : "/"; userDefaults.setStringForKey("cmsAddr", nval); }); $scope.$watch("vizSettings.venueId", function(nval) { if (!nval) return; userDefaults.setStringForKey("venueId", nval); }); $scope.onApply = function() { $window.location.reload(); }; $scope.onReset = function() { $scope.vizSettings.a8Ip = $rootScope.configs.defaultA8Ip; $scope.vizSettings.cmsAddr = $rootScope.configs.defaultCmsAddr; $scope.vizSettings.venueId = $rootScope.configs.defaultVenueId; }; }); <file_sep>app.directive('fallbackSrc', function($timeout, $location) { return { link: function(scope, element, attrs) { var defaultSrc = attrs.fallbackSrc ? attrs.fallbackSrc : "assets/img/default.jpg"; element.on('error', function() { element.off('error'); console.log('ERROR loading primary source'); element[0].src = defaultSrc; if (element[0].localName == 'video') { scope.currentItem.src = defaultSrc; scope.currentItem.duration = 3; $timeout(function () { $location.path('image/9999') }); } }); } }; });
750210567f3a74ae1f980abf823116a84a450750
[ "JavaScript", "Markdown" ]
11
JavaScript
torresalyssa/nwviz
0a7966c09b854c21a7e7691aca7298041fa35cc9
a54165818419932d4fdae83d688825f38551eda4
refs/heads/master
<file_sep># **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: dpromoha <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2019/06/27 14:35:46 by dpromoha #+# #+# # # Updated: 2019/06/27 14:35:49 by dpromoha ### ########.fr # # # # **************************************************************************** # NAME = dpromoha.filler FLAGS = -Wall -Werror -Wextra -I./includes -I./libft/includes SRCDIR = ./sources/ OBJDIR = ./objects/ LIBDIR = ./libft/ SRC = what_is_map.c filler.c help_to_count.c look_for.c \ free.c execute_algorithm.c where_to_attack.c around.c piece_overlay.c \ additional_func.c \ OBJ = $(addprefix $(OBJDIR), $(SRC:.c=.o)) LIB = libftprintf.a all: $(NAME) $(NAME): $(OBJDIR) $(OBJ) $(LIBDIR)$(LIB) @cp $(LIBDIR)$(LIB) ./ @echo "made the best player $(NAME)" @gcc -o $(NAME) $(OBJ) $(LIB) $(FLAGS) $(OBJ): $(OBJDIR)%.o : $(SRCDIR)%.c @gcc -o $@ -c $< $(FLAGS) $(LIBDIR)$(LIB): @make -C $(LIBDIR) $(OBJDIR): @mkdir $(OBJDIR) clean: @make -C $(LIBDIR) clean @rm -rf $(OBJ) $(OBJDIR) fclean: @make -C $(LIBDIR) fclean @rm -rf $(OBJ) $(OBJDIR) @rm -rf $(NAME) $(LIB) re: fclean $(NAME) magic: @echo "creating magic" gcc -Wall -Wextra -Werror ./to_see/take_maps.c ./to_see/magic_result.c ./to_see/magic.c ./libft/libftprintf.a -lncurses -o ./to_see/magic <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* filler.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:35:22 by dpromoha #+# #+# */ /* Updated: 2019/07/03 09:13:43 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FILLER_H # define FILLER_H # include "../libft/includes/libft.h" # include "../libft/includes/ft_printf.h" # include "structure.h" t_form *create_piece(char *line_sizes); t_form *more_mem_map(char *line); void help_filler(t_form **piece, t_compens **offsets, char **line); void find_space(int **c_form, int height, int width, char for_hero); t_form *mem_for_new(char *line_sizes); int h(char *line); int w(char *line); void create_map(t_form *board, char for_enemy); t_compens *atack(t_form *rect_struct); void mem_for_piece(t_form *piece, t_compens *offsets); void coordinates(t_form *piece, t_compens *o, t_form *brd, t_player *p); void print_c(int *winning_coordinates, t_compens **o); int coincidance(t_form *piece, t_form *board, int *c, t_player *p); void check_around(int **tab, int height, int width, int for_enemy); int algorithm(int **tab, int height, int width, int current); int piece_found(t_form *piece, t_form *board, int *coords, t_player *players); void free_launcher(t_form *board, t_form *piece, t_compens *offsets); void double_free(char **two_d); void check_read(char **line, t_form **brd, t_player **p); void hero(t_player **players); #endif <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* magic.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/29 12:39:27 by dpromoha #+# #+# */ /* Updated: 2019/07/03 09:03:24 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "magic.h" static void who_it_is(WINDOW *map_w, int i, int j, char c) { short color_pair; color_pair = 0; init_pair(1, COLOR_BLACK, COLOR_CYAN); init_pair(2, COLOR_BLACK, COLOR_WHITE); init_pair(3, COLOR_BLACK, COLOR_BLACK); if (c == 'O' || c == 'o') color_pair = 2; else if (c == 'X' || c == 'x') color_pair = 1; else if (c == '.') color_pair = 3; wattron(map_w, COLOR_PAIR(color_pair)); mvwprintw(map_w, i, j * 2 - 3, " ", c); wattroff(map_w, COLOR_PAIR(color_pair)); } static void frame(t_square *show_map, WINDOW **map_w, WINDOW **result) { t_square a; a.y = 0; a.x = 0; a.y = show_map->y; a.x = show_map->x; *map_w = newwin(a.y + (2 * 2), a.x * 2 + 3 + (4 * 2), 5, 0); *result = newwin(10, 18, 10, a.x * 3 + 3 + (4 * 3)); box(*result, 0, 0); wrefresh(*map_w); box(*map_w, 0, 0); } static void draw(WINDOW *map_w, char **game_arr, t_square *show_map) { t_count a; a.i = 2; while (a.i < show_map->y + 2) { a.j = 4; while (a.j < show_map->x + 4) { who_it_is(map_w, a.i, a.j, game_arr[a.i][a.j]); a.j++; } a.i++; } } void print_game(char **game_arr, t_square *show_map) { int i; WINDOW *map_w; WINDOW *result; i = 0; initscr(); curs_set(0); start_color(); frame(show_map, &map_w, &result); while (game_arr[i]) { while (game_arr[i] != NULL && !ft_strstr(game_arr[i], "Plateau") && !ft_strstr(game_arr[i], "== O fin")) i++; if (print_result(&result, game_arr + i) == 1) break ; draw(map_w, game_arr + i, show_map); usleep(10000); wrefresh(map_w); i++; } getch(); endwin(); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* structure.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:35:30 by dpromoha #+# #+# */ /* Updated: 2019/06/27 14:35:32 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef STRUCTURE_H # define STRUCTURE_H # include "../libft/includes/libft.h" # include "../libft/includes/ft_printf.h" # include "filler.h" typedef struct s_compens { int first; int second; int third; int fourth; } t_compens; typedef struct s_form { int **form; int **c_form; int **shape; int height; int width; int h; int w; } t_form; typedef struct s_player { int what_is_player; int for_hero; int enemy; int for_enemy; } t_player; typedef struct s_count { int i; int j; int coordinates[2]; int coordinates_copy[2]; int winning_coordinates[2]; int smallest_sum; int dimensions[2]; int sum; int i_cr; int j_cr; } t_count; #endif <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* filler.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:36:54 by dpromoha #+# #+# */ /* Updated: 2019/07/03 08:09:04 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" static void what_sign(t_form *rect, char cell, int i, int j) { rect->form[i][j] = cell; rect->c_form[i][j] = cell; if (cell == 'x' || cell == 'o') { rect->form[i][j] = rect->form[i][j] - 32; rect->c_form[i][j] = rect->c_form[i][j] - 32; } } t_form *mem_for_new(char *line_sizes) { t_count a; int k; char *line; t_form *rect_struct; a.i = 0; a.j = 0; k = 4; rect_struct = more_mem_map(line_sizes); gnl(0, &line); line != NULL ? free(line) : 0; while (a.i < rect_struct->height) { gnl(0, &line); while (a.j < rect_struct->width) what_sign(rect_struct, line[k++], a.i, a.j++); if (line) free(line); rect_struct->form[a.i][a.j] = 0; rect_struct->c_form[a.i][a.j] = 0; a.j = 0; k = 4; a.i++; } return (rect_struct); } void find_space(int **c_form, int height, int width, char for_hero) { t_count a; a.i = 0; a.j = 0; while (a.i < height) { a.j = 0; while (a.j < width) { if (c_form[a.i][a.j] == for_hero) c_form[a.i][a.j] = '.'; a.j++; } a.i++; } } static t_player *hero_or_not(void) { char *line; char **line_items; t_player *players; gnl(0, &line); if (!line[0]) return (NULL); players = (t_player*)malloc(sizeof(t_player)); line_items = ft_strsplit(line, ' '); if (ft_strncmp("p1", line_items[2], 2) == 0) { players->what_is_player = 1; players->for_hero = 'O'; players->enemy = 2; players->for_enemy = 'X'; } else if (ft_strncmp("p2", line_items[2], 2) == 0) hero(&players); double_free(line_items); free(line); return (players); } int main(void) { t_form *brd; t_form *piece; t_player *p; t_compens *offsets; char *line; if (!(p = hero_or_not())) return (0); while (gnl(0, &line) > 0) { if (line != NULL) { check_read(&line, &brd, &p); if (ft_strncmp(line, "Piece", 5) == 0) { help_filler(&piece, &offsets, &line); coordinates(piece, offsets, brd, p); free_launcher(brd, piece, offsets); } ft_strdel(&line); } } return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* execute_algorithm.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/29 12:45:34 by dpromoha #+# #+# */ /* Updated: 2019/06/29 12:45:35 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" static int one_side(int **tab, int *coords, int *dimensions, int current) { t_count a; int height; int width; a.i = coords[0]; a.j = coords[1]; height = dimensions[0]; width = dimensions[1]; if (a.i < (height - 1) && tab[a.i + 1][a.j] == '.' && tab[a.i][a.j] != current) tab[a.i + 1][a.j] = current; if (a.i > 0 && tab[a.i - 1][a.j] == '.' && tab[a.i][a.j] != current) tab[a.i - 1][a.j] = current; if (a.j < (width - 1) && tab[a.i][a.j + 1] == '.' && tab[a.i][a.j] != current) tab[a.i][a.j + 1] = current; if (a.j > 0 && tab[a.i][a.j - 1] == '.' && tab[a.i][a.j] != current) tab[a.i][a.j - 1] = current; if ((a.i < (height - 1) && tab[a.i + 1][a.j] == current) || (a.i > 0 && tab[a.i - 1][a.j] == current) || (a.j < (width - 1) && tab[a.i][a.j + 1] == current) || (a.j > 0 && tab[a.i][a.j - 1] == current)) return (1); else return (0); } static int helpful(int ***tab, t_count a, int height, int c) { if ((a.i < (height - 1) && (*tab)[a.i + 1][a.j + 1] == c) || (a.i < (height - 1) && (*tab)[a.i + 1][a.j - 1] == c) || (a.i > 0 && (*tab)[a.i - 1][a.j + 1] == c) || (a.i > 0 && (*tab)[a.i - 1][a.j - 1] == c)) return (1); else return (1); } static int another_side(int **tab, int *coordinates, int *dimensions, int c) { t_count a; int height; int width; a.i = coordinates[0]; a.j = coordinates[1]; height = dimensions[0]; width = dimensions[1]; if (a.i < (height - 1) && a.j < (width - 1) && tab[a.i + 1][a.j + 1] == '.' && tab[a.i][a.j] != c) tab[a.i + 1][a.j + 1] = c; if (a.i < (height - 1) && a.j > 0 && tab[a.i + 1][a.j - 1] == '.' && tab[a.i][a.j] != c) tab[a.i + 1][a.j - 1] = c; if (a.i > 0 && a.j < (width - 1) && tab[a.i - 1][a.j + 1] == '.' && tab[a.i][a.j] != c) tab[a.i - 1][a.j + 1] = c; if (a.i > 0 && a.j > 0 && tab[a.i - 1][a.j - 1] == '.' && tab[a.i][a.j] != c) tab[a.i - 1][a.j - 1] = c; if (helpful(&tab, a, height, c) == 1) return (1); return (0); } static void in(t_count *a) { a->i = 0; a->j = 0; a->sum = 0; } int algorithm(int **tab, int height, int width, int current) { t_count a; in(&a); while (a.i < height) { a.j = 0; while (a.j++ < width) { if (tab[a.i][a.j] >= 100) { a.coordinates[0] = a.i; a.coordinates[1] = a.j; a.dimensions[0] = height; a.dimensions[1] = width; if (one_side(tab, a.coordinates, a.dimensions, current) != 0 && another_side(tab, a.coordinates, a.dimensions, current) != 0) a.sum = 1; } } a.i++; } if (a.sum == 1) return (1); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* take_maps.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/29 12:41:29 by dpromoha #+# #+# */ /* Updated: 2019/07/03 09:12:04 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "magic.h" static void help_j_free(char **s1, char *s2) { char *copy; if (!*s1 || !s1) return ; else copy = *s1; *s1 = ft_strjoin(*s1, s2); ft_strdel(&copy); } static char *from_term(void) { char *input; char *what_is; char *after; what_is = NULL; input = NULL; while (gnl(0, &input) > 0) { if (what_is == NULL) what_is = ft_strdup(input); else help_j_free(&what_is, input); after = ft_strdup("\n"); help_j_free(&what_is, after); ft_strdel(&after); if (ft_strstr(input, "== X fin:")) break ; else ft_strdel(&input); } ft_strdel(&input); return (what_is); } static void size_of_game(t_square **show_map, char *size_str) { int i; i = 0; if (!((*show_map) = (t_square*)malloc(sizeof(t_square)))) return ; else { while (!ft_isdigit(size_str[i])) i++; (*show_map)->y = ft_atoi(size_str + i); while (ft_isdigit(size_str[i])) i++; (*show_map)->x = ft_atoi(size_str + i); (*show_map)->arr = NULL; } } static void start(void) { initscr(); refresh(); curs_set(0); printw("###### ###### #### ## ## ###### ###\n"); printw("## ## ## ## ## ## ###\n"); printw("#### ## ## ### ###### ## ###\n"); printw("## ## ## ## ## ## ## \n"); printw("## ###### #### ## ## ## ###\n"); getch(); refresh(); endwin(); } int main(void) { char **game_arr; char *game_str; t_square *show_map; int i; i = 0; game_str = from_term(); game_arr = ft_strsplit(game_str, '\n'); ft_strdel(&game_str); start(); while (game_arr[i] != NULL && !ft_strstr(game_arr[i], "Plateau") && !ft_strstr(game_arr[i], "== O fin")) i++; size_of_game(&show_map, game_arr[i]); print_game(game_arr + i, show_map); free(show_map); twice_free(&game_arr); ft_printf("%s", "\xF0\x9F\x94\xA5"); ft_printf("%s", "\xF0\x9F\x94\xA5"); ft_printf(" GAME OVER "); ft_printf("%s", "\xF0\x9F\x94\xA5"); ft_printf("%s\n", "\xF0\x9F\x94\xA5"); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* look_for.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:37:28 by dpromoha #+# #+# */ /* Updated: 2019/07/03 08:58:11 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" void mem_for_piece(t_form *piece, t_compens *offsets) { int i; int height; int width; i = 0; height = piece->height - offsets->second - offsets->fourth + 1; width = piece->width - offsets->first - offsets->third + 1; piece->shape = (int**)malloc(sizeof(int*) * height); while (i < height - 1) piece->shape[i++] = (int*)malloc(sizeof(int) * width); piece->shape[i] = NULL; piece->h = height - 1; piece->w = width - 1; } static void transfer_array(int *dst, int *src) { dst[0] = src[0]; dst[1] = src[1]; } static int all_coord(t_form *piece, t_form *board, int *coordinates) { t_count a; a.i = coordinates[0]; a.j = coordinates[1]; a.i_cr = a.i + piece->h; a.j_cr = a.j + piece->w; a.sum = 0; while (a.i < a.i_cr) { while (a.j < a.j_cr) a.sum += board->c_form[a.i][a.j++]; a.j = coordinates[1]; a.i++; } return (a.sum); } void help_coord(t_count *a, t_form *piece, t_form *brd) { a->smallest_sum = all_coord(piece, brd, a->coordinates_copy); transfer_array(a->winning_coordinates, a->coordinates_copy); } void coordinates(t_form *piece, t_compens *o, t_form *brd, t_player *p) { t_count a; a.coordinates[0] = 0; a.coordinates[1] = 0; a.winning_coordinates[0] = -100; a.winning_coordinates[1] = -100; a.smallest_sum = 999999999; while (a.coordinates[0] < brd->height - piece->h + 1) { while (a.coordinates[1] < brd->width - piece->w + 1) { transfer_array(a.coordinates_copy, a.coordinates); if (piece_found(piece, brd, a.coordinates, p) && coincidance(piece, brd, a.coordinates, p) && all_coord(piece, brd, a.coordinates_copy) < a.smallest_sum) help_coord(&a, piece, brd); transfer_array(a.coordinates, a.coordinates_copy); a.coordinates[1]++; } a.coordinates[1] = 0; a.coordinates[0]++; } print_c(a.winning_coordinates, &o); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* free.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/29 12:54:24 by dpromoha #+# #+# */ /* Updated: 2019/06/29 12:54:25 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" void double_free(char **two_d) { int i; i = 0; while (two_d[i] != NULL) free(two_d[i++]); if (two_d != NULL) free(two_d); } static void double_free_int(int **two_d) { int i; i = 0; while (two_d[i] != NULL) free(two_d[i++]); if (two_d != NULL) free(two_d); } static void map_free(t_form *board) { double_free_int(board->form); double_free_int(board->c_form); free(board); } static void random_free(t_form *piece) { double_free_int(piece->form); double_free_int(piece->c_form); double_free_int(piece->shape); free(piece); } void free_launcher(t_form *board, t_form *piece, t_compens *offsets) { map_free(board); random_free(piece); free(offsets); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* what_is_map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:38:01 by dpromoha #+# #+# */ /* Updated: 2019/06/27 14:38:02 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" int h(char *line) { int height; char **buffer; buffer = ft_strsplit(line, ' '); height = ft_atoi(buffer[1]); double_free(buffer); return (height); } int w(char *line) { int width; char **buffer; buffer = ft_strsplit(line, ' '); width = ft_atoi(buffer[2]); double_free(buffer); return (width); } t_form *create_piece(char *line_sizes) { t_count a; int k; char *line; t_form *rect_struct; a.i = 0; a.j = 0; k = 0; rect_struct = more_mem_map(line_sizes); while (a.i < rect_struct->height) { if (gnl(0, &line) > 0) { while (a.j < rect_struct->width) rect_struct->form[a.i][a.j++] = line[k++]; rect_struct->form[a.i][a.j] = 0; k = 0; a.j = 0; a.i++; free(line); } } rect_struct->shape = NULL; return (rect_struct); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* piece_overlay.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:37:40 by dpromoha #+# #+# */ /* Updated: 2019/06/27 14:37:41 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" static void initial(int *i, int *j, int *coordinates) { (*i)++; *j = 0; coordinates[0]++; storage(&coordinates[1]); } static void help_to_coi(t_count *a, int *c, t_form *piece, int *above) { a->i_cr = c[0] + piece->h; a->j_cr = c[1] + piece->w; a->i = 0; a->j = 0; *above = 0; storage(&c[1]); } int coincidance(t_form *piece, t_form *board, int *c, t_player *p) { t_count a; int above; storage(NULL); help_to_coi(&a, c, piece, &above); while (c[0] < a.i_cr) { while (c[1] < a.j_cr) { if (board->form[c[0]][c[1]] == p->for_hero && piece->shape[a.i][a.j] == '*') above++; else if (board->form[c[0]][c[1]] == p->for_enemy && piece->shape[a.i][a.j] == '*') return (0); a.j++; c[1]++; } initial(&a.i, &a.j, c); } if (above == 1) return (1); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* magic_result.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/29 12:39:35 by dpromoha #+# #+# */ /* Updated: 2019/07/03 09:06:52 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "magic.h" static void print_in_box(WINDOW ***result, int o, int x) { init_pair(4, COLOR_BLACK, COLOR_RED); wattron(**result, COLOR_PAIR(4)); mvwprintw(**result, 2, 14 / 2 - 2, " WINNER?"); wattron(**result, COLOR_PAIR(2) | A_STANDOUT | A_BOLD); mvwprintw(**result, 4, 5, "O took %d", o); wattroff(**result, COLOR_PAIR(2)); wattron(**result, COLOR_PAIR(1) | A_STANDOUT | A_BOLD); mvwprintw(**result, 6, 5, "X took %d", x); wattroff(**result, COLOR_PAIR(1)); } int print_result(WINDOW **result, char **game_arr) { int o; int x; if (ft_strstr(game_arr[0], "== O fin") != 0) { o = ft_atoi(game_arr[0] + 10); x = ft_atoi(game_arr[1] + 10); init_pair(1, COLOR_BLACK, 6); init_pair(2, COLOR_BLACK, 7); print_in_box(&result, o, x); wrefresh(*result); usleep(3000000); return (1); } return (0); } <file_sep># filler The main principle is: two players take on each other on a board, and take turns placing the piece that the master of the game gives them, earning points. The game stops as soon as a piece can no longer be placed. **HOW TO USE:** make ./resources/filler_vm -f resources/maps/map01 -p1 ./dpromoha.filler -p2 resources/players/grati.filler ![ezgif com-video-to-gif (1)](https://user-images.githubusercontent.com/46355522/68535373-3206ef80-034a-11ea-9469-2b7cbdaaf000.gif) **VISUALIZATION:** make magic ./resources/filler_vm -f resources/maps/map01 -p1 ./dpromoha.filler -p2 resources/players/grati.filler | to_see/magic ![ezgif com-video-to-gif (2)](https://user-images.githubusercontent.com/46355522/68535520-4b10a000-034c-11ea-9e6e-ea7e807965f1.gif) <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* where_to_attack.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:38:09 by dpromoha #+# #+# */ /* Updated: 2019/06/27 14:38:10 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" static int first_side(t_form *map_form) { t_count a; a.i = 0; a.j = 0; while (a.j < map_form->width) { while (a.i < map_form->height && map_form->form[a.i][a.j] == '.') a.i++; if (map_form->form[a.i] == '\0') { a.j++; a.i = 0; } else break ; } return (a.j); } static int second_side(t_form *map_form) { t_count a; a.i = 0; a.j = 0; while (map_form->form[a.i] != '\0') { while (a.j < map_form->width && map_form->form[a.i][a.j] == '.') a.j++; if (map_form->form[a.i][a.j] == '\0') { a.i++; a.j = 0; } else break ; } return (a.i); } static int third_side(t_form *map_form) { t_count a; int result; a.i = 0; a.j = map_form->width - 1; while (a.j >= 0) { while (a.i < map_form->height && map_form->form[a.i][a.j] == '.') a.i++; if (map_form->form[a.i] == '\0') { a.j--; a.i = 0; } else break ; } result = map_form->width - a.j - 1; return (result); } static int fourth_side(t_form *map_form) { t_count a; a.i = map_form->height - 1; a.j = 0; while (a.i >= 0) { while (map_form->form[a.i][a.j] == '.') a.j++; if (map_form->form[a.i][a.j] == '\0') { a.i--; a.j = 0; } else break ; } return (map_form->height - a.i - 1); } t_compens *atack(t_form *map_form) { t_compens *offsets; offsets = (t_compens*)malloc(sizeof(t_compens)); offsets->first = first_side(map_form); offsets->second = second_side(map_form); offsets->third = third_side(map_form); offsets->fourth = fourth_side(map_form); return (offsets); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* around.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:36:37 by dpromoha #+# #+# */ /* Updated: 2019/07/03 08:48:39 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" static void one_side(int **tab, int *coordinates, int height, int width) { t_count a; a.i = coordinates[0]; a.j = coordinates[1]; if (a.i < (height - 1) && tab[a.i + 1][a.j] == '.') tab[a.i + 1][a.j] = 100; if (a.i > 0 && tab[a.i - 1][a.j] == '.') tab[a.i - 1][a.j] = 100; if (a.j < (width - 1) && tab[a.i][a.j + 1] == '.') tab[a.i][a.j + 1] = 100; if (a.j > 0 && tab[a.i][a.j - 1] == '.') tab[a.i][a.j - 1] = 100; } static void around(int height, int width, int *coordinates, int ***tab) { t_count a; one_side((*tab), coordinates, height, width); a.i = coordinates[0]; a.j = coordinates[1]; if (a.i < (height - 1) && a.j < (width - 1) && (*tab)[a.i + 1][a.j + 1] == '.') (*tab)[a.i + 1][a.j + 1] = 100; if (a.i < (height - 1) && a.j > 0 && (*tab)[a.i + 1][a.j - 1] == '.') (*tab)[a.i + 1][a.j - 1] = 100; if (a.i > 0 && a.j < (width - 1) && (*tab)[a.i - 1][a.j + 1] == '.') (*tab)[a.i - 1][a.j + 1] = 100; if (a.i > 0 && a.j > 0 && (*tab)[a.i - 1][a.j - 1] == '.') (*tab)[a.i - 1][a.j - 1] = 100; } void check_around(int **tab, int height, int width, int for_enemy) { t_count a; int coordinates[2]; a.i = 0; while (a.i < height) { a.j = 0; while (a.j < width) { if (tab[a.i][a.j] == for_enemy) { coordinates[0] = a.i; coordinates[1] = a.j; around(height, width, coordinates, &tab); } a.j++; } a.i++; } } void check_read(char **line, t_form **brd, t_player **p) { if (ft_strncmp((*line), "Plateau", 7) == 0) { (*brd) = mem_for_new(*line); find_space((*brd)->c_form, (*brd)->height, (*brd)->width, (*p)->for_hero); create_map((*brd), (*p)->for_enemy); } } void hero(t_player **players) { (*players)->what_is_player = 2; (*players)->for_hero = 'X'; (*players)->enemy = 1; (*players)->for_enemy = 'O'; } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dariadasha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/25 10:53:18 by dpromoha #+# #+# */ /* Updated: 2019/01/26 22:17:16 by dariadasha ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" void ft_check_emp(t_listok **add, int fd, t_listok **lst) { t_listok *copy; if ((*add) == NULL) { copy = (t_listok*)malloc(sizeof(t_listok)); copy->content = ft_strdup(""); copy->fd = fd; copy->next = NULL; if ((*lst) != NULL) { copy->next = (*lst); (*lst) = copy; } else (*lst) = copy; (*add) = copy; } } char *ft_read(t_listok *add, int fd) { char buf[BUFF_SIZE + 1]; int ret; char *copy; while ((ret = read(fd, buf, BUFF_SIZE)) > 0) { buf[ret] = '\0'; copy = add->content; add->content = ft_strjoin(add->content, buf); free(copy); if (ft_strchr(add->content, '\n')) break ; copy = NULL; } if (ret == 0) return (0); return (add->content); } int ft_line_size(char *length) { int i; i = 0; if (!length[i]) return (-1); while (length[i] && length[i] != '\n') i++; return (i); } void ft_check_spaces(int length, t_listok **add) { char *copy; if (length == 0) { copy = (*add)->content; if (ft_strchr((*add)->content, '\n') == 0) (*add)->content = ft_strdup(""); else (*add)->content = ft_strdup(ft_strchr((*add)->content, '\n') + 1); free(copy); copy = NULL; } } int get_next_line(const int fd, char **line) { char buf[BUFF_SIZE + 1]; static t_listok *lst = NULL; t_listok *add; int length; if (BUFF_SIZE < 1 || fd < 0 || read(fd, buf, 0) < 0 || line == NULL) return (-1); add = lst; while (add && add->fd != fd) add = add->next; ft_check_emp(&add, fd, &lst); ft_read(add, fd); length = ft_strlen(add->content) == 0 ? 1 : 0; if (length == 1) return (0); *line = ft_strsub(add->content, 0, ft_line_size(add->content)); ft_check_spaces(length, &add); return (1); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstnew.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/23 15:21:14 by dpromoha #+# #+# */ /* Updated: 2018/12/26 15:56:41 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" t_list *ft_lstnew(void const *content, size_t content_size) { t_list *listok; if (!(listok = (t_list*)malloc(sizeof(*listok)))) return (NULL); if (!content) { listok->content = NULL; listok->content_size = 0; } else { if (!(listok->content = malloc(content_size))) return (NULL); ft_memcpy(listok->content, content, content_size); listok->content_size = content_size; } listok->next = NULL; return (listok); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* help_to_count.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:37:17 by dpromoha #+# #+# */ /* Updated: 2019/06/27 14:37:18 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" int piece_found(t_form *piece, t_form *board, int *coords, t_player *p) { t_count a; a.i_cr = 0; a.j_cr = 0; a.i = coords[0]; a.j = coords[1]; a.i_cr = coords[0] + piece->h; a.j_cr = coords[1] + piece->w; while (a.i < a.i_cr) { while (a.j < a.j_cr) { if (board->form[a.i][a.j] == p->for_hero) return (1); a.j++; } a.j = coords[1]; a.i++; } return (0); } static int dot_found(int **tab, int height, int width) { t_count a; a.i = 0; a.j = 0; while (a.i < height) { a.j = 0; while (a.j < width) { if (tab[a.i][a.j] == '.') return (1); a.j++; } a.i++; } return (0); } void create_map(t_form *board, char for_enemy) { int current; current = 100; check_around(board->c_form, board->height, board->width, for_enemy); while (dot_found(board->c_form, board->height, board->width)) { if (algorithm(board->c_form, board->height, board->width, current++) == 0) break ; } } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* additional_func.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpromoha <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/27 14:36:29 by dpromoha #+# #+# */ /* Updated: 2019/07/03 08:47:41 by dpromoha ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" static void what_is_piece(t_form *piece, t_compens *offsets) { t_count a; int m; int n; mem_for_piece(piece, offsets); a.i = offsets->second; a.j = offsets->first; m = 0; n = 0; while (a.i < piece->height - offsets->fourth) { while (a.j < piece->width - offsets->third) piece->shape[m][n++] = piece->form[a.i][a.j++]; piece->shape[m][n] = '\0'; a.j = offsets->first; a.i++; m++; n = 0; } } void help_filler(t_form **piece, t_compens **offsets, char **line) { (*piece) = create_piece(*line); (*offsets) = atack(*piece); what_is_piece((*piece), (*offsets)); } void print_c(int *winning_coordinates, t_compens **o) { if (winning_coordinates[0] != -100) { ft_printf("%d %d\n", winning_coordinates[0] - (*o)->second, winning_coordinates[1] - (*o)->first); } else ft_printf("0 0\n"); } static void mem_map(char **line, t_form **map) { (*map) = (t_form*)malloc(sizeof(t_form)); (*map)->height = h(*line); (*map)->width = w(*line); (*map)->c_form = (int**)malloc(sizeof(int*) * (*map)->height + 1); (*map)->form = (int**)malloc(sizeof(int*) * (*map)->height + 1); } t_form *more_mem_map(char *line) { int i; t_form *map; mem_map(&line, &map); i = 0; while (i < map->height) { map->form[i] = (int *)malloc(sizeof(int) * map->width + 1); map->c_form[i] = (int *)malloc(sizeof(int) * map->width + 1); i++; } map->form[i] = NULL; map->c_form[i] = NULL; return (map); }
da3997bdc869076ae3c628b5d00e8361213a6d66
[ "Markdown", "C", "Makefile" ]
19
Makefile
dpromoha/filler
70fa9ccc3d1fb906bc1bcddcbe7893349234d644
f825c452fd7c6da514a8d284e49a13c67df07634
refs/heads/master
<repo_name>corbtastik/game-logs<file_sep>/README.md # Retrosheet Game Log kinda fun ## Totes Props to Retrosheet Original Game Log Field schema is [here](https://www.retrosheet.org/gamelogs/glfields.txt). ## What is this? Simply stated its just fun with: * [Kotlin](https://kotlinlang.org) because its compact and cute * [Exposed](https://github.com/JetBrains/Exposed) for type-safe fluent SQL * [Baseball](https://www.mlb.com) with [Retrosheet](https://www.retrosheet.org)! * [Spring Boot](https://github.com/spring-projects/spring-boot) as the application framework * [Spring Shell](https://github.com/spring-projects/spring-shell) as the cli (awesomeness) ## Build and Run ```bash $ ./mvn clean package $ java -jar ./target/game-logs-0.0.1-SNAPSHOT.jar . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.6.RELEASE) shell:>help AVAILABLE COMMANDS Built-In Commands clear: Clear the shell screen. exit, quit: Exit the shell. help: Display help about available commands. script: Read and execute commands from a file. stacktrace: Display the full stacktrace of the last error. Game Logs Application games-between: Games Between: MM-dd-yyyy MM-dd-yyyy, ex: 07-04-2017 07-05-2017 games-on: Games On: MM-dd-yyyy, ex: 07-04-2017 load: Load Game Logs: game-log, ex: /path/to/gamelog.csv print: Print Game Log: game-log team-games: Team Games: team, ex: TEX or: TEX 04-01-2017 04-30-2017 ``` ## Play Type ``help`` to get a listing of methods to run. The ``load`` method takes a [retrosheet](https://www.retrosheet.org) game-log file and loads [H2](http://www.h2database.com) using [Exposed](https://github.com/JetBrains/Exposed). ### Load Game Log ```bash shell:>load src/main/resources/GL2017.TXT Loaded 2430 Game Log records. ``` #### Insert Snippet ```kotlin GameLogsTable.insert({ it[dateOfGame] = parts[0].asDateTime("yyyyMMdd") it[numberOfGame] = parts[1].unquote().toChar() it[dayOfWeek] = parts[2].unquote() it[visitingTeam] = parts[3].unquote() it[visitingTeamLeague] = parts[4].unquote() it[visitingTeamGameNumber] = parts[5].toInt() it[homeTeam] = parts[6].unquote() it[homeTeamLeague] = parts[7].unquote() it[homeTeamGameNumber] = parts[8].toInt() it[visitingTeamScore] = parts[9].toInt() it[homeTeamScore] = parts[10].toInt() }) ``` ### List Games #### Spring-Shell method to list games ```kotlin @ShellMethod("Games On: MM-dd-yyyy, for example 07-04-2017") fun gamesOn(gameDate: String) { transaction { val query = GameLogsTable.select { GameLogsTable.dateOfGame eq gameDate.asDateTime() } println("+--------------------------------+") query.forEach { val dateOfGame: DateTime = it[GameLogsTable.dateOfGame] val visitingTeam: String = it[GameLogsTable.visitingTeam] val visitingTeamLeague: String = it[GameLogsTable.visitingTeamLeague] val homeTeam: String = it[GameLogsTable.homeTeam] val homeTeamLeague: String = it[GameLogsTable.homeTeamLeague] val visitingTeamScore: String = it[GameLogsTable.visitingTeamScore].toString().padStart(3) val homeTeamScore: String = it[GameLogsTable.homeTeamScore].toString().padStart(3) println("|${dateOfGame.asString()}|$visitingTeam|$visitingTeamLeague|$visitingTeamScore" + "|$homeTeam|$homeTeamLeague|$homeTeamScore|") } println("+--------------------------------+") } } ``` ```bash shell:>games-on 07-04-2017 +--------------------------------+ |07-04-2017|HOU|AL| 16|ATL|NL| 4| |07-04-2017|TBA|AL| 6|CHN|NL| 5| |07-04-2017|CIN|NL| 8|COL|NL| 1| |07-04-2017|ARI|NL| 3|LAN|NL| 4| |07-04-2017|BAL|AL| 2|MIL|NL| 6| |07-04-2017|PIT|NL| 3|PHI|NL| 0| |07-04-2017|MIA|NL| 5|SLN|NL| 2| |07-04-2017|NYN|NL| 4|WAS|NL| 11| |07-04-2017|SDN|NL| 1|CLE|AL| 0| |07-04-2017|SFN|NL| 3|DET|AL| 5| |07-04-2017|ANA|AL| 4|MIN|AL| 5| |07-04-2017|TOR|AL| 4|NYA|AL| 1| |07-04-2017|CHA|AL| 6|OAK|AL| 7| |07-04-2017|KCA|AL| 7|SEA|AL| 3| |07-04-2017|BOS|AL| 11|TEX|AL| 4| +--------------------------------+ ``` ### Kotlin extension functions Love the way extension functions reduce code clutter. For example its nice to have simple ``String`` to ``DateTime`` and ``DateTime`` to ``String`` conversions via extensions. ```kotlin fun CharSequence.toChar() = single() // "W".toChar() fun String.unquote() = replace("\"", "") // "\"20170403\"".unquote() fun String.asDateTime(pattern: String) = DateTime.parse(this.unquote(), DateTimeFormat.forPattern(pattern)) // "20170704".asDateTime("yyyyMMdd") fun String.asDateTime() = asDateTime("MM-dd-yyyy") // "07-04-2017".asDateTime() fun DateTime.asString() = toString("MM-dd-yyyy") // dateTime.asString() ``` ### Exposed Simply elegant and type-safe SQL! Easily define tables and create schemas. ```kotlin object GameLogsTable: Table() { val id = integer("id").autoIncrement().primaryKey() val dateOfGame = date("date_of_game") val numberOfGame = char("number_of_game") val dayOfWeek = varchar("day_of_week", 3) val visitingTeam = varchar("visiting_team", 3) val visitingTeamLeague = varchar("visiting_team_league", 2) val visitingTeamGameNumber = integer("visiting_team_game_number") val homeTeam = varchar("home_team", 3) val homeTeamLeague = varchar("home_team_league", 2) val homeTeamGameNumber = integer("home_team_game_number") val visitingTeamScore = integer("visiting_team_score") val homeTeamScore = integer("home_team_score") } ``` ### Have Fun Watch more baseball and code less with Kotlin!<file_sep>/src/main/resources/gl2017.sql DROP TABLE IF EXISTS `game_log`; CREATE TABLE `game_log` ( `id` INT AUTO_INCREMENT, `date` DATE DEFAULT NULL, `title` CHAR(1) DEFAULT NULL, `day_of_week` CHAR(3) DEFAULT NULL, `visiting_team` CHAR(3) DEFAULT NULL, `visiting_team_league` CHAR(2) DEFAULT NULL, `visiting_team_game_number` SMALLINT DEFAULT NULL, `home_team` CHAR(3) DEFAULT NULL, `home_team_league` CHAR(2) DEFAULT NULL, `home_team_game_number` SMALLINT DEFAULT NULL, `visiting_team_score` SMALLINT DEFAULT NULL, `home_team_score` SMALLINT DEFAULT NULL, PRIMARY KEY (`id`), INDEX (`date`) );<file_sep>/src/main/kotlin/io/corbs/gamelogs/GameLogsApp.kt package io.corbs.gamelogs import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.shell.standard.ShellComponent import org.springframework.shell.standard.ShellMethod import org.springframework.shell.standard.ShellOption import java.io.File object GameLogsTable: Table() { val id = integer("id").autoIncrement().primaryKey() val dateOfGame = date("date_of_game") val numberOfGame = char("number_of_game") val dayOfWeek = varchar("day_of_week", 3) val visitingTeam = varchar("visiting_team", 3) val visitingTeamLeague = varchar("visiting_team_league", 2) val visitingTeamGameNumber = integer("visiting_team_game_number") val homeTeam = varchar("home_team", 3) val homeTeamLeague = varchar("home_team_league", 2) val homeTeamGameNumber = integer("home_team_game_number") val visitingTeamScore = integer("visiting_team_score") val homeTeamScore = integer("home_team_score") } fun CharSequence.toChar() = single() fun String.unquote() = replace("\"", "") fun String.asDateTime(pattern: String) = DateTime.parse(this.unquote(), DateTimeFormat.forPattern(pattern)) fun String.asDateTime() = asDateTime("MM-dd-yyyy") fun DateTime.asString() = toString("MM-dd-yyyy") @ShellComponent @SpringBootApplication class GameLogsApplication { init { Database.connect("jdbc:h2:mem:gamelogs;DB_CLOSE_DELAY=-1", driver = "org.h2.Driver") } @ShellMethod("Load Game Logs: game-log, ex: /path/to/gamelog.csv") fun load(gameLog: String) { transaction { SchemaUtils.create(GameLogsTable) var lines = 0 File(gameLog).forEachLine { val parts = it.split(",") GameLogsTable.insert({ it[dateOfGame] = parts[0].asDateTime("yyyyMMdd") it[numberOfGame] = parts[1].unquote().toChar() it[dayOfWeek] = parts[2].unquote() it[visitingTeam] = parts[3].unquote() it[visitingTeamLeague] = parts[4].unquote() it[visitingTeamGameNumber] = parts[5].toInt() it[homeTeam] = parts[6].unquote() it[homeTeamLeague] = parts[7].unquote() it[homeTeamGameNumber] = parts[8].toInt() it[visitingTeamScore] = parts[9].toInt() it[homeTeamScore] = parts[10].toInt() }) lines++ } println("Loaded $lines Game Log records.") } } @ShellMethod("Games On: MM-dd-yyyy, ex: 07-04-2017") fun gamesOn(gameDate: String) { transaction { val query = GameLogsTable.select { GameLogsTable.dateOfGame eq gameDate.asDateTime() } fetchGames(query) } } @ShellMethod("Games Between: MM-dd-yyyy MM-dd-yyyy, ex: 07-04-2017 07-05-2017") fun gamesBetween(@ShellOption(defaultValue = "01-01-2017") start: String, @ShellOption(defaultValue = "12-31-2017") end: String) { transaction { val query = GameLogsTable.select { (GameLogsTable.dateOfGame greaterEq start.asDateTime()) and (GameLogsTable.dateOfGame lessEq end.asDateTime()) } fetchGames(query) } } @ShellMethod("Team Games: team, ex: TEX or: TEX 04-01-2017 04-30-2017") fun teamGames(team: String, @ShellOption(defaultValue = "01-01-2017") start: String, @ShellOption(defaultValue = "12-31-2017") end: String) { transaction { val query = GameLogsTable.select { (GameLogsTable.dateOfGame greaterEq start.asDateTime()) and (GameLogsTable.dateOfGame lessEq end.asDateTime()) and ((GameLogsTable.homeTeam eq team) or (GameLogsTable.visitingTeam eq team)) } fetchGames(query) } } @ShellMethod("Print Game Log: game-log") fun print(gameLog: String) { File(gameLog).forEachLine { println(it) } } private fun fetchGames(query: Query) { printDiv() query.forEach { printGame(it) } printDiv() } private fun printGame(row: ResultRow) { val dateOfGame: DateTime = row[GameLogsTable.dateOfGame] val visitingTeam: String = row[GameLogsTable.visitingTeam] val visitingTeamLeague: String = row[GameLogsTable.visitingTeamLeague] val homeTeam: String = row[GameLogsTable.homeTeam] val homeTeamLeague: String = row[GameLogsTable.homeTeamLeague] val visitingTeamScore: String = row[GameLogsTable.visitingTeamScore].toString().padStart(3) val homeTeamScore: String = row[GameLogsTable.homeTeamScore].toString().padStart(3) println("|${dateOfGame.asString()}|$visitingTeam|$visitingTeamLeague|$visitingTeamScore" + "|$homeTeam|$homeTeamLeague|$homeTeamScore|") } private fun printDiv() { println("+--------------------------------+") } } fun main(args: Array<String>) { runApplication<GameLogsApplication>(*args) }
832ef77f8a36cba60f823993354478ba27947122
[ "Markdown", "SQL", "Kotlin" ]
3
Markdown
corbtastik/game-logs
925b7719208bdecac2da95d78948d55f6dee9164
286cbd814315ebb73931eabff53b3daabcfbde08
refs/heads/master
<repo_name>enimiste/dress-advisore<file_sep>/protected/data/migrations/1_add_last_login_column_users_table.sql ALTER TABLE users ADD last_login TIMESTAMP NULL;<file_sep>/README.md # Dress advisore web application An application to manage our clothes and dresses. - List all clothes that we have. - Compose clothes combination. - List all combinations. ## Pre-requisites : * php : >=5.3.3 * ext-ctype * ext-dom * ext-json * ext-pcre * ext-spl ## Installation : Firstly run this command : ```sh $ cd path/to/web/server/www $ git clone enimiste/dress-advisore project_name ``` If all goes right open the new project in your favorite IDE. (ex: [PhpStorm]) ### Setup the Database schema and data : You can use many types of database as it is supported by [PDO Driver]. In this section i will focus on two database types : **Sqlite** and **Mysql**. * __Sqlite__ : + Prequisites : - Installing Sqlite3 from [Sqlite3]. - Enabling PHP Sqlite extension on `php.ini` file + The project is bundled with the database file located under `protected/data/app.db`. + This database is seeded with the needed data. So it is ready to use for next steps. * __Mysql__ : You have two options : *Mysql* extension or *Mysqli* extension So you should be sure that the desired extension is enabled in `php.ini` file before using it. 1. Open the `protected/config.database.xml` file. 2. Comment the sqlite config : ```xml <database ConnectionString="sqlite:protected/data/app.db"/> ``` 3. Uncomment the Mysql config (mysql or mysqli) : ```xml <!-- <database ConnectionString="mysqli:host=localhost;dbname=test" username="dbuser" password="<PASSWORD>" /> --> <!-- <database ConnectionString="mysql:host=localhost;dbname=test" username="dbuser" password="<PASSWORD>" /> --> ``` 4. Create an empty database named as `;dbname=` in the step 3. 5. Update **host**, **username** and **password** with the correct ones. 6. Open your Mysql console and run the following statements in order : * The content of `protected/data/migrations` directory files (*.sql) * The content of `protected/data/seeds` directory files (*.sql) ### Parameters config : Now its time to update our parameters config located in the file `protected/config/parameters.xml`. Ex : ```xml <parameter id="base_url" value="http://localhost/project_name/"/> ``` This parameter is used to build assets urls (css, javascripts, ...) via the function `site_url($uri)` ## Test in browser : Now you can test the project. 1. Check if your web server under it the project is deployed is running. 2. Check if your RDBS is running if you use one. 3. Type the URL to your project in the browser. Ex : `http://localhost/project_name`. 4. The web app will show you the default page of Frontoffice. 5. To see the Backoffice, click on the link **"Espace d'administration"** (Backoffice space in frensh, sorry) : + A login page will show. + Type one of these credentials to access the web app as authenticated user : Username | Password | Role --- | --- | --- sadmin |sadmin |Super Admin admin |admin |Normal Admin user |user |Normal User + And bingo you can manage : **users**, **site settings** [//]:# (These are the links used in this document.) [PhpStorm]: https://www.jetbrains.com/phpstorm/ [PDO Driver]: http://php.net/manual/en/pdo.drivers.php [Sqlite3]: https://www.sqlite.org/ [PRADO]: http://www.pradoframework.net/site/
2eca489f3bf28ecae6dab780063f69e0ecf363a1
[ "Markdown", "SQL" ]
2
SQL
enimiste/dress-advisore
00202c29feefe257a22c7010ec6bf7f09a6a92ff
5eec5396fbb3512257a8374c0e20a3a579498929
refs/heads/master
<file_sep>import math import random # input1 = persen # input2 = nama file # input4 = file training # input5 = file testing class divider: # constructor def __init__(self, input1, input2, input4, input5): self.input1 = input1 try: self.input2 = open(input2, 'r') self.fileTraining = open(input4, 'w') self.fileTesting = open(input5, 'w') except: print "error : File "+input2+" not found\n[-] Exit\n" exit(1) self.count = 0 self.tempArr = [] def read(self): for line in self.input2: if line.strip() == "@data": self.count += 1 self.fileTraining.write(line) self.fileTesting.write(line) elif self.count == 0: self.fileTraining.write(line) self.fileTesting.write(line) else : if self.count >= 1 and line.strip() != '': self.tempArr.append(line.strip()) self.count += 1 self.write() def write(self): countTemp = self.count for item in range(0, int(math.floor((float(self.input1) / 100) * (countTemp-1)))): ran = random.randint(0, len(self.tempArr) - 1) self.fileTraining.write(self.tempArr[ran] + "\n") self.tempArr.pop(ran) for item in self.tempArr: self.fileTesting.write(item + "\n") self.clean() # cleaning up memory def clean(self): for k in range(0, len(self.tempArr)): self.tempArr.pop(0) self.input2.close() self.fileTesting.close() self.fileTraining.close() if __name__ == '__main__': input1 = raw_input("berapa persen : ") input2 = raw_input("nama file : ") input4 = raw_input("file training : ") input5 = raw_input("file testing : ") run = divider(input1, input2, input4, input5) run.read() <file_sep># mycode author : <NAME>
1f7bd1ded6809f3d607e997aec9a01c5ce72614b
[ "Markdown", "Python" ]
2
Python
jamilsalsabila/mycode
03878dd6dd23ff7376a917d52bbfc8d01ece24c6
201339d7652dfbd89f6efde05205a5f80845eee2
refs/heads/master
<repo_name>h243582/yikuaitui<file_sep>/js/toggleClass.js function hasClass(obj, cls) { return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); } function addClass(obj, cls) { if (!this.hasClass(obj, cls)) obj.className += " " + cls; } function removeClass(obj, cls) { if (hasClass(obj, cls)) { var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); obj.className = obj.className.replace(reg, ' '); } } function toggleClass(obj,cls,string1,string2){ if(hasClass(obj,cls)){ removeClass(obj, cls); obj.innerText = string1; }else{ addClass(obj, cls); obj.innerText = string2; } } function Siblings(elm) { var a = []; var p = elm.parentNode.children; for(var i =0,pl= p.length;i<pl;i++) { if(p[i] !== elm) a.push(p[i]); } return a; }<file_sep>/README.md # yikuaitui 这是我的第一个比较大且完整的前端项目吧。 是一个web app,功能主要是展示每个人推出的视频,图片,文字来与他人共同交流等。 类似于一个社交版的朋友圈。 这是一个外包项目, 但是也倾注了我许多心血, 加油。 [![ghit.me](https://ghit.me/badge.svg?repo=BernersH/yikuaitui)](https://ghit.me/repo/BernersH/yikuaitui)
e863ae57c922c436c9af128b20fd49f59e6d9185
[ "JavaScript", "Markdown" ]
2
JavaScript
h243582/yikuaitui
4243a758f7609e59db17f887f320ab17593f8f57
0a60e58a74f94326e5b34f11d435254b6fd551c3
refs/heads/master
<repo_name>sudo4odus/LearnGit-Github<file_sep>/README.md # LearnGit-Github this repo is created to practise git and github <file_sep>/Person.java public class Person{ private String first_name, last_name, address, phone_number; private Date birth_date; public Person(){} public Person(String fn, String ln, String ad, String pn, Date bd) { first_name = fn; last_name = ln; address = ad; phone_number = ph; birth_date = bd; } public Person(String fn, String ln, Date bd) { first_name = fn; last_name = ln; birth_date = bd; } }
0c2e674b5b79139ecd8929474501b77b0792a04f
[ "Markdown", "Java" ]
2
Markdown
sudo4odus/LearnGit-Github
371af8ce59be916436b5311b14300a48adf75ee1
4421bc07c26bdc99b3db473596a7d3969e9d4720
refs/heads/master
<repo_name>LittleDevilGames/inari-firefly<file_sep>/src/main/java/com/inari/firefly/physics/collision/Contact.java package com.inari.firefly.physics.collision; import java.util.ArrayDeque; import com.inari.commons.geom.BitMask; import com.inari.commons.geom.Rectangle; import com.inari.commons.lang.Disposable; import com.inari.commons.lang.aspect.Aspect; public class Contact implements Disposable { private static final ArrayDeque<Contact> disposedContacts = new ArrayDeque<Contact>(); private int entityId; private final Rectangle worldBounds = new Rectangle(); private final Rectangle intersectionBounds = new Rectangle(); private final BitMask intersectionMask = new BitMask( 0, 0 ); Aspect contactType; Aspect materialType; public final int entityId() { return entityId; } public final Rectangle worldBounds() { return worldBounds; } public final Rectangle intersectionBounds() { return intersectionBounds; } public final BitMask intersectionMask() { return intersectionMask; } public final Aspect contactType() { return contactType; } public final Aspect materialType() { return materialType; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append( "Contact [entityId=" ); builder.append( entityId ); builder.append( ", worldBounds=" ); builder.append( worldBounds ); builder.append( ", intersectionBounds=" ); builder.append( intersectionBounds ); builder.append( ", intersectionMask=" ); builder.append( intersectionMask ); builder.append( ", contactType=" ); builder.append( contactType ); builder.append( ", materialType=" ); builder.append( materialType ); builder.append( "]" ); return builder.toString(); } @Override public final void dispose() { entityId = -1; intersectionMask.clearMask(); worldBounds.clear(); contactType = null; materialType = null; intersectionBounds.clear(); disposedContacts.add( this ); } public final static Contact createContact( int entityId ) { Contact contact = disposedContacts.getFirst(); if ( contact == null ) { contact = new Contact(); } contact.entityId = entityId; return contact; } public final static Contact createContact( int entityId, Aspect materialType, Aspect contactType, int x, int y, int width, int height ) { Contact contact = ( !disposedContacts.isEmpty() )? disposedContacts.pollFirst() : new Contact(); contact.entityId = entityId; contact.contactType = contactType; contact.materialType = materialType; contact.worldBounds.x = x; contact.worldBounds.y = y; contact.worldBounds.width = width; contact.worldBounds.height = height; return contact; } } <file_sep>/src/main/java/com/inari/firefly/control/behavior/BCondition.java package com.inari.firefly.control.behavior; import com.inari.firefly.control.behavior.Action.ActionState; import com.inari.firefly.system.FFContext; public interface BCondition { ActionState check( int entityId, final EBehavoir behavior, final FFContext context ); } <file_sep>/src/main/java/com/inari/firefly/physics/collision/ECollision.java package com.inari.firefly.physics.collision; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.inari.commons.geom.BitMask; import com.inari.commons.geom.Rectangle; import com.inari.commons.lang.aspect.Aspect; import com.inari.commons.lang.list.DynArray; import com.inari.firefly.component.attr.AttributeKey; import com.inari.firefly.component.attr.AttributeMap; import com.inari.firefly.entity.EntityComponent; public final class ECollision extends EntityComponent { public static final EntityComponentTypeKey<ECollision> TYPE_KEY = EntityComponentTypeKey.create( ECollision.class ); public static final AttributeKey<Rectangle> COLLISION_BOUNDS = new AttributeKey<Rectangle>( "collisionBounds", Rectangle.class, ECollision.class ); public static final AttributeKey<BitMask> COLLISION_MASK = new AttributeKey<BitMask>( "collisionMask", BitMask.class, ECollision.class ); public static final AttributeKey<String> COLLISION_RESOLVER_NAME = new AttributeKey<String>( "collisionResolverName", String.class, ECollision.class ); public static final AttributeKey<Integer> COLLISION_RESOLVER_ID = new AttributeKey<Integer>( "collisionResolverId", Integer.class, ECollision.class ); public static final AttributeKey<Aspect> MATERIAL_TYPE = new AttributeKey<Aspect>( "materialType", Aspect.class, ECollision.class ); public static final AttributeKey<Aspect> CONTACT_TYPE = new AttributeKey<Aspect>( "contactType", Aspect.class, ECollision.class ); public static final AttributeKey<DynArray<ContactConstraint>> CONTACT_CONSTRAINTS = AttributeKey.createDynArray( "contactConstraints", ECollision.class ); private static final AttributeKey<?>[] ATTRIBUTE_KEYS = new AttributeKey[] { COLLISION_BOUNDS, COLLISION_MASK, COLLISION_RESOLVER_ID, MATERIAL_TYPE, CONTACT_TYPE, CONTACT_CONSTRAINTS }; private final Rectangle collisionBounds; private BitMask collisionMask; private int collisionResolverId; private Aspect materialType; private Aspect contactType; private ContactScan contactScan; ECollision() { super( TYPE_KEY ); collisionBounds = new Rectangle(); contactScan = new ContactScan(); resetAttributes(); } @Override public final void resetAttributes() { collisionMask = null; collisionResolverId = -1; contactType = null; materialType = null; contactScan = new ContactScan(); } public final Rectangle getCollisionBounds() { return collisionBounds; } public final void setCollisionBounds( Rectangle collisionBounds ) { if ( collisionBounds == null ) { this.collisionBounds.x = 0; this.collisionBounds.y = 0; this.collisionBounds.width = 0; this.collisionBounds.height = 0; return; } this.collisionBounds.setFrom( collisionBounds ); } public final BitMask getCollisionMask() { return collisionMask; } public final void setCollisionMask( BitMask collisionMask ) { this.collisionMask = collisionMask; } public final int getCollisionResolverId() { return collisionResolverId; } public final void setCollisionResolverId( int collisionResolverId ) { this.collisionResolverId = collisionResolverId; } public final ContactScan getContactScan() { return contactScan; } public final Aspect getMaterialType() { return materialType; } public final void setMaterialType( Aspect materialType ) { this.materialType = materialType; } public final Aspect getContactType() { return contactType; } public final void setContactType( Aspect contactType ) { this.contactType = contactType; } public final void addContactConstraint( ContactConstraint constraint ) { contactScan.addContactContstraint( constraint ); } @Override public final Set<AttributeKey<?>> attributeKeys() { return new HashSet<AttributeKey<?>>( Arrays.asList( ATTRIBUTE_KEYS ) ); } @Override public final void fromAttributes( AttributeMap attributes ) { setCollisionBounds( attributes.getValue( COLLISION_BOUNDS, collisionBounds ) ); collisionMask = attributes.getValue( COLLISION_MASK, collisionMask ); collisionResolverId = attributes.getIdForName( COLLISION_RESOLVER_NAME, COLLISION_RESOLVER_ID, CollisionResolver.TYPE_KEY, collisionResolverId ); materialType = attributes.getValue( MATERIAL_TYPE, materialType ); contactType = attributes.getValue( CONTACT_TYPE, contactType ); if ( attributes.contains( CONTACT_CONSTRAINTS ) ) { DynArray<ContactConstraint> constraints = attributes.getValue( CONTACT_CONSTRAINTS ); for ( ContactConstraint constraint : constraints ) { addContactConstraint( constraint ); } } } @Override public final void toAttributes( AttributeMap attributes ) { attributes.put( COLLISION_BOUNDS, collisionBounds ); attributes.put( COLLISION_MASK, collisionMask ); attributes.put( COLLISION_RESOLVER_ID, collisionResolverId ); attributes.put( MATERIAL_TYPE, materialType ); attributes.put( CONTACT_TYPE, contactType ); } } <file_sep>/src/main/java/com/inari/firefly/system/external/SpriteData.java package com.inari.firefly.system.external; import com.inari.commons.geom.Rectangle; import com.inari.firefly.component.attr.AttributeKey; public interface SpriteData { int getTextureId(); Rectangle getTextureRegion(); <A> A getDynamicAttribute( AttributeKey<A> key ); boolean isHorizontalFlip(); boolean isVerticalFlip(); } <file_sep>/src/main/java/com/inari/firefly/component/dynattr/DynamicAttributeMap.java /******************************************************************************* * Copyright (c) 2015 - 2016, <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.inari.firefly.component.dynattr; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.inari.firefly.component.attr.AttributeKey; import com.inari.firefly.component.attr.AttributeMap; public class DynamicAttributeMap { protected Map<AttributeKey<?>, Object> dynamicAttributes = new HashMap<AttributeKey<?>, Object>(); public final Set<AttributeKey<?>> attributeKeys( DynamicAttributedComponent component, Set<AttributeKey<?>> attributeKeys ) { attributeKeys.addAll( component.attributeKeys() ); Set<AttributeKey<?>> dynAttributeSetForType = DynamicAttribueMapper.getDynAttributeSetForType( component.componentType() ); if ( dynAttributeSetForType != null && !attributeKeys.containsAll( dynAttributeSetForType ) ) { attributeKeys.addAll( dynAttributeSetForType ); } return attributeKeys; } public final void fromAttributeMap( AttributeMap attributes, DynamicAttributedComponent component ) { Set<AttributeKey<?>> dynAttributeSetForType = DynamicAttribueMapper.getDynAttributeSetForType( component.componentType() ); if ( dynAttributeSetForType == null ) { return; } for ( AttributeKey<?> key : dynAttributeSetForType ) { Object defaultValue = dynamicAttributes.get( key ); dynamicAttributes.put( key, attributes.getUntypedValue( key, defaultValue ) ); } } public final void toAttributeMap( AttributeMap attributes, DynamicAttributedComponent component ) { Set<AttributeKey<?>> dynAttributeSetForType = DynamicAttribueMapper.getDynAttributeSetForType( component.componentType() ); if ( dynAttributeSetForType == null ) { return; } } public final <A> void setDynamicAttribute( AttributeKey<A> key, A value, Class<? extends DynamicAttributedComponent> type ) { Set<AttributeKey<?>> dynAttributeSetForType = DynamicAttribueMapper.getDynAttributeSetForType( type ); if ( dynAttributeSetForType == null || !dynAttributeSetForType.contains( key ) ) { throw new IllegalArgumentException( "Unknown AttributeKey " + key + " for DynamicAttributedAsset " + type ); } dynamicAttributes.put( key, value ); } public final <A> A getDynamicAttribute( AttributeKey<A> key ) { Object value = dynamicAttributes.get( key ); if ( value == null ) { return null; } return key.valueType().cast( value ); } } <file_sep>/src/main/java/com/inari/firefly/graphics/tile/TileGridSystem.java /******************************************************************************* * Copyright (c) 2015 - 2016, <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.inari.firefly.graphics.tile; import java.util.Iterator; import com.inari.commons.geom.Position; import com.inari.commons.lang.aspect.Aspects; import com.inari.commons.lang.list.DynArray; import com.inari.firefly.FFInitException; import com.inari.firefly.entity.EntityActivationEvent; import com.inari.firefly.entity.EntityActivationListener; import com.inari.firefly.entity.EntitySystem; import com.inari.firefly.graphics.ETransform; import com.inari.firefly.graphics.view.ViewEvent; import com.inari.firefly.graphics.view.ViewEvent.Type; import com.inari.firefly.graphics.view.ViewEventListener; import com.inari.firefly.system.FFContext; import com.inari.firefly.system.RenderEvent; import com.inari.firefly.system.component.ComponentSystem; import com.inari.firefly.system.component.SystemBuilderAdapter; import com.inari.firefly.system.component.SystemComponent.SystemComponentKey; import com.inari.firefly.system.component.SystemComponentBuilder; public final class TileGridSystem extends ComponentSystem<TileGridSystem> implements ViewEventListener, EntityActivationListener { public static final FFSystemTypeKey<TileGridSystem> SYSTEM_KEY = FFSystemTypeKey.create( TileGridSystem.class ); private static final SystemComponentKey<?>[] SUPPORTED_COMPONENT_TYPES = new SystemComponentKey[] { TileGrid.TYPE_KEY, TileGridRenderer.TYPE_KEY }; private EntitySystem entitySystem; private final DynArray<TileGridRenderer> renderer; private final DynArray<TileGrid> tileGrids; private final DynArray<DynArray<TileGrid>> tileGridOfViewsPerLayer; public TileGridSystem() { super( SYSTEM_KEY ); renderer = DynArray.create( TileGridRenderer.class, 5, 5 ); tileGrids = DynArray.create( TileGrid.class, 20, 10 ); tileGridOfViewsPerLayer = DynArray.createTyped( DynArray.class, 10, 10 ); } @Override public void init( FFContext context ) { super.init( context ); entitySystem = context.getSystem( EntitySystem.SYSTEM_KEY ); // build and register default tile grid renderer getRendererBuilder( NormalFastTileGridRenderer.class ) .set( TileGridRenderer.NAME, NormalFastTileGridRenderer.NAME ) .build(); getRendererBuilder( NormalFullTileGridRenderer.class ) .set( TileGridRenderer.NAME, NormalFullTileGridRenderer.NAME ) .build(); context.registerListener( ViewEvent.TYPE_KEY, this ); context.registerListener( EntityActivationEvent.TYPE_KEY, this ); context.registerListener( TileSystemEvent.TYPE_KEY, this ); } public final TileGridRendererBuilder getRendererBuilder( Class<? extends TileGridRenderer> componentType ) { return new TileGridRendererBuilder( componentType ); } @Override public final void dispose( FFContext context ) { context.disposeListener( ViewEvent.TYPE_KEY, this ); context.disposeListener( EntityActivationEvent.TYPE_KEY, this ); context.disposeListener( TileSystemEvent.TYPE_KEY, this ); for ( TileGridRenderer r : renderer ) { context.disposeListener( RenderEvent.TYPE_KEY, r ); r.dispose(); } clear(); } final void removeMultiTilePosition( final int tileGridId, final int entityId, final int x, final int y ) { ETile tile = entitySystem.getComponent( entityId, ETile.TYPE_KEY ); tile.getGridPositions().remove( new Position( x, y ) ); getTileGrid( tileGridId ).reset( x, y ); } final void addMultiTilePosition( final int tileGridId, final int entityId, final int x, final int y ) { ETile tile = entitySystem.getComponent( entityId, ETile.TYPE_KEY ); tile.getGridPositions().add( new Position( x, y ) ); getTileGrid( tileGridId ).set( entityId, x, y ); } public final void entityActivated( int entityId, final Aspects aspects ) { final ETransform transform = entitySystem.getComponent( entityId, ETransform.TYPE_KEY ); final ETile tile = entitySystem.getComponent( entityId, ETile.TYPE_KEY ); final TileGrid tileGrid = getTileGrid( transform.getViewId(), transform.getLayerId() ); final DynArray<Position> gridPositions = tile.getGridPositions(); for ( int i = 0; i < gridPositions.capacity(); i++ ) { if ( !gridPositions.contains( i ) ) { continue; } tileGrid.set( entityId, gridPositions.get( i ) ); } } public final void entityDeactivated( int entityId, final Aspects aspects ) { final ETransform transform = entitySystem.getComponent( entityId, ETransform.TYPE_KEY ); final ETile tile = entitySystem.getComponent( entityId, ETile.TYPE_KEY ); final TileGrid tileGrid = getTileGrid( transform.getViewId(), transform.getLayerId() ); final DynArray<Position> gridPositions = tile.getGridPositions(); for ( int i = 0; i < gridPositions.capacity(); i++ ) { if ( !gridPositions.contains( i ) ) { continue; } tileGrid.resetIfMatch( entityId, gridPositions.get( i ) ); } } @Override public final void onViewEvent( ViewEvent event ) { if ( event.isOfType( Type.VIEW_DELETED ) ) { deleteAllTileGrid( event.getView().index() ); return; } } @Override public final boolean match( Aspects aspects ) { return aspects.contains( ETile.TYPE_KEY ); } public final TileGridRenderer getRenderer( int id ) { if ( renderer.contains( id ) ) { return renderer.get( id ); } return null; } public final int getRendererId( String name ) { for ( TileGridRenderer r : renderer ) { if ( name.equals( r.getName() ) ) { return r.index(); } } return -1; } public final void deleteRenderer( int id ) { TileGridRenderer r = renderer.remove( id ); if ( r != null ) { context.disposeListener( RenderEvent.TYPE_KEY, r ); r.dispose(); } } public final boolean hasTileGrid( int viewId, int layerId ) { return getTileGrid( viewId, layerId ) != null; } public final TileGrid getTileGrid( final String tileGridName ) { for ( TileGrid tileGrid : tileGrids ) { if ( tileGrid != null && tileGrid.getName().equals( tileGridName ) ) { return tileGrid; } } return null; } public final int getTileGridId( final String tileGridName ) { for ( TileGrid tileGrid : tileGrids ) { if ( tileGrid != null && tileGrid.getName().equals( tileGridName ) ) { return tileGrid.index(); } } return -1; } public final TileGrid getTileGrid( int tileGridId ) { for ( TileGrid tileGrid : tileGrids ) { if ( tileGrid != null && tileGrid.index() == tileGridId ) { return tileGrid; } } return null; } public final TileGrid getTileGrid( int viewId, int layerId ) { if ( !tileGridOfViewsPerLayer.contains( viewId ) ) { return null; } DynArray<TileGrid> tileGridsForView = tileGridOfViewsPerLayer.get( viewId ); return tileGridsForView.get( layerId ); } public final int getTile( int viewId, int layerId, final Position position ) { TileGrid tileGrid = getTileGrid( viewId, layerId ); if ( tileGrid == null ) { return -1; } return tileGrid.getTileAt( position ); } public final int getTile( int tileGridId, final Position position ) { TileGrid tileGrid = getTileGrid( tileGridId ); if ( tileGrid == null ) { return -1; } return tileGrid.getTileAt( position ); } public final void deleteAllTileGrid( int viewId ) { if ( tileGridOfViewsPerLayer.contains( viewId ) ) { DynArray<TileGrid> toRemove = tileGridOfViewsPerLayer.remove( viewId ); for ( TileGrid tileGrid : toRemove ) { tileGrids.remove( tileGrid.index() ); disposeSystemComponent( tileGrid ); } } } public final void deleteTileGrid( int viewId, int layerId ) { if ( !tileGridOfViewsPerLayer.contains( viewId ) ) { return; } DynArray<TileGrid> tileGridsForView = tileGridOfViewsPerLayer.get( viewId ); if ( tileGridsForView == null ) { return; } if ( !tileGridOfViewsPerLayer.contains( layerId ) ) { return; } TileGrid removed = tileGridsForView.remove( layerId ); tileGrids.remove( removed.index() ); disposeSystemComponent( removed ); } public final void deleteTileGrid( int tileGridId ) { if ( !tileGrids.contains( tileGridId ) ) { return; } TileGrid removed = tileGrids.get( tileGridId ); tileGridOfViewsPerLayer.get( removed.getViewId() ).remove( removed.getLayerId() ); }; public final SystemComponentBuilder getTileGridBuilder() { return new TileGridBuilder(); } @Override public final SystemComponentKey<?>[] supportedComponentTypes() { return SUPPORTED_COMPONENT_TYPES; } @Override public final SystemBuilderAdapter<?>[] getSupportedBuilderAdapter() { return new SystemBuilderAdapter<?>[] { new TileGridBuilderAdapter(), new TileGridRendererBuilderAdapter() }; } @Override public final void clear() { tileGridOfViewsPerLayer.clear(); renderer.clear(); } private final class TileGridBuilder extends SystemComponentBuilder { private TileGridBuilder() { super( context ); } @Override public final SystemComponentKey<TileGrid> systemComponentKey() { return TileGrid.TYPE_KEY; } @Override public int doBuild( int componentId, Class<?> subType, boolean activate ) { TileGrid tileGrid = createSystemComponent( componentId, subType, context ); int viewId = tileGrid.getViewId(); int layerId = tileGrid.getLayerId(); if ( viewId < 0 ) { throw new FFInitException( "ViewId is mandatory for TileGrid" ); } if ( layerId < 0 ) { throw new FFInitException( "LayerId is mandatory for TileGrid" ); } if ( !tileGridOfViewsPerLayer.contains( viewId ) ) { tileGridOfViewsPerLayer.set( viewId, DynArray.create( TileGrid.class, 20, 10 ) ); } tileGrids.set( tileGrid.index(), tileGrid ); tileGridOfViewsPerLayer .get( viewId ) .set( layerId, tileGrid ); return tileGrid.index(); } } private final class TileGridRendererBuilder extends SystemComponentBuilder { private TileGridRendererBuilder( Class<? extends TileGridRenderer> componentType ) { super( context, componentType ); } @Override public final SystemComponentKey<TileGridRenderer> systemComponentKey() { return TileGridRenderer.TYPE_KEY; } @Override public int doBuild( int componentId, Class<?> componentType, boolean activate ) { TileGridRenderer component = createSystemComponent( componentId, componentType, context ); renderer.set( component.index(), component ); return component.index(); } } private final class TileGridBuilderAdapter extends SystemBuilderAdapter<TileGrid> { private TileGridBuilderAdapter() { super( TileGridSystem.this, TileGrid.TYPE_KEY ); } @Override public final TileGrid get( int id ) { return getTileGrid( id ); } @Override public final Iterator<TileGrid> getAll() { return tileGrids.iterator(); } @Override public final void delete( int id ) { deleteTileGrid( id ); } @Override public final int getId( String name ) { return getTileGridId( name ); } @Override public final void activate( int id ) { throw new UnsupportedOperationException( componentTypeKey() + " is not activable" ); } @Override public final void deactivate( int id ) { throw new UnsupportedOperationException( componentTypeKey() + " is not activable" ); } @Override public final SystemComponentBuilder createComponentBuilder( Class<? extends TileGrid> componentType ) { return new TileGridBuilder(); } } private final class TileGridRendererBuilderAdapter extends SystemBuilderAdapter<TileGridRenderer> { private TileGridRendererBuilderAdapter() { super( TileGridSystem.this, TileGridRenderer.TYPE_KEY ); } @Override public final TileGridRenderer get( int id ) { return getRenderer( id ); } @Override public final void delete( int id ) { deleteRenderer( id ); } @Override public final Iterator<TileGridRenderer> getAll() { return renderer.iterator(); } @Override public final int getId( String name ) { return getRendererId( name ); } @Override public final void activate( int id ) { throw new UnsupportedOperationException( componentTypeKey() + " is not activable" ); } @Override public final void deactivate( int id ) { throw new UnsupportedOperationException( componentTypeKey() + " is not activable" ); } @Override public final SystemComponentBuilder createComponentBuilder( Class<? extends TileGridRenderer> componentType ) { if ( componentType == null ) { throw new IllegalArgumentException( "componentType is needed for SystemComponentBuilder for component: " + componentTypeKey().name() ); } return new TileGridRendererBuilder( componentType ); } } } <file_sep>/src/main/java/com/inari/firefly/physics/animation/AnimationSystem.java /******************************************************************************* * Copyright (c) 2015 - 2016, <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.inari.firefly.physics.animation; import java.util.Iterator; import com.inari.commons.lang.aspect.Aspects; import com.inari.commons.lang.list.DynArray; import com.inari.firefly.entity.EntityActivationEvent; import com.inari.firefly.entity.EntityActivationListener; import com.inari.firefly.system.FFContext; import com.inari.firefly.system.UpdateEvent; import com.inari.firefly.system.UpdateEventListener; import com.inari.firefly.system.component.ComponentSystem; import com.inari.firefly.system.component.SystemBuilderAdapter; import com.inari.firefly.system.component.SystemComponent.SystemComponentKey; import com.inari.firefly.system.component.SystemComponentBuilder; public final class AnimationSystem extends ComponentSystem<AnimationSystem> implements UpdateEventListener, EntityActivationListener { public static final FFSystemTypeKey<AnimationSystem> SYSTEM_KEY = FFSystemTypeKey.create( AnimationSystem.class ); private static final SystemComponentKey<?>[] SUPPORTED_COMPONENT_TYPES = new SystemComponentKey[] { Animation.TYPE_KEY, AnimationResolver.TYPE_KEY }; final DynArray<Animation> animations; final DynArray<AnimationMapping> activeMappings; AnimationSystem() { super( SYSTEM_KEY ); animations = DynArray.create( Animation.class, 20, 10 ); activeMappings = DynArray.create( AnimationMapping.class, 100, 100 ); } @Override public void init( FFContext context ) { super.init( context ); context.registerListener( UpdateEvent.TYPE_KEY, this ); context.registerListener( AnimationSystemEvent.TYPE_KEY, this ); context.registerListener( EntityActivationEvent.TYPE_KEY, this ); } @Override public void dispose( FFContext context ) { clear(); context.disposeListener( UpdateEvent.TYPE_KEY, this ); context.disposeListener( AnimationSystemEvent.TYPE_KEY, this ); context.disposeListener( EntityActivationEvent.TYPE_KEY, this ); } @Override public final boolean match( Aspects aspects ) { return aspects.contains( EAnimation.TYPE_KEY ); } @Override public final void entityActivated( int entityId, Aspects aspects ) { DynArray<AnimationMapping> animationMappings = context.getEntityComponent( entityId, EAnimation.TYPE_KEY ).getAnimationMappings(); for ( int i = 0; i < animationMappings.capacity(); i++ ) { final AnimationMapping animationMapping = animationMappings.get( i ); if ( animationMapping == null ) { continue; } animationMapping.entityId = entityId; if ( animationMapping.animationId < 0 ) { animationMapping.animationId = getAnimationId( animationMapping.animationName ); } activeMappings.add( animationMapping ); } } @Override public final void entityDeactivated( int entityId, Aspects aspects ) { for ( int i = 0; i < activeMappings.capacity(); i++ ) { AnimationMapping animationMapping = activeMappings.get( i ); if ( animationMapping == null ) { continue; } if ( animationMapping.entityId == entityId ) { activeMappings.remove( i ); } } } public final void clear() { for ( Animation animation : animations ) { disposeSystemComponent( animation ); } animations.clear(); } final void onAnimationEvent( AnimationSystemEvent event ) { if ( !animations.contains( event.animationId ) ) { return; } Animation animation = animations.get( event.animationId ); switch ( event.type ) { case START_ANIMATION: { animation.active = true; break; } case STOP_ANIMATION: { animation.active = false; break; } case FINISH_ANIMATION: { animation.active = false; animation.finished = true; break; } } } public final boolean exists( int animationId ) { if ( animationId < 0 ) { return false; } return animations.contains( animationId ); } public final boolean isActive( int animationId ) { if ( animationId < 0 || !animations.contains( animationId ) ) { return false; } Animation animation = animations.get( animationId ); return animation.isActive(); } public final void activateAnimation( int animationId ) { animations.get( animationId ).activate(); } public final void resetAnimation( int animationId ) { animations.get( animationId ).reset(); } @Override public final void update( UpdateEvent event ) { for ( int i = 0; i < animations.capacity(); i++ ) { Animation animation = animations.get( i ); if ( animation != null ) { if ( animation.active ) { animation.systemUpdate(); applyValueAttribute( animation ); continue; } if ( animation.finished ) { animations.remove( animation.index() ); animation.dispose(); continue; } if ( animation.startTime > 0 && event.timer.getTime() >= animation.startTime ) { animation.activate(); applyValueAttribute( animation ); continue; } } } } private void applyValueAttribute( Animation animation ) { for ( int i = 0; i < activeMappings.capacity(); i++ ) { AnimationMapping animationMapping = activeMappings.get( i ); if ( animationMapping == null ) { continue; } animationMapping .adapterKey .getAdapterInstance() .apply( animationMapping.entityId, animation, context ); } } public final Animation getAnimation( int animationId ) { if ( animationId < 0 ) { return null; } return animations.get( animationId ); } public final <T extends Animation> T getAnimationAs( String animationName, Class<T> subType ) { return getAnimationAs( getAnimationId( animationName ), subType ); } public final <T extends Animation> T getAnimationAs( int animationId, Class<T> subType ) { if ( !animations.contains( animationId ) ) { return null; } return subType.cast( animations.get( animationId ) ); } public final int getAnimationId( String animationName ) { for ( int i = 0; i < animations.capacity(); i++ ) { if ( !animations.contains( i ) ) { continue; } Animation anim = animations.get( i ); if ( animationName.equals( anim.getName() ) ) { return anim.index(); } } return -1; } public final <A extends Animation> A getAnimation( Class<A> type, int animationId ) { Animation animation = animations.get( animationId ); if ( animation == null ) { return null; } return type.cast( animation ); } public final float getValue( int animationId, int componentId, float currentValue ) { if ( !isActive( animationId ) ) { return currentValue; } FloatAnimation animation = getAnimation( FloatAnimation.class, animationId ); return animation.getValue( componentId, currentValue ); } public final int getValue( int animationId, int componentId, int currentValue ) { if ( !isActive( animationId ) ) { return currentValue; } IntAnimation animation = getAnimation( IntAnimation.class, animationId ); return animation.getValue( componentId, currentValue ); } public final <V> V getValue( int animationId, int componentId, V currentValue ) { if ( !isActive( animationId ) ) { return currentValue; } @SuppressWarnings( "unchecked" ) ValueAnimation<V> animation = getAnimation( ValueAnimation.class, animationId ); return animation.getValue( componentId, currentValue ); } public final void deleteAnimation( int animationId ) { if ( !animations.contains( animationId ) ) { return; } disposeSystemComponent( animations.remove( animationId ) ); } public final SystemComponentBuilder getAnimationBuilder( Class<? extends Animation> componentType ) { if ( componentType == null ) { throw new IllegalArgumentException( "componentType is needed for SystemComponentBuilder for component: " + Animation.TYPE_KEY.name() ); } return new AnimationBuilder( componentType ); } @Override public final SystemComponentKey<?>[] supportedComponentTypes() { return SUPPORTED_COMPONENT_TYPES; } @Override public final SystemBuilderAdapter<?>[] getSupportedBuilderAdapter() { return new SystemBuilderAdapter[] { new AnimationBuilderAdapter() }; }; private final class AnimationBuilder extends SystemComponentBuilder { private AnimationBuilder( Class<? extends Animation> componentType ) { super( context, componentType ); } @Override public final SystemComponentKey<Animation> systemComponentKey() { return Animation.TYPE_KEY; } @Override public int doBuild( int componentId, Class<?> componentType, boolean activate ) { Animation animation = createSystemComponent( componentId, componentType, context ); animations.set( animation.index(), animation ); if ( activate ) { animation.active = true; } return animation.index(); } } private final class AnimationBuilderAdapter extends SystemBuilderAdapter<Animation> { private AnimationBuilderAdapter() { super( AnimationSystem.this, Animation.TYPE_KEY ); } @Override public final Animation get( int id ) { return getAnimation( id ); } @Override public final void delete( int id ) { deleteAnimation( id ); } @Override public final Iterator<Animation> getAll() { return animations.iterator(); } @Override public final int getId( String name ) { return getAnimationId( name ); } @Override public final void activate( int id ) { activateAnimation( id ); } @Override public final void deactivate( int id ) { resetAnimation( id ); } @Override public final SystemComponentBuilder createComponentBuilder( Class<? extends Animation> componentType ) { return getAnimationBuilder( componentType ); } } } <file_sep>/src/main/java/com/inari/firefly/graphics/sprite/ESpriteMultiplier.java package com.inari.firefly.graphics.sprite; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.inari.commons.geom.PositionF; import com.inari.commons.lang.list.DynArray; import com.inari.firefly.component.attr.AttributeKey; import com.inari.firefly.component.attr.AttributeMap; import com.inari.firefly.entity.EntityComponent; public final class ESpriteMultiplier extends EntityComponent { public static final EntityComponentTypeKey<ESpriteMultiplier> TYPE_KEY = EntityComponentTypeKey.create( ESpriteMultiplier.class ); public static final AttributeKey<DynArray<PositionF>> MULTI_POSITIONS = AttributeKey.createDynArray( "positions", ESpriteMultiplier.class ); private static final AttributeKey<?>[] ATTRIBUTE_KEYS = new AttributeKey[] { MULTI_POSITIONS }; private final DynArray<PositionF> positions; public ESpriteMultiplier() { super( TYPE_KEY ); positions = DynArray.create( PositionF.class, 20, 10 ); } @Override public final void resetAttributes() { positions.clear(); } public final DynArray<PositionF> getPositions() { return positions; } @Override public final Set<AttributeKey<?>> attributeKeys() { return new HashSet<AttributeKey<?>>( Arrays.asList( ATTRIBUTE_KEYS ) ); } @Override public final void fromAttributes( AttributeMap attributes ) { positions.clear(); if ( attributes.contains( MULTI_POSITIONS ) ) { positions.addAll( attributes.getValue( MULTI_POSITIONS ) ); } } @Override public final void toAttributes( AttributeMap attributes ) { attributes.put( MULTI_POSITIONS, positions ); } } <file_sep>/src/main/java/com/inari/firefly/graphics/tile/NormalFastTileGridRenderer.java package com.inari.firefly.graphics.tile; import com.inari.firefly.graphics.tile.TileGrid.TileGridIterator; import com.inari.firefly.system.RenderEvent; public class NormalFastTileGridRenderer extends TileGridRenderer { public static final String NAME = "NormalFastTileGridRenderer"; NormalFastTileGridRenderer( int id ) { super( id ); } @Override public final void render( RenderEvent event ) { int viewId = event.getViewId(); int layerId = event.getLayerId(); TileGrid tileGrid = tileGridSystem.getTileGrid( viewId, layerId ); if ( tileGrid == null || tileGrid.getRendererId() != index() ) { return; } TileGridIterator tileGridIterator = tileGrid.getTileGridIterator( event.getClip() ); while( tileGridIterator.hasNext() ) { ETile tile = entitySystem.getComponent( tileGridIterator.next(), ETile.TYPE_KEY ); graphics.renderSprite( tile, tileGridIterator.getWorldXPos(), tileGridIterator.getWorldYPos() ); } } } <file_sep>/src/main/java/com/inari/firefly/graphics/text/FontAsset.java package com.inari.firefly.graphics.text; import java.util.Arrays; import java.util.Set; import com.inari.commons.geom.Rectangle; import com.inari.commons.lang.IntIterator; import com.inari.commons.lang.list.IntBag; import com.inari.firefly.asset.Asset; import com.inari.firefly.component.attr.AttributeKey; import com.inari.firefly.component.attr.AttributeMap; import com.inari.firefly.system.FFContext; import com.inari.firefly.system.external.FFGraphics; import com.inari.firefly.system.external.SpriteData; import com.inari.firefly.system.external.TextureData; import com.inari.firefly.system.utils.Disposable; public final class FontAsset extends Asset implements TextureData { public static final AttributeKey<String> TEXTURE_RESOURCE_NAME = new AttributeKey<String>( "fontTextureId", String.class, FontAsset.class ); public static final AttributeKey<char[][]> CHAR_TEXTURE_MAP = new AttributeKey<char[][]>( "charTextureMap", char[][].class, FontAsset.class ); public static final AttributeKey<Integer> CHAR_WIDTH = new AttributeKey<Integer>( "charWidth", Integer.class, FontAsset.class ); public static final AttributeKey<Integer> CHAR_HEIGHT = new AttributeKey<Integer>( "charHeight", Integer.class, FontAsset.class ); public static final AttributeKey<Integer> CHAR_SPACE = new AttributeKey<Integer>( "charSpace", Integer.class, FontAsset.class ); public static final AttributeKey<Integer> LINE_SPACE = new AttributeKey<Integer>( "lineSpace", Integer.class, FontAsset.class ); public static final AttributeKey<Integer> DEFAULT_CHAR = new AttributeKey<Integer>( "defaultChar", Integer.class, FontAsset.class ); private static final AttributeKey<?>[] ATTRIBUTE_KEYS = new AttributeKey[] { TEXTURE_RESOURCE_NAME, CHAR_TEXTURE_MAP, CHAR_WIDTH, CHAR_HEIGHT, CHAR_HEIGHT, LINE_SPACE, DEFAULT_CHAR }; private String textureResourceName; private int textureWidth; private int textureHeight; private char[][] charTextureMap; private int charWidth; private int charHeight; private int charSpace; private int lineSpace; private int defaultChar; private IntBag charSpriteMap; private int textureId = -1; FontAsset( int id ) { super( id ); charTextureMap = null; charSpriteMap = new IntBag( 256, -1 ); charWidth = 0; charHeight = 0; charSpace = 0; lineSpace = 0; defaultChar = -1; } @Override public final int getInstanceId( int index ) { throw new UnsupportedOperationException(); } public final int getSpriteId( char character ) { int spriteId = charSpriteMap.get( character ); if ( spriteId >= 0 ) { return spriteId; } return charSpriteMap.get( defaultChar ); } @Override public final String getResourceName() { return textureResourceName; } public final String getTextureResourceName() { return textureResourceName; } public final void setTextureResourceName( String textureResourceName ) { this.textureResourceName = textureResourceName; } public final int getTextureWidth() { return textureWidth; } @Override public final void setTextureWidth( int textureWidth ) { this.textureWidth = textureWidth; } public final int getTextureHeight() { return textureHeight; } @Override public final void setTextureHeight( int textureHeight ) { this.textureHeight = textureHeight; } public final char[][] getCharTextureMap() { return charTextureMap; } public final void setCharTextureMap( char[][] charTextureMap ) { this.charTextureMap = charTextureMap; } public final int getCharWidth() { return charWidth; } public final void setCharWidth( int charWidth ) { this.charWidth = charWidth; } public final int getCharHeight() { return charHeight; } public final void setCharHeight( int charHeight ) { this.charHeight = charHeight; } public final int getCharSpace() { return charSpace; } public final void setCharSpace( int charSpace ) { this.charSpace = charSpace; } public final int getLineSpace() { return lineSpace; } public final void setLineSpace( int lineSpace ) { this.lineSpace = lineSpace; } public final int getDefaultChar() { return defaultChar; } public final void setDefaultChar( int defaultChar ) { this.defaultChar = defaultChar; } @Override public final Set<AttributeKey<?>> attributeKeys() { Set<AttributeKey<?>> attributeKeys = super.attributeKeys(); attributeKeys.addAll( Arrays.asList( ATTRIBUTE_KEYS ) ); return attributeKeys; } @Override public final void fromAttributes( AttributeMap attributes ) { super.fromAttributes( attributes ); textureResourceName = attributes.getValue( TEXTURE_RESOURCE_NAME, textureResourceName ); charTextureMap = attributes.getValue( CHAR_TEXTURE_MAP, charTextureMap ); charWidth = attributes.getValue( CHAR_WIDTH, charWidth ); charHeight = attributes.getValue( CHAR_HEIGHT, charHeight ); charSpace = attributes.getValue( CHAR_SPACE, charSpace ); lineSpace = attributes.getValue( LINE_SPACE, lineSpace ); defaultChar = attributes.getValue( DEFAULT_CHAR, defaultChar ); } @Override public final void toAttributes( AttributeMap attributes ) { super.toAttributes( attributes ); attributes.put( TEXTURE_RESOURCE_NAME, textureResourceName ); attributes.put( CHAR_TEXTURE_MAP, charTextureMap ); attributes.put( CHAR_WIDTH, charWidth ); attributes.put( CHAR_HEIGHT, charHeight ); attributes.put( CHAR_SPACE, charSpace ); attributes.put( LINE_SPACE, lineSpace ); attributes.put( DEFAULT_CHAR, defaultChar ); } @Override public final Disposable load( FFContext context ) { if ( loaded ) { return this; } FFGraphics graphics = context.getGraphics(); textureId = graphics.createTexture( this ); Rectangle textureRegion = new Rectangle( 0, 0, getCharWidth(), getCharHeight() ); InternalSpriteData spriteData = new InternalSpriteData( this, textureRegion ); for ( int y = 0; y < charTextureMap.length; y++ ) { for ( int x = 0; x < charTextureMap[ y ].length; x++ ) { textureRegion.x = x * charWidth; textureRegion.y = y * charHeight; int charSpriteId = graphics.createSprite( spriteData ); charSpriteMap.set( charTextureMap[ y ][ x ], charSpriteId ); } } return this; } @Override public final void dispose( FFContext context ) { if ( !loaded ) { return; } FFGraphics graphics = context.getGraphics(); IntIterator iterator = charSpriteMap.iterator(); while ( iterator.hasNext() ) { graphics.disposeSprite( iterator.next() ); } charSpriteMap.clear(); graphics.disposeTexture( textureId ); textureId = -1; } private final class InternalSpriteData implements SpriteData { private final FontAsset fontAsset; private final Rectangle region; public InternalSpriteData( FontAsset fontAsset, Rectangle region ) { super(); this.fontAsset = fontAsset; this.region = region; } @Override public final int getTextureId() { return fontAsset.textureId; } @Override public final Rectangle getTextureRegion() { return region; } @Override public final <A> A getDynamicAttribute( AttributeKey<A> key ) { return fontAsset.getDynamicAttribute( key ); } @Override public final boolean isHorizontalFlip() { return false; } @Override public final boolean isVerticalFlip() { return false; } } } <file_sep>/src/main/java/com/inari/firefly/control/behavior/EBehavoir.java package com.inari.firefly.control.behavior; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.inari.firefly.component.attr.AttributeKey; import com.inari.firefly.component.attr.AttributeMap; import com.inari.firefly.control.behavior.Action.ActionState; import com.inari.firefly.entity.EntityComponent; public final class EBehavoir extends EntityComponent { public static final EntityComponentTypeKey<EBehavoir> TYPE_KEY = EntityComponentTypeKey.create( EBehavoir.class ); public static final AttributeKey<Integer> ROOT_NODE_ID = AttributeKey.createInt( "rootNodeId", EBehavoir.class ); public static final AttributeKey<String> ROOT_NODE_NAME = AttributeKey.createString( "rootNodeName", EBehavoir.class ); private int rootNodeId; private final Map<Integer, Integer> nodeMapping = new HashMap<Integer, Integer>(); int runningActionId; ActionState actionState; protected EBehavoir( EntityComponentTypeKey<?> indexedTypeKey ) { super( indexedTypeKey ); resetAttributes(); } public final int getRootNodeId() { return rootNodeId; } public final void setRootNodeId( int rootNodeId ) { this.rootNodeId = rootNodeId; } public final void setNodeMapping( int nodeId, int subNodeId ) { nodeMapping.put( nodeId, subNodeId ); } public final int getSubNodeMapping( int nodeId ) { if ( !nodeMapping.containsKey( nodeId ) ) { return -1; } return nodeMapping.get( nodeId ); } public final void removeNodeMapping( int nodeId ) { nodeMapping.remove( nodeId ); } public final void clearNodeMapping() { nodeMapping.clear(); } // public final void stepIn( int nodeId ) { // pathToRoot.add( nodeId ); // } // // public final int stepOut() { // if ( pathToRoot.size() <= 0 ) { // return -1; // } // // return pathToRoot.removeAt( pathToRoot.size() - 1 ); // } // // final int getActiveNodeId() { // if ( actionState != ActionState.RUNNING ) { // return rootNodeId; // } // // if ( pathToRoot.isEmpty() ) { // return rootNodeId; // } // // return pathToRoot.get( pathToRoot.size() - 1 ); // } public final ActionState getActionState() { return actionState; } final void setActionState( ActionState actionState ) { this.actionState = actionState; } @Override public final Set<AttributeKey<?>> attributeKeys() { return new HashSet<AttributeKey<?>>( Arrays.asList( ROOT_NODE_ID, ROOT_NODE_NAME ) ); } @Override public final void fromAttributes( AttributeMap attributes ) { rootNodeId = attributes.getIdForName( ROOT_NODE_NAME, ROOT_NODE_ID, BehaviorNode.TYPE_KEY, rootNodeId ); } @Override public final void toAttributes( AttributeMap attributes ) { attributes.put( ROOT_NODE_ID, rootNodeId ); } @Override public final void resetAttributes() { rootNodeId = -1; actionState = ActionState.SUCCESS; nodeMapping.clear(); runningActionId = -1; } } <file_sep>/src/main/java/com/inari/firefly/control/ControllerSystem.java /******************************************************************************* * Copyright (c) 2015 - 2016, <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.inari.firefly.control; import java.util.Iterator; import com.inari.commons.StringUtils; import com.inari.commons.lang.list.DynArray; import com.inari.firefly.system.FFContext; import com.inari.firefly.system.UpdateEvent; import com.inari.firefly.system.UpdateEventListener; import com.inari.firefly.system.component.ComponentSystem; import com.inari.firefly.system.component.SystemBuilderAdapter; import com.inari.firefly.system.component.SystemComponent.SystemComponentKey; import com.inari.firefly.system.component.SystemComponentBuilder; public final class ControllerSystem extends ComponentSystem<ControllerSystem> implements UpdateEventListener { public static final FFSystemTypeKey<ControllerSystem> SYSTEM_KEY = FFSystemTypeKey.create( ControllerSystem.class ); private static final SystemComponentKey<?>[] SUPPORTED_COMPONENT_TYPES = new SystemComponentKey[] { Controller.TYPE_KEY }; private final DynArray<Controller> controller; ControllerSystem() { super( SYSTEM_KEY ); controller = DynArray.create( Controller.class, 20, 10 ); } @Override public void init( FFContext context ) { super.init( context ); context.registerListener( UpdateEvent.TYPE_KEY, this ); } @Override public final void dispose( FFContext context ) { context.disposeListener( UpdateEvent.TYPE_KEY, this ); clear(); } public final Controller getController( int controllerId ) { if ( !controller.contains( controllerId ) ) { return null; } return controller.get( controllerId ); } public final <T extends Controller> T getControllerAs( int controllerId, Class<T> controllerType ) { Controller c = getController( controllerId ); if ( c == null ) { return null; } return controllerType.cast( c ); } public final <T extends Controller> T getControllerAs( String controllerName, Class<T> controllerType ) { Controller c = getController( getControllerId( controllerName ) ); if ( c == null ) { return null; } return controllerType.cast( c ); } public final void deleteController( int controllerId ) { if ( controllerId < 0 ) { return; } if ( !controller.contains( controllerId ) ) { return; } Controller removed = controller.remove( controllerId ); if ( removed != null ) { disposeSystemComponent( removed ); } } public final void deleteController( String name ) { deleteController( getControllerId( name ) ); } public final int getControllerId( String name ) { if ( StringUtils.isBlank( name ) ) { return -1; } for ( Controller c : controller ) { if ( name.equals( c.getName() ) ) { return c.index(); } } return -1; } public final void addControlledComponentId( int controllerId, int componentId ) { if ( !controller.contains( controllerId ) ) { return; } controller.get( controllerId ).addComponentId( componentId ); } public final void removeControlledComponentId( int controllerId, int componentId ) { if ( !controller.contains( controllerId ) ) { return; } controller.get( controllerId ).removeComponentId( componentId ); } public final void clear() { for ( Controller c : controller ) { disposeSystemComponent( c ); } controller.clear(); } @Override public final void update( UpdateEvent event ) { for ( int i = 0; i < controller.capacity(); i++ ) { Controller c = controller.get( i ); if ( c != null ) { c.processUpdate(); } } } public final SystemComponentBuilder getControllerBuilder( Class<? extends Controller> componentType ) { return new ControllerBuilder( componentType ); } @Override public final SystemComponentKey<?>[] supportedComponentTypes() { return SUPPORTED_COMPONENT_TYPES; } @Override public final SystemBuilderAdapter<?>[] getSupportedBuilderAdapter() { return new SystemBuilderAdapter<?>[] { new ControllerBuilderAdapter() }; } private final class ControllerBuilder extends SystemComponentBuilder { private ControllerBuilder( Class<? extends Controller> componentType ) { super( context, componentType ); } @Override public final SystemComponentKey<Controller> systemComponentKey() { return Controller.TYPE_KEY; } @Override public final int doBuild( int componentId, Class<?> controllerType, boolean activate ) { Controller result = createSystemComponent( componentId, controllerType, context ); controller.set( result.index(), result ); if ( activate ) { result.setActive( true ); } return result.index(); } } private final class ControllerBuilderAdapter extends SystemBuilderAdapter<Controller> { private ControllerBuilderAdapter() { super( ControllerSystem.this, Controller.TYPE_KEY ); } @Override public final Controller get( int id ) { return controller.get( id ); } @Override public final Iterator<Controller> getAll() { return controller.iterator(); } @Override public final void delete( int id ) { deleteController( id ); } @Override public final int getId( String name ) { return getControllerId( name ); } @Override public final void activate( int id ) { get( id ).setActive( true ); } @Override public final void deactivate( int id ) { get( id ).setActive( false ); } @Override public final SystemComponentBuilder createComponentBuilder( Class<? extends Controller> componentType ) { if ( componentType == null ) { throw new IllegalArgumentException( "componentType is needed for SystemComponentBuilder for component: " + componentTypeKey().name() ); } return new ControllerBuilder( componentType ); } } } <file_sep>/README.md # Firefly [![Build Status](https://travis-ci.org/Inari-Soft/inari-firefly.svg?branch=master)](https://travis-ci.org/Inari-Soft/inari-firefly) Introduction Firefly is a top level 2D game engine framework for Java focusing on intuitive API build on stringent architecture and design. What makes it different to other java gaming frameworks is its focus on build and manage components and game objects within a component- entity-system approach and being independent from low level implementation(s). The main idea of Firefly is to have a top-level 2D game API that comes with a in-build Component-Entity-System architecture that helps organizing all the game-objects, data and assets in a well defined form and also helps a lot on keeping the game codebase as flexible as possible for changes, modify/adding new behavior during the development cycle. What is one of the most impressive benefits of a Component-Entity-System based architecture and design approach. Firefly is implemented on-top of other existing java gaming frameworks like lwjgl or libgdx with the flexibility to change the lower level implementation while reusing as much of the game code as possible. Key features - Strong backing on Component and Component-Entity-System approach. Almost everything within Firefly is a Component or a Entity (composite of components) or a System - Lightweight but power-full and easy extendable event system for communication between Systems. - Component Attributes Every Component in Firefly has a Attribute interface where its attributes (and meta information) can be accessed within attribute maps. This makes it possible to serialize the state of a component into what-ever format you need (XML, json...) and also create a Component from. Or the attribute mapping allows to access the attributes within a UI tool inspector for example. - Independent Lower Level interface definition There are a few interface definitions that must be implemented to implement Firefly within a lower level library like lwjgl or libgdx. All code that is written against the Firefly API is not affected by the change of the lower level library. Until now only a project with an implementation for libgdx is supported. - Stringent Component builder API and Context driven Firefly is context driven, this means no static method calls like Firefly.files.createAsset(...) and since almost everything within Firefly is a Component, there is a component builder that is used to build every kind of Component within the same way and with good code completion suggestions possibilities and a fluent interface. Code example: ``` context.getComponentBuilder( TextureAsset.TYPE ) .set( TextureAsset.NAME, "logoTexture" ) .set( TextureAsset.RESOURCE, "logo.png" ) .set( TextureAsset.WIDTH, 200 ) .set( TextureAsset.HEIGHT, 100 ) .build(); ``` - Indexing for Component types and instances for fast access Firefly comes with an indexing system that allows to index Java types (Class types) within a defined root type on one hand and on the other to index instances (objects) of a specified type. All Components, Entities and Systems are indexed by type and mostly, if needed also by instance to guarantee fast access. <file_sep>/src/main/java/com/inari/firefly/asset/AssetSystem.java /******************************************************************************* * Copyright (c) 2015 - 2016, <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.inari.firefly.asset; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.inari.commons.lang.IntIterator; import com.inari.commons.lang.list.DynArray; import com.inari.commons.lang.list.IntBag; import com.inari.firefly.FFInitException; import com.inari.firefly.system.FFContext; import com.inari.firefly.system.component.ComponentSystem; import com.inari.firefly.system.component.SystemBuilderAdapter; import com.inari.firefly.system.component.SystemComponent.SystemComponentKey; import com.inari.firefly.system.component.SystemComponentBuilder; public class AssetSystem extends ComponentSystem<AssetSystem> { public static final FFSystemTypeKey<AssetSystem> SYSTEM_KEY = FFSystemTypeKey.create( AssetSystem.class ); private static final SystemComponentKey<?>[] SUPPORTED_COMPONENT_TYPES = new SystemComponentKey[] { Asset.TYPE_KEY }; private final DynArray<Asset> assets; private final Map<String, Asset> nameMapping; AssetSystem() { super( SYSTEM_KEY ); assets = DynArray.create( Asset.class ); nameMapping = new HashMap<String, Asset>(); } @Override public void init( FFContext context ) { super.init( context ); } @Override public final void dispose( FFContext context ) { clear(); } public final Asset getAsset( String assetName ) { return nameMapping.get( assetName ); } public final <A extends Asset> A getAssetAs( String assetName, Class<A> subType ) { Asset asset = getAsset( assetName ); if ( asset == null ) { return null; } return subType.cast( asset ); } public final Asset getAsset( int assetId ) { if ( !assets.contains( assetId ) ) { return null; } return assets.get( assetId ); } public final <A extends Asset> A getAssetAs( int assetId, Class<A> subType ) { Asset asset = getAsset( assetId ); if ( asset == null ) { return null; } return subType.cast( asset ); } public final int getAssetInstanceId( int assetId ) { return getAssetInstanceId( getAsset( assetId ) ); } public final int getAssetInstanceId( String assetName ) { return getAssetInstanceId( getAsset( assetName ) ); } private int getAssetInstanceId( Asset asset ) { if ( !asset.loaded ) { throw new IllegalStateException( "Asset with name: " + asset.getName() + " not loaded" ); } return asset.getInstanceId(); } public final SystemComponentBuilder getAssetBuilder( Class<? extends Asset> assetType ) { if ( assetType == null ) { throw new IllegalArgumentException( "componentType is needed for SystemComponentBuilder for component: " + Asset.TYPE_KEY.name() ); } return new AssetBuilder( assetType ); } public final void loadAsset( String assetName ) { loadAsset( getAsset( assetName ) ); } public final void loadAsset( int assetId ) { loadAsset( getAsset( assetId ) ); } public final boolean isLoaded( int assetId ) { Asset asset = getAsset( assetId ); if ( asset == null ) { return false; } return asset.loaded; } public final boolean isLoaded( String assetName ) { Asset asset = getAsset( assetName ); if ( asset == null ) { return false; } return asset.loaded; } public final void disposeAsset( String assetName ) { Asset asset = getAsset( assetName ); if ( asset == null ) { return; } if ( !asset.loaded ) { return; } disposeAsset( asset ); } public final void disposeAsset( int assetId ) { Asset asset = getAsset( assetId ); if ( asset == null ) { return; } if ( !asset.loaded ) { return; } disposeAsset( asset ); } public final void deleteAsset( String assetName ) { Asset asset = getAsset( assetName ); if ( asset == null ) { return; } deleteAsset( asset ); } public final void deleteAsset( int assetId ) { Asset asset = getAsset( assetId ); if ( asset == null ) { return; } deleteAsset( asset ); } public final boolean hasAsset( String assetName ) { Asset asset = getAsset( assetName ); return ( asset != null ); } public final boolean hasAsset( int assetId ) { return assets.contains( assetId ); } public final int getAssetId( String assetName ) { Asset asset = getAsset( assetName ); if ( asset == null ) { throw new IllegalArgumentException( "No Asset with Name: " + assetName + " found." ); } return asset.index(); } public final void clear() { for ( Asset asset : assets ) { deleteAsset( asset ); } assets.clear(); nameMapping.clear(); } @Override public final SystemComponentKey<?>[] supportedComponentTypes() { return SUPPORTED_COMPONENT_TYPES; } @Override public final SystemBuilderAdapter<?>[] getSupportedBuilderAdapter() { return new SystemBuilderAdapter<?>[] { new AssetBuilderAdapter() }; } private IntBag disposeAsset( Asset asset ) { IntBag toDisposeFirst = findeAssetsToDisposeFirst( asset.index() ); if ( !toDisposeFirst.isEmpty() ) { IntIterator iterator = toDisposeFirst.iterator(); while ( iterator.hasNext() ) { Asset toDispose = getAsset( iterator.next() ); if ( toDispose.loaded ) { dispose( toDispose ); } } } dispose( asset ); return toDisposeFirst; } private IntBag findeAssetsToDisposeFirst( int assetId ) { IntBag result = new IntBag( 1, -1 ); for ( Asset asset : assets ) { IntBag disposeFirst = asset.dependsOn(); if ( disposeFirst != null ) { IntIterator iterator = disposeFirst.iterator(); while ( iterator.hasNext() ) { int next = iterator.next(); if ( next == assetId ) { result.add( next ); break; } } } } return result; } private void deleteAsset( Asset asset ) { if ( asset.loaded ) { IntBag alsoDisposedAssets = disposeAsset( asset ); if ( alsoDisposedAssets != null ) { IntIterator iterator = alsoDisposedAssets.iterator(); while ( iterator.hasNext() ) { delete( iterator.next() ); } } } delete( asset.index() ); } private void delete( int assetId ) { Asset deleted = assets.remove( assetId ); if ( deleted == null ) { return; } nameMapping.remove( deleted.getName() ); context.notify( new AssetEvent( deleted, AssetEvent.Type.ASSET_DELETED ) ); deleted.dispose(); } private void dispose( Asset asset ) { asset.dispose( context ); context.notify( new AssetEvent( asset, AssetEvent.Type.ASSET_DISPOSED ) ); asset.loaded = false; } private void loadAsset( Asset asset ) { IntBag loadFirst = asset.dependsOn(); if ( loadFirst != null ) { IntIterator iterator = loadFirst.iterator(); while ( iterator.hasNext() ) { Asset assetToLoadFirst = getAsset( iterator.next() ); if ( !assetToLoadFirst.loaded ) { load( assetToLoadFirst ); } } } load( asset ); } private void load( Asset asset ) { asset.load( context ); context.notify( new AssetEvent( asset, AssetEvent.Type.ASSET_LOADED ) ); asset.loaded = true; } private final class AssetBuilder extends SystemComponentBuilder { private AssetBuilder( Class<? extends Asset> componentType ) { super( context, componentType ); } @Override public final SystemComponentKey<Asset> systemComponentKey() { return Asset.TYPE_KEY; } @Override public int doBuild( int componentId, Class<?> componentType, boolean activate ) { Asset asset = createSystemComponent( componentId, componentType, context ); if ( nameMapping.containsKey( asset.getName() ) ) { throw new FFInitException( "There is already a Asset with name: " + asset.getName() ); } assets.set( asset.index(), asset ); String name = asset.getName(); if ( name == null ) { asset.setName( context.createNextNoName() ); name = asset.getName(); } nameMapping.put( name, asset ); context.notify( new AssetEvent( asset, AssetEvent.Type.ASSET_CREATED ) ); if ( activate ) { load( asset ); } return asset.index(); } } private final class AssetBuilderAdapter extends SystemBuilderAdapter<Asset> { private AssetBuilderAdapter() { super( AssetSystem.this, Asset.TYPE_KEY ); } @Override public final SystemComponentBuilder createComponentBuilder( Class<? extends Asset> assetType ) { return getAssetBuilder( assetType ); } @Override public final Asset get( int id ) { return getAsset( id ); } @Override public final void delete( int id ) { deleteAsset( id ); } @Override public final Iterator<Asset> getAll() { return assets.iterator(); } @Override public final int getId( String name ) { return getAssetId( name ); } @Override public final void activate( int id ) { loadAsset( id ); } @Override public final void deactivate( int id ) { disposeAsset( id ); } } } <file_sep>/src/main/java/com/inari/firefly/system/utils/Loadable.java package com.inari.firefly.system.utils; import com.inari.firefly.system.FFContext; public interface Loadable { boolean isLoaded(); Disposable load( FFContext context ); } <file_sep>/src/main/java/com/inari/firefly/physics/collision/ContactEvent.java package com.inari.firefly.physics.collision; import com.inari.commons.event.Event; public final class ContactEvent extends Event<ContactEventListener> { public static final EventTypeKey TYPE_KEY = createTypeKey( ContactEvent.class ); int entityId; ContactEvent() { super( TYPE_KEY ); } @Override protected final void notify( ContactEventListener listener ) { listener.onContact( this ); } } <file_sep>/src/main/java/com/inari/firefly/system/external/FFGraphics.java /******************************************************************************* * Copyright (c) 2015 - 2016, <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.inari.firefly.system.external; import com.inari.commons.geom.Rectangle; import com.inari.commons.lang.list.DynArray; import com.inari.firefly.graphics.ShaderAsset; import com.inari.firefly.graphics.SpriteRenderable; import com.inari.firefly.graphics.view.View; import com.inari.firefly.graphics.view.ViewEventListener; import com.inari.firefly.system.utils.FFContextInitiable; public interface FFGraphics extends FFContextInitiable, ViewEventListener { int createTexture( TextureData data ); void disposeTexture( int textureId ); int createSprite( SpriteData data ); void disposeSprite( int spriteId ); int createShader( ShaderAsset shaderAsset ); void disposeShader( int shaderAssetId ); int getScreenWidth(); int getScreenHeight(); void startRendering( View view, boolean clear ); void renderSprite( SpriteRenderable renderableSprite, float xpos, float ypos ); void renderSprite( SpriteRenderable renderableSprite, float xpos, float ypos, float scale ); void renderSprite( SpriteRenderable renderableSprite, TransformData tranform ); void renderShape( ShapeData data ); void renderShape( ShapeData data, TransformData tranform ); void endRendering( View view ); void flush( DynArray<View> virtualViews ); byte[] getScreenshotPixels( Rectangle area ); } <file_sep>/src/main/java/com/inari/firefly/graphics/text/TextRenderer.java package com.inari.firefly.graphics.text; import com.inari.commons.graphics.RGBColor; import com.inari.commons.lang.indexed.IndexedTypeKey; import com.inari.firefly.asset.AssetSystem; import com.inari.firefly.graphics.BaseRenderer; import com.inari.firefly.graphics.BlendMode; import com.inari.firefly.graphics.SpriteRenderable; public abstract class TextRenderer extends BaseRenderer { public static final SystemComponentKey<TextRenderer> TYPE_KEY = SystemComponentKey.create( TextRenderer.class ); protected TextSystem textSystem; protected AssetSystem assetSystem; TextRenderer( int id ) { super( id ); } @Override public void init() { super.init(); textSystem = context.getSystem( TextSystem.SYSTEM_KEY ); assetSystem = context.getSystem( AssetSystem.SYSTEM_KEY ); } @Override public final IndexedTypeKey indexedTypeKey() { return TYPE_KEY; } final TextRenderable textRenderable = new TextRenderable(); final class TextRenderable implements SpriteRenderable { int spriteId; RGBColor tintColor; BlendMode blendMode; int shaderId; @Override public final int getSpriteId() { return spriteId; } @Override public final RGBColor getTintColor() { return tintColor; } @Override public final BlendMode getBlendMode() { return blendMode; } @Override public final int getOrdering() { return 0; } @Override public final int getShaderId() { return shaderId; } } } <file_sep>/src/main/java/com/inari/firefly/system/NameMapping.java package com.inari.firefly.system; public final class NameMapping { public final String name1; public final String name2; private final int hashCode; public NameMapping( String name1, String name2 ) { this.name1 = name1; this.name2 = name2; final int prime = 31; int result = 1; result = prime * result + ( ( name1 == null ) ? 0 : name1.hashCode() ); result = prime * result + ( ( name2 == null ) ? 0 : name2.hashCode() ); hashCode = result; } public final String getName1() { return name1; } public final String getName2() { return name2; } @Override public int hashCode() { return hashCode; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; NameMapping other = (NameMapping) obj; if ( name1 == null ) { if ( other.name1 != null ) return false; } else if ( !name1.equals( other.name1 ) ) return false; if ( name2 == null ) { if ( other.name2 != null ) return false; } else if ( !name2.equals( other.name2 ) ) return false; return true; } } <file_sep>/src/main/java/com/inari/firefly/control/task/TaskSystem.java /******************************************************************************* * Copyright (c) 2015 - 2016, <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.inari.firefly.control.task; import java.util.Iterator; import com.inari.commons.lang.list.DynArray; import com.inari.firefly.system.FFContext; import com.inari.firefly.system.component.ComponentSystem; import com.inari.firefly.system.component.SystemBuilderAdapter; import com.inari.firefly.system.component.SystemComponent.SystemComponentKey; import com.inari.firefly.system.component.SystemComponentBuilder; public final class TaskSystem extends ComponentSystem<TaskSystem> { public static final FFSystemTypeKey<TaskSystem> SYSTEM_KEY = FFSystemTypeKey.create( TaskSystem.class ); private static final SystemComponentKey<?>[] SUPPORTED_COMPONENT_TYPES = new SystemComponentKey[] { Task.TYPE_KEY, }; private final DynArray<Task> tasks; TaskSystem() { super( SYSTEM_KEY ); tasks = DynArray.create( Task.class, 20, 10 ); } @Override public final void init( FFContext context ) { super.init( context ); context.registerListener( TaskSystemEvent.TYPE_KEY, this ); } @Override public final void dispose( FFContext context ) { context.disposeListener( TaskSystemEvent.TYPE_KEY, this ); clear(); } public final Task getTask( int taskId ) { if ( !tasks.contains( taskId ) ) { return null; } return tasks.get( taskId ); } public final <T extends Task> T getTaskAs( int taskId, Class<T> subType ) { Task task = getTask( taskId ); if ( task == null ) { return null; } return subType.cast( task ); } public final void clear() { for ( Task task : tasks ) { disposeSystemComponent( task ); } tasks.clear(); } public final int getTaskId( String taskName ) { for ( int i = 0; i < tasks.capacity(); i++ ) { if ( !tasks.contains( i ) ) { continue; } Task task = tasks.get( i ); if ( task.getName().equals( taskName ) ) { return i; } } return -1; } public final void deleteTask( int taskId ) { Task task = tasks.remove( taskId ); if ( task != null ) { disposeSystemComponent( task ); } } public final void runTask( int taskId ) { if ( !tasks.contains( taskId ) ) { return; } Task task = tasks.get( taskId ); task.runTask(); if ( task.removeAfterRun() && tasks.contains( taskId ) ) { tasks.remove( taskId ); } } public final SystemComponentBuilder getTaskBuilder( Class<? extends Task> componentType ) { if ( componentType == null ) { throw new IllegalArgumentException( "componentType is needed for SystemComponentBuilder for component: " + Task.TYPE_KEY.name() ); } return new TaskBuilder( componentType ); } @Override public final SystemComponentKey<?>[] supportedComponentTypes() { return SUPPORTED_COMPONENT_TYPES; } @Override public final SystemBuilderAdapter<?>[] getSupportedBuilderAdapter() { return new SystemBuilderAdapter<?>[] { new TaskBuilderAdapter() }; } private final class TaskBuilder extends SystemComponentBuilder { private TaskBuilder( Class<? extends Task> componentType ) { super( context, componentType ); } @Override public final SystemComponentKey<Task> systemComponentKey() { return Task.TYPE_KEY; } @Override public final int doBuild( int componentId, Class<?> taskType, boolean activate ) { Task task = createSystemComponent( componentId, taskType, context ); tasks.set( task.index(), task ); return task.index(); } } private final class TaskBuilderAdapter extends SystemBuilderAdapter<Task> { private TaskBuilderAdapter() { super( TaskSystem.this, Task.TYPE_KEY ); } @Override public final Task get( int id ) { return tasks.get( id ); } @Override public final Iterator<Task> getAll() { return tasks.iterator(); } @Override public final void delete( int id ) { deleteTask( id ); } @Override public final int getId( String name ) { return getTaskId( name ); } @Override public final void activate( int id ) { runTask( id ); } @Override public final void deactivate( int id ) { throw new UnsupportedOperationException( componentTypeKey() + " is not activable" ); } @Override public final SystemComponentBuilder createComponentBuilder( Class<? extends Task> componentType ) { return getTaskBuilder( componentType ); } } } <file_sep>/src/main/java/com/inari/firefly/graphics/text/DefaultTextRenderer.java package com.inari.firefly.graphics.text; import com.inari.commons.lang.indexed.IndexedTypeSet; import com.inari.commons.lang.list.DynArray; import com.inari.firefly.graphics.ETransform; import com.inari.firefly.system.RenderEvent; public final class DefaultTextRenderer extends TextRenderer { protected final ExactTransformDataCollector transformCollector = new ExactTransformDataCollector(); protected DefaultTextRenderer( int id ) { super( id ); } @Override public final void render( RenderEvent event ) { int viewId = event.getViewId(); int layerId = event.getLayerId(); if ( !textSystem.hasTexts( viewId ) ) { return; } DynArray<IndexedTypeSet> textsToRender = textSystem.getTexts( viewId, layerId ); if ( textsToRender == null ) { return; } for ( int i = 0; i < textsToRender.capacity(); i++ ) { IndexedTypeSet components = textsToRender.get( i ); if ( components == null ) { continue; } EText text = components.get( EText.TYPE_KEY ); int rendererId = text.getRendererId(); if ( rendererId >= 0 && rendererId != index() ) { continue; } ETransform transform = components.get( ETransform.TYPE_KEY ); FontAsset font = assetSystem.getAssetAs( text.getFontAssetId(), FontAsset.class ); char[] chars = text.getText().toCharArray(); textRenderable.blendMode = text.getBlendMode(); textRenderable.tintColor = text.getTintColor(); textRenderable.shaderId = text.getShaderId(); transformCollector.set( transform ); float horizontalStep = ( font.getCharWidth() + font.getCharSpace() ) * transform.getScalex(); float verticalStep = ( font.getCharHeight() + font.getLineSpace() ) * transform.getScaley(); for ( char character : chars ) { if ( character == '\n' ) { transformCollector.xpos = transform.getXpos(); transformCollector.ypos += verticalStep; continue; } if ( character == ' ' ) { transformCollector.xpos += horizontalStep; continue; } textRenderable.spriteId = font.getSpriteId( character ); render( textRenderable, transformCollector ); transformCollector.xpos += horizontalStep; } } } } <file_sep>/src/main/java/com/inari/firefly/system/component/ComponentSystemAdapter.java package com.inari.firefly.system.component; public interface ComponentSystemAdapter<C extends SystemComponent> { int getId( String name ); C get( int id ); void activate( int id ); void deactivate( int id ); void delete( int id ); }
237d0200908f75488125a1df3658a93ba26af650
[ "Markdown", "Java" ]
22
Java
LittleDevilGames/inari-firefly
da04364474be9b0c2095161ea2e4a30650a555be
873e883105203ba08c3f1f07052a2b9912117849
refs/heads/master
<file_sep># deebot-alerter Alert me when my deebot starts vacuuming <file_sep>package main import ( "encoding/xml" "fmt" "log" "os" "reflect" "time" ifttt "github.com/lorenzobenvenuti/ifttt" vacbot "github.com/skburgart/go-vacbot" ) const ( CleanModeAuto = "auto" CleanModeEdge = "border" CleanModeSpot = "spot" CleanModeSingleRoom = "singleRoom" CleanModeStop = "stop" ) var iftttKey = os.Getenv("IFTTT_KEY") var iftttEvent = os.Getenv("IFTTT_EVENT") var RunningModes = []string{CleanModeAuto, CleanModeEdge, CleanModeSpot, CleanModeSingleRoom} var client = vacbot.NewFromConfigFile("./config") type Clean struct { CleanType string `xml:"type,attr"` } type Control struct { Ret string `xml:"ret,attr"` Clean Clean `xml:"clean"` TD string `xml:"td,attr"` } type XmlResult struct { XMLName xml.Name `xml:"query"` Ctl Control `xml:"ctl"` } var previousStatus = "stop" func contains(a []string, x string) bool { for _, n := range a { if x == n { return true } } return false } func main() { iftttClient := ifttt.NewIftttClient(iftttKey) callback := func(result interface{}, err error) { if err != nil { log.Printf("FAIL - %s", err) } if result != nil { resultValue := reflect.ValueOf(result) _, ok := resultValue.Type().FieldByName("Query") if ok { battery := reflect.ValueOf(result).FieldByName("Query").Bytes() var xmlResult = XmlResult{} batteryString := string(battery[:]) if batteryString != "" { // fmt.Println(batteryString) err := xml.Unmarshal([]byte(battery), &xmlResult) if err != nil { fmt.Printf("error: %v", err) return } if xmlResult.Ctl.TD != "" { return } if xmlResult.Ctl.Clean.CleanType == CleanModeStop && previousStatus != CleanModeStop { previousStatus = CleanModeStop message := "Stopping" fmt.Println(message) iftttClient.Trigger(iftttEvent, []string{message}) } else if contains(RunningModes, xmlResult.Ctl.Clean.CleanType) && !contains(RunningModes, previousStatus) { fmt.Println(batteryString) previousStatus = xmlResult.Ctl.Clean.CleanType message := fmt.Sprintf("Started Running in Mode %s", previousStatus) fmt.Println(message) iftttClient.Trigger(iftttEvent, []string{message}) } else { } } } } } fiveMinuteTicker := time.NewTicker(20 * time.Second) go func() { for _ = range fiveMinuteTicker.C { client.FetchCleanState() } }() // call initial call client.FetchCleanState() go client.RecvHandler(callback) fmt.Scanln() fiveMinuteTicker.Stop() }
0e1fa65b58ac8f7631b3d96bfa9b06c619e3edd0
[ "Markdown", "Go" ]
2
Markdown
securingsincity/deebot-alerter
eff531d80526459c9f5228639d480a428ed1857a
60cf35180d07258b0be5859f6504af3f7fff3117
refs/heads/master
<repo_name>GabrielAfflitto/job-tracker<file_sep>/spec/features/jobs/user_deletes_a_job_spec.rb require 'rails_helper' describe "User can delete a job" do scenario "user can delete a job and redirect to company jobs page" do company = Company.create!(name: "ESPN") category = Category.create!(title: "Web Development") company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver", category: category) # company.jobs.create!(title: "QA Analyst", level_of_interest: 70, city: "New York City") visit company_jobs_path(company.id) expect(current_path).to eq(company_jobs_path(company.id)) expect(company.jobs.count).to eq(1) click_link "Delete" expect(current_path).to eq(company_jobs_path(company.id)) expect(company.jobs.count).to eq(0) end end <file_sep>/spec/models/contact_spec.rb require 'rails_helper' describe Contact do describe "validations" do context "invalid attributes" do it "is invalid without a name" do company = Company.create!(name: "ESPN") contact = Contact.new(position: "Manager", email: "<EMAIL>", company: company) expect(contact).to be_invalid end it "is invalid without a position" do company = Company.create!(name: "ESPN") contact = Contact.new(name: "<NAME>", email: "<EMAIL>", company: company) expect(contact).to be_invalid end it "is invalid without an email" do company = Company.create!(name: "ESPN") contact = Contact.new(name: "<NAME>", position: "Manager", company: company) expect(contact).to be_invalid end it "is invalid without a company" do company = Company.create!(name: "ESPN") contact = Contact.new(name: "<NAME>", position: "Manager", email: "<EMAIL>") expect(contact).to be_invalid end end end end <file_sep>/spec/features/comments/user_can_create_new_comment_spec.rb require 'rails_helper' describe "When a user visits a single job page" do it "is presented with a form to create a comment about job" do company = Company.create!(name: "ESPN") category_1 = Category.create!(title: "Web Development") company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver", category: category_1) visit company_job_path(company, company.jobs.first) # binding.pry expect(page).to have_content("Leave a Comment") fill_in "comment[content]", with: "This is awesome" click_on "Create Comment" expect(current_path).to eq(company_job_path(company, company.jobs.first)) expect(page).to have_content("This is awesome") end end <file_sep>/spec/features/categories/user_can_see_one_category_spec.rb require 'rails_helper' describe "when the user visits a specific category page" do it "user sees a list of jobs in the category" do company = Company.create!(name: "Cash Money") category_1 = Category.create!(title: "Music") company.jobs.create!(title: "Rapper", description: "spit hot fyaa", level_of_interest: 4, city: "Denver", category_id: category_1.id) company.jobs.create!(title: "Producer", description: "beatz", level_of_interest: 4, city: "Denver", category_id: category_1.id) company.jobs.create!(title: "Hype Man", description: "free money", level_of_interest: 4, city: "Denver", category_id: category_1.id) visit category_path(category_1) expect(category_1.jobs.count).to eq(3) expect(page).to have_content("Rapper") expect(page).to have_content("Producer") expect(page).to have_content("Hype Man") end end <file_sep>/spec/features/categories/user_can_create_a_new_category_spec.rb require 'rails_helper' describe "user can create a new category" do it "is presented with a new category form" do visit new_category_path expect(current_path).to eq(new_category_path) fill_in "category[title]", with: "Music" click_button "Create" expect(current_path).to eq(category_path(Category.last.id)) expect(page).to have_content("Music") end it "it redirected to the user to the category form page if the category exists" do category = Category.create!(title: "Music") visit new_category_path expect(current_path).to eq(new_category_path) fill_in "category[title]", with: "Music" click_button "Create" # save_and_open_page expect(page).to have_content("Create a New Category Here!") end end <file_sep>/app/models/job.rb class Job < ApplicationRecord validates :title, :level_of_interest, :city, presence: true belongs_to :company belongs_to :category has_many :comments def self.order_by_city order(:city) end def self.order_by_level_of_interest order(:level_of_interest) end def self.count_of_jobs_by_level_of_interest group(:level_of_interest).order("count_id DESC").count(:id) end def self.highest_average_level_of_interest_by_company company_averages = group(:company_id).average(:level_of_interest).invert.sort company_averages[3..5] end end <file_sep>/app/controllers/jobs_search_controller.rb class JobsSearchController < ApplicationController def index @jobs = Job.all if params[:sort] == "location" @jobs = Job.order_by_city elsif params[:sort] == "interest" @jobs = Job.order_by_level_of_interest elsif params[:location] @jobs = Job.where(city: params[:location]) else @jobs = Job.all end end def dashboard @jobs = Job.all end end <file_sep>/spec/features/categories/user_can_see_all_categories_spec.rb require 'rails_helper' describe "User can see all categories" do it "shows the index page of all categories" do category_1 = Category.create!(title: "Music") category_2 = Category.create!(title: "Art") visit categories_path expect(page).to have_content("Music") expect(page).to have_content("Art") end it "each category has a delete link" do category_1 = Category.create!(title: "Music") visit categories_path expect(page).to have_content("Music") expect(Category.count).to eq(1) click_link "Delete" expect(Category.count).to eq(0) end it "each category has an edit link" do category_1 = Category.create!(title: "Music") visit categories_path click_link "Edit" expect(current_path).to eq(edit_category_path(category_1.id)) fill_in "category[title]", with: "Construction" click_button "Update" expect(current_path).to eq(categories_path) expect(page).to have_content("Construction") end end <file_sep>/spec/features/contacts/user_can_create_a_contact_spec.rb require 'rails_helper' describe "when a user visits a company show page" do it "is presented with a form to create a contact" do company = Company.create!(name: "ESPN") visit company_jobs_path(company) expect(page).to have_content("Enter your contact information") fill_in "contact[name]", with: "<NAME>" fill_in "contact[position]", with: "Manager" fill_in "contact[email]", with: "<EMAIL>" click_on "Create Contact" expect(current_path).to eq(company_jobs_path(company)) expect(page).to have_content("<NAME>") expect(page).to have_content("Manager") expect(page).to have_content("<EMAIL>") end end <file_sep>/spec/features/jobs/user_updates_a_job_spec.rb require 'rails_helper' describe "User can edit a job" do scenario "user sees the form page for one company" do company = Company.create!(name: "ESPN") category = Category.create!(title: "Web Development") job = company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver", category: category) visit edit_company_job_path(job.company, job) expect(current_path).to eq(edit_company_job_path(job.company, job)) fill_in "job[title]", with: "Developer" fill_in "job[description]", with: "Not fun!" fill_in "job[level_of_interest]", with: 80 fill_in "job[city]", with: "Lakewood" select("Web Development", from: "job_category_id").select_option click_button "Update Job" expect(current_path).to eq(company_job_path(job.company_id, job.id)) expect(page).to have_content("Not fun!") expect(page).to have_content("80") expect(page).to have_content("Lakewood") expect(page).to have_content("Developer") end end
c8d5cae7654090a54f9d7c47bbddf9ff64a3b7c6
[ "Ruby" ]
10
Ruby
GabrielAfflitto/job-tracker
bbf140b2982acd4a45c0c2bbbbff3a7a6392ca11
c58b7a90639b1981a96e9b8aaa30c83ba754ce85
refs/heads/master
<file_sep># Cocktail Web Application using Shiny STA 141B UC Davis Spring 2020 <href> https://nikhthota.shinyapps.io/cocktail-web-app/ </href> This app uses the Cocktail DB API to get information on 595 cocktail recipes. The user can get a random cocktail recipe by clicking the 'Random' button or filter by one of the following: ingredients, type of drink, type of glass for the drink, or by first letter of the drink. The user can also see how their drink compares to the other drinks in the data base in the second 'How does my drink compare?' tab which highlights the user's drink in a bar graph comparing the drink in four categories: the number of ingredients in the recipe, the type of glass it uses, the type of drink, and by first letter of the drink recipe. <file_sep> library(shiny) library(jsonlite) library(httr) library(tidyverse) library(styler) library(shinyjs) # Getting API Key for Cocktail DB stored in .Renviron file readRenviron(".Renviron") api_key = Sys.getenv("API_KEY") ifAlcohol_options <- fromJSON(str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/list.php?a=list", api_key = api_key))$drinks$strAlcoholic glass_options <- fromJSON(str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/list.php?g=list", api_key = api_key))$drink$strGlass firstChar_options <- c(toupper(letters), 0:9, "'") ingred_options <- sort(fromJSON(str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/list.php?i=list", api_key = api_key))$drinks$strIngredient1) shinyUI(fluidPage( useShinyjs(), # Application title headerPanel("Cocktail Recipe App"), sidebarLayout( sidebarPanel( wellPanel( h5("Find me a random recipe:"), actionButton("random", "Random!"), ), h4("Select one of the following filters to apply:"), wellPanel( h5("Filter by Ingredients:"), selectizeInput("mult_ingredients", label = NULL, choices = ingred_options, multiple = TRUE) ), wellPanel( h5("Filter by Type of Drink:"), selectInput("ifAlcohol", label = NULL, choices = c("Select a Type", ifAlcohol_options)) ), wellPanel( h5("Filter by Type of Glass:"), selectInput("glassType", label = NULL, choices = c("Select a Type", glass_options)) ), wellPanel( h5("Filter by First Letter/Character:"), selectInput("byLetter", label = NULL, choices = c("Select a Letter", firstChar_options)) ), wellPanel( h5(strong("Matching Recipes:")), h6("(by most recently selected filter)"), uiOutput("recipeMatchInputs"), class = "wellPanelRecipe", id = "wP-R" ) ), mainPanel( tabsetPanel(type = "tabs", tabPanel("Recipe", br(), fluidRow( column( 6, textOutput("recipeTitle"), br(), wellPanel(tableOutput("recipeIngr_Measure")), textOutput("recipeInstructions") ), column( 6, htmlOutput("recipeImage")#, #verbatimTextOutput("testInputOptions") ) ) ), tabPanel("How does my drink compare?", br(), fluidRow( column(6, plotOutput("numIngredPlot")), column(6, plotOutput("byDrinkPlot")) ), fluidRow( column(12, plotOutput("byLetterPlot")) ), fluidRow( column(12, plotOutput("byGlassPlot")) ) ) #close compare tabPanel ) #close tabsetPanel ) #close Main Panel ),#close sidebar Layout tags$head(tags$style("#recipeTitle{color: black; font-size: 18px; font-style: bold;}"), tags$style("#wP-R{background-color: #c9d7e8;}"), tags$style("#matchingRecipeHeader{font-size: 14px; font-style: bold;}") ) )) <file_sep>library(shiny) library(jsonlite) library(httr) library(tidyverse) library(styler) library(pool) library(curl) readRenviron(".Renviron") api_key = Sys.getenv("API_KEY") #letters_and_num <- c(0:9, letters, "'") #drink_details_df <- data.frame() #for (i in letters_and_num) { # url <- str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/search.php?f={letter}", # api_key = Sys.getenv("API_KEY"), letter = i) # drinks_details <- fromJSON(url)$drinks # drink_details_df <- rbind(drink_details_df, drinks_details) # print("reading lines") #} drink_details_df <- read.csv("drink_details.csv") drink_details_df <- drink_details_df %>% select(idDrink, strDrink, strCategory, strAlcoholic, strGlass, strInstructions, strDrinkThumb, strIngredient1:strIngredient15, strMeasure1:strMeasure15) %>% mutate(across(starts_with("str"), na_if, "NA")) %>% mutate(across(starts_with("str"), na_if, "<NA>")) %>% mutate(across(starts_with("str"), na_if, "")) %>% mutate(across(starts_with("str"), na_if, '')) shinyServer(function(input, output, session) { ##### CREATE REACTIVE VALUES FOR RECIPES ---------------------- recipe <- reactiveValues(details = NULL) ##### RANDOM RECIPE GENERATION --- ----------------------------- # random recipe observeEvent(input$random, { print("random button clicked") recipe$details <- fromJSON(str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/random.php", api_key = api_key))$drinks }) ##### OBSERVEEVENT FOR FILTERING -------------------------------- # filter by ingredient observeEvent(input$mult_ingredients, { print("ingredients selection updated") req(!is.null(input$mult_ingredients)) multiple_ingreds <- str_replace_all(paste(input$mult_ingredients, collapse = ','), pattern = " ", replacement = "_") recipe$drinks <- fromJSON(str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/filter.php?i={ingr}", api_key = api_key, ingr = multiple_ingreds))$drinks }) # filter by type of category observeEvent(input$ifAlcohol, { print("type of category selection updated") req(!is.null(input$mult_ingredients)) if(input$ifAlcohol != "Select a type"){ recipe$drinks <- fromJSON(str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/filter.php?a={type}", api_key = api_key, type = str_replace_all(input$ifAlcohol, ' ', '_')))$drinks } }) # filter by type of glass observeEvent(input$glassType, { print("type of glass selection updated") req(!is.null(input$glassType)) if(input$glassType != "Select a type"){ recipe$drinks <- fromJSON(str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/filter.php?g={glass_type}", api_key = api_key, glass_type = str_replace_all(input$glassType, ' ', '_')))$drinks } }) # filter by first letter/digit observeEvent(input$byLetter, { print("letter selection updated") req(!is.null(input$byLetter)) if(input$byLetter != "Select a Letter") { recipe$drinks <- fromJSON(str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/search.php?f={letter}", api_key = api_key, letter = tolower(input$byLetter)))$drinks } }) # create a selectInput object that has all of the recipe names that match the selected filter output$recipeMatchInputs <- renderUI ({ req(!is.null(recipe$drinks)) print("drink matches showing") if(recipe$drinks != "None Found") { selectInput("recipeMatch", label = NULL, choices = recipe$drinks$idDrink %>% set_names(recipe$drinks$strDrink)) } else { print("No matching drinks found, try another filter!") } }) # When a recipe is selected, save the value in the reactiveValue observeEvent(input$recipeMatch, { print("recipe match selected") recipe$details <- fromJSON(str_glue("https://www.thecocktaildb.com/api/json/v2/{api_key}/lookup.php?i={recipe_id}", api_key = api_key, recipe_id = input$recipeMatch))$drinks }) output$testInputOptions <- renderPrint({ req(!is.null(recipe$drinks)) print("input options selected") recipe$drinks }) ##### RECIPE DETAILS PRINTED ON MAIN RECIPE TAB ----------------------- # print out the selected recipe title output$recipeTitle <- renderText ({ req(!is.null(recipe$details)) print("title updated") recipe$details$strDrink }) # print out the selected recipe ingredients and measurements output$recipeIngr_Measure <- renderTable({ req(!is.null(recipe$details)) drink <- recipe$details ingredients <- drink %>% mutate_if(is.logical, as.character) %>% mutate(across(starts_with("str"), na_if, "NA")) %>% mutate(across(starts_with("str"), na_if, "<NA>")) %>% mutate(across(starts_with("str"), na_if, "")) %>% dplyr::select(starts_with("strIngredient")) %>% pivot_longer(starts_with("strIngredient")) %>% drop_na() %>% mutate(Ingredient = value) %>% dplyr::select(Ingredient) len_ingred <- ingredients %>% dplyr::summarize(n = n()) %>% pull(n) # Get measurements from drink information measurements <- drink %>% mutate_if(is.logical, as.character) %>% mutate(across(starts_with("str"), na_if, "NA")) %>% mutate(across(starts_with("str"), na_if, "<NA>")) %>% mutate(across(starts_with("str"), na_if, "")) %>% dplyr::select(starts_with("strMeasure")) %>% pivot_longer(starts_with("strMeasure")) %>% replace_na(list(value = "See Instructions")) %>% slice_head(n = len_ingred) %>% mutate(Quantity = value) %>% dplyr::select(Quantity) # Combine and print as table cbind(ingredients, measurements) }) # print out the selected recipe instructions output$recipeInstructions <- renderText({ req(!is.null(recipe$details)) print("instructions updated") recipe$details$strInstructions }) # print out the selected recipe image from URL output$recipeImage <- renderText({ req(!is.null(recipe$details)) print("image updated") src = paste0(recipe$details$strDrinkThumb) paste0('<img src="', src,'" ', 'style="width:250px;height:250px;">') }) ##### PLOTS ON COMPARISON TAB ------------------------------------------- # bar plot by ingredient output$numIngredPlot <- renderPlot({ req(!is.null(recipe$details)) print("plotting num ingreds bar plot") drink <- recipe$details recipeID <- drink$idDrink num_ingred <- drink_details_df %>% select(idDrink, starts_with("strIngredient")) %>% mutate(numIngredients = rowSums(!is.na(.))-1) # Plot to show bar plot with the number of ingredients that they selected ggplot(data = num_ingred, aes(x = numIngredients, fill = factor(ifelse(numIngredients == (num_ingred %>% filter(idDrink == recipeID) %>% pull(numIngredients)), "Highlighted", "Normal")))) + geom_bar(show.legend = FALSE) + scale_fill_manual(name = "numIngredients", values=c("#7B0828","grey50")) + xlab("Number of Ingredients") + ylab("Number of Drinks") + ggtitle("How many ingredients are in my drink?") + theme(axis.text = element_text(size = rel(1.5))) }) # bar plot by letter output$byLetterPlot <- renderPlot({ req(!is.null(recipe$details)) print("plotting by letter bar plot") drink <- recipe$details recipeID <- drink$idDrink byLetter <- drink_details_df %>% select(idDrink, strDrink) %>% mutate(firstLetter = substr(strDrink, 1, 1)) ggplot(data = byLetter, aes(x = firstLetter, fill = factor(ifelse(firstLetter == (byLetter %>% filter(idDrink == recipeID) %>% pull(firstLetter)), "Highlighted", "Normal")))) + geom_bar(show.legend = FALSE) + scale_fill_manual(name = "firstLetter", values=c("#7B0828","grey50")) + xlab("Character") + ylab("Number of Drinks") + ggtitle("Drinks by First Character") + theme(axis.text = element_text(size = rel(1.5))) }) # bar plot by type of drink output$byDrinkPlot <- renderPlot({ req(!is.null(recipe$details)) print("plotting by type of drink plot") drink <- recipe$details recipeID <- drink$idDrink byDrink <- drink_details_df %>% select(idDrink, strAlcoholic) ggplot(data = byDrink, aes(x = strAlcoholic, fill = factor(ifelse(strAlcoholic == (byDrink %>% filter(idDrink == recipeID) %>% pull(strAlcoholic)), "Highlighted", "Normal")))) + geom_bar(show.legend = FALSE) + scale_fill_manual(name = "strAlcoholic", values=c("#7B0828","grey50")) + xlab("Type of Drink") + ylab("Number of Drinks") + ggtitle("Drinks by Type of Drink") + theme(axis.text.y = element_text(size = rel(1.5)), axis.text.x = element_text(size = rel(1.25))) }) # bar plot by glass output$byGlassPlot <- renderPlot({ req(!is.null(recipe$details)) print("plotting by glass plot") drink <- recipe$details recipeID <- drink$idDrink byGlass <- drink_details_df %>% select(idDrink, strGlass) ggplot(data = byGlass, aes(x = strGlass, fill = factor(ifelse(strGlass == (byGlass %>% filter(idDrink == recipeID) %>% pull(strGlass)), "Highlighted", "Normal")))) + geom_bar(show.legend = FALSE) + scale_fill_manual(name = "strGlass", values=c("#7B0828","grey50")) + xlab("Type of Glass") + ylab("Number of Drinks") + ggtitle("Drinks by Type of Glass") + theme(axis.text.x = element_text(angle = 33, size = rel(1.0)), axis.text.y = element_text(size = rel(1.5))) }) })
464095d5b5db867e399a8a9e6baeb56fee7856a5
[ "Markdown", "R" ]
3
Markdown
nikhthota/sta141b-project
5a20fe14db6e841411550f78c95460fad5cd174f
32daeaef7abda3198ed4a564ba3c90e764b7e6ba